r1234chen commited on
Commit
74de7fe
·
verified ·
1 Parent(s): 6b23b6b

Mirror public GitHub main c456a7d (24/25)

Browse files
.gitattributes CHANGED
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  runtime/h2_runtime/fonts/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
 
 
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  runtime/h2_runtime/fonts/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
62
+ runtime/native_runtime/fonts/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
runtime/native_runtime/engine/MODIFIED_FILE.py ADDED
The diff for this file is too large to render. See raw diff
 
runtime/native_runtime/font_aliases.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from PIL import ImageFont
3
+ def install(runtime_root):
4
+ if getattr(ImageFont,'_puzzlemix_font',False): return
5
+ old=ImageFont.truetype
6
+ local=Path(runtime_root)/'fonts'
7
+ def use(font,*a,**kw):
8
+ name=str(font).replace(chr(92),'/').rsplit('/',1)[-1].lower()
9
+ if name in ('consola.ttf','consolab.ttf'):
10
+ exact=local/name
11
+ font=str(exact if exact.is_file() else local/'DejaVuSansMono.ttf')
12
+ return old(font,*a,**kw)
13
+ ImageFont.truetype=use;ImageFont._puzzlemix_font=True
runtime/native_runtime/font_utils.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from PIL import ImageFont
3
+
4
+ _FONT = Path(__file__).resolve().parent / 'fonts' / 'DejaVuSansMono.ttf'
5
+
6
+ def load_font(size):
7
+ return ImageFont.FreeTypeFont(str(_FONT), max(9, int(size)))
runtime/native_runtime/fonts/DejaVuSansMono.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:602ec86b8948cfcd956482fe64f94c36c867770149ef2f791d4613f443bcecb3
3
+ size 340240
runtime/native_runtime/fonts/LICENSE_DEJAVU ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
2
+ Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
3
+
4
+ Bitstream Vera Fonts Copyright
5
+ ------------------------------
6
+
7
+ Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
8
+ a trademark of Bitstream, Inc.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of the fonts accompanying this license ("Fonts") and associated
12
+ documentation files (the "Font Software"), to reproduce and distribute the
13
+ Font Software, including without limitation the rights to use, copy, merge,
14
+ publish, distribute, and/or sell copies of the Font Software, and to permit
15
+ persons to whom the Font Software is furnished to do so, subject to the
16
+ following conditions:
17
+
18
+ The above copyright and trademark notices and this permission notice shall
19
+ be included in all copies of one or more of the Font Software typefaces.
20
+
21
+ The Font Software may be modified, altered, or added to, and in particular
22
+ the designs of glyphs or characters in the Fonts may be modified and
23
+ additional glyphs or characters may be added to the Fonts, only if the fonts
24
+ are renamed to names not containing either the words "Bitstream" or the word
25
+ "Vera".
26
+
27
+ This License becomes null and void to the extent applicable to Fonts or Font
28
+ Software that has been modified and is distributed under the "Bitstream
29
+ Vera" names.
30
+
31
+ The Font Software may be sold as part of a larger software package but no
32
+ copy of one or more of the Font Software typefaces may be sold by itself.
33
+
34
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
36
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
37
+ TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
38
+ FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
39
+ ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
40
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
41
+ THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
42
+ FONT SOFTWARE.
43
+
44
+ Except as contained in this notice, the names of Gnome, the Gnome
45
+ Foundation, and Bitstream Inc., shall not be used in advertising or
46
+ otherwise to promote the sale, use or other dealings in this Font Software
47
+ without prior written authorization from the Gnome Foundation or Bitstream
48
+ Inc., respectively. For further information, contact: fonts at gnome dot
49
+ org.
50
+
51
+ Arev Fonts Copyright
52
+ ------------------------------
53
+
54
+ Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
55
+
56
+ Permission is hereby granted, free of charge, to any person obtaining
57
+ a copy of the fonts accompanying this license ("Fonts") and
58
+ associated documentation files (the "Font Software"), to reproduce
59
+ and distribute the modifications to the Bitstream Vera Font Software,
60
+ including without limitation the rights to use, copy, merge, publish,
61
+ distribute, and/or sell copies of the Font Software, and to permit
62
+ persons to whom the Font Software is furnished to do so, subject to
63
+ the following conditions:
64
+
65
+ The above copyright and trademark notices and this permission notice
66
+ shall be included in all copies of one or more of the Font Software
67
+ typefaces.
68
+
69
+ The Font Software may be modified, altered, or added to, and in
70
+ particular the designs of glyphs or characters in the Fonts may be
71
+ modified and additional glyphs or characters may be added to the
72
+ Fonts, only if the fonts are renamed to names not containing either
73
+ the words "Tavmjong Bah" or the word "Arev".
74
+
75
+ This License becomes null and void to the extent applicable to Fonts
76
+ or Font Software that has been modified and is distributed under the
77
+ "Tavmjong Bah Arev" names.
78
+
79
+ The Font Software may be sold as part of a larger software package but
80
+ no copy of one or more of the Font Software typefaces may be sold by
81
+ itself.
82
+
83
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
84
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
85
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
86
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
87
+ TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
88
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
89
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
90
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
91
+ OTHER DEALINGS IN THE FONT SOFTWARE.
92
+
93
+ Except as contained in this notice, the name of Tavmjong Bah shall not
94
+ be used in advertising or otherwise to promote the sale, use or other
95
+ dealings in this Font Software without prior written authorization
96
+ from Tavmjong Bah. For further information, contact: tavmjong @ free
97
+ . fr.
98
+
99
+ $Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $
runtime/native_runtime/legacy_driver_transport.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import copy, json, math, types
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ def attach(driver, session):
7
+ if getattr(driver, 'shared_legacy_session', None) is not None:
8
+ raise RuntimeError('Driver already has a common executor')
9
+ required = ('act', 'a_open', 'a_close', 'a_take', 'a_unlock', 'a_use')
10
+ for name in required:
11
+ if getattr(type(session.esc), name) is not getattr(session.E.Escape, name):
12
+ raise RuntimeError('Common handler was replaced: ' + name)
13
+ prior = driver.execute
14
+
15
+ def execute(d, action, purpose='', allow_failure=False):
16
+ from observation1280 import validate_action
17
+ from unified_protocol import feedback
18
+ a = validate_action(action)
19
+ kind = a['action']
20
+ if kind == 'recall':
21
+ raise RuntimeError('Recall belongs to the shared episode/history layer')
22
+ if d.step >= d.cap:
23
+ raise RuntimeError('Action budget exhausted')
24
+ if d.clean is None:
25
+ raise RuntimeError('Native observation is missing')
26
+ from observation_group import begin, finalize
27
+ begin(session)
28
+ before = copy.deepcopy(d.game.snapshot())
29
+ step = d.step + 1
30
+ decision = d.run / 'steps' / ('%03d_decision_model.png' % step)
31
+ d.small.save(decision)
32
+ decision_images = list(d.current_observation_images) or [str(decision)]
33
+ d.step = step
34
+ d._legacy_action_step = step
35
+ d.current_action = copy.deepcopy(a)
36
+ d.current_hit = None
37
+ d.current_visual_feedback = []
38
+ if hasattr(session, 'extra_images'):
39
+ session.extra_images = []
40
+ result = feedback(kind, session.act(a))
41
+ if not result.get('images'):
42
+ e = session.esc
43
+ boxed, _ = session.C.shoot(e, 'common_current_result')
44
+ e._claw_photos = [boxed]
45
+ result = dict(result, images=[session.C._small(e, boxed)])
46
+ finalize(session, result.get('images', []))
47
+ e = session.esc
48
+ d.step = step
49
+ d.pos = np.asarray(e.pos, float).copy()
50
+ d.yaw = float(e.yaw)
51
+ d.pitch = math.radians(float(getattr(e, '_claw_pitch', 0.0)))
52
+ native = d.run / 'steps' / ('%03d_native.png' % step)
53
+ model = d.run / 'steps' / ('%03d_model.png' % step)
54
+ d.clean.save(native)
55
+ d.small.save(model)
56
+ images = []
57
+ for value in result.get('images', []):
58
+ p = Path(value)
59
+ if not p.is_file():
60
+ raise RuntimeError('Common executor returned a missing observation: ' + str(p))
61
+ with Image.open(p) as im:
62
+ if im.size != (640, 360):
63
+ raise RuntimeError('Common executor model observation is not640x360: ' + str(p))
64
+ images.append(str(p))
65
+ if not images:
66
+ images = [str(model)]
67
+ ids = result.get('action_ids') or result.get('action_ids_private') or {}
68
+ oid = ids.get('object', ids.get('target', ids.get('item')))
69
+ key = result.get('native_resolved_key_private') or getattr(session, 'oid_to_key', {}).get(oid)
70
+ if key is None and oid in e.objs:
71
+ sim = e.objs[oid]['sim']
72
+ key = getattr(session.backend, 'sim_to_key', {}).get(sim, sim)
73
+ if key is not None:
74
+ d.current_hit = {'key': key, 'source': 'actual_common_legacy_resolution'}
75
+ result = dict(result)
76
+ d.current_result = result
77
+ row = {'step': step, 'action': copy.deepcopy(a), 'result': result, 'before': before, 'after': copy.deepcopy(d.game.snapshot()), 'camera_position': d.pos.tolist(), 'camera_quaternion': d.quat.tolist(), 'pixel_hit_private': d.current_hit, 'decision_image': str(decision), 'decision_images': decision_images, 'model_image': str(model), 'native_image': str(native), 'model_images': images, 'common_executor': 'E.Escape.act -> C.act/_act_core', 'common_action_only': True}
78
+ d.rows.append(row)
79
+ d.current_observation_images = list(images)
80
+ d.save('trajectory.json', d.rows)
81
+ if d.writer is not None:
82
+ d.append(purpose or kind, 12)
83
+ d.packet()
84
+ if not result.get('ok') and (not allow_failure):
85
+ raise RuntimeError('Standard action rejected by common executor: ' + json.dumps({'action': a, 'result': result}, ensure_ascii=False, default=str))
86
+ return result
87
+ driver.execute = types.MethodType(execute, driver)
88
+ driver.shared_legacy_session = session
89
+ return {'execute': prior, 'session': session}
runtime/native_runtime/legacy_h2_bridge.py ADDED
@@ -0,0 +1,917 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import copy, hashlib, json, math, types, sys, re
3
+ import numpy as np
4
+ from legacy_rooms_bridge import RoomsBackend, RoomsSession, ObjectView, MotionJoint, UnsupportedBinding, install_mechanism_hooks, LinkedLockItem
5
+ from legacy_r01_pilot import quat_from, load_stack
6
+ BASE = Path(__file__).resolve().parent.parent
7
+
8
+ def _path(node):
9
+ return str(node['prim'].GetPath())
10
+ PUBLIC_CATEGORY_FIXTURES = {'R31': {'source_sha256': 'f2e383d98d3f2e5c82338f239f490792462d69c009d10d9aab71b3cfebdff327', 'items': {'film_a': 'numeral film', 'film_b': 'numeral film'}}, 'R43': {'source_sha256': '541a2560e6b66e5103eb4042a075d00e2dfa61cf396f0be78647b883c6ff7d5c', 'items': {'ta': 'route tile', 'tb': 'route tile', 'tc': 'route tile', 'td': 'route tile', **{'slot' + str(i): 'route slot' for i in range(4)}}, 'dual_press_inventory': ['ta', 'tb', 'tc', 'td'], 'non_press_receivers': ['slot' + str(i) for i in range(4)], 'non_item_receivers': ['slot' + str(i) for i in range(4)]}, 'R44': {'source_sha256': '31b27b340a4755fa7f8802f8d58f0347b0c24d53dec560a070bfde399a99b6f5', 'items': {'seat' + str(i): 'sample seat' for i in range(4)}, 'non_press_receivers': ['seat' + str(i) for i in range(4)], 'non_item_receivers': ['seat' + str(i) for i in range(4)]}}
11
+
12
+ def public_label(scene, key):
13
+ fixture = PUBLIC_CATEGORY_FIXTURES.get(getattr(scene, '_h2_source_id', None), {})
14
+ if fixture.get('source_sha256') == getattr(scene, '_h2_source_sha256', None) and key in fixture.get('items', {}):
15
+ return fixture['items'][key]
16
+ explicit = getattr(scene, '_h2_explicit_labels', {})
17
+ raw = str(explicit.get(key, scene.labels.get(key, str(key).replace('_', ' '))))
18
+ if key in explicit:
19
+ return raw.split(':', 1)[0].strip()
20
+ if re.fullmatch('\\d+-unit block', raw.strip(), re.I):
21
+ return 'weight block'
22
+ if 'figurine' in raw.lower():
23
+ return 'figurine'
24
+ short = raw.split(':', 1)[0].split(' with ', 1)[0]
25
+ short = re.sub('\\s*\\([^)]*\\)', '', short).strip()
26
+ if ':' in raw:
27
+ short = re.sub('\\s+[A-Z]$', '', short).strip()
28
+ return short or 'object'
29
+
30
+ def _record_printed_text():
31
+ from PIL import ImageDraw
32
+ original = ImageDraw.ImageDraw.text
33
+ if getattr(original, '_h2_print_metadata', False):
34
+ return
35
+
36
+ def text(draw, xy, value, *args, **kwargs):
37
+ depth = getattr(draw, '_h2_print_depth', 0)
38
+ draw._h2_print_depth = depth + 1
39
+ try:
40
+ result = original(draw, xy, value, *args, **kwargs)
41
+ finally:
42
+ draw._h2_print_depth = depth
43
+ if depth == 0 and str(value).strip():
44
+ image = draw._image
45
+ rows = getattr(image, '_h2_printed_rows', [])
46
+ rows.append(str(value))
47
+ image._h2_printed_rows = rows
48
+ return result
49
+ text._h2_print_metadata = True
50
+ ImageDraw.ImageDraw.text = text
51
+ from PIL import Image
52
+ original_rotate = Image.Image.rotate
53
+ original_resize = Image.Image.resize
54
+
55
+ def rotate(image, angle, *args, **kwargs):
56
+ result = original_rotate(image, angle, *args, **kwargs)
57
+ expand = kwargs.get('expand', args[1] if len(args) > 1 else False)
58
+ full = float(angle) % 180 == 0 or (float(angle) % 90 == 0 and (expand or image.width == image.height))
59
+ if full and hasattr(image, '_h2_printed_rows'):
60
+ result._h2_printed_rows = list(image._h2_printed_rows)
61
+ return result
62
+
63
+ def resize(image, *args, **kwargs):
64
+ result = original_resize(image, *args, **kwargs)
65
+ if hasattr(image, '_h2_printed_rows'):
66
+ result._h2_printed_rows = list(image._h2_printed_rows)
67
+ return result
68
+ Image.Image.rotate = rotate
69
+ Image.Image.resize = resize
70
+
71
+ def _node_visible(scene, node):
72
+ if not getattr(scene, 'shown', {}).get(id(node), True):
73
+ return False
74
+ if getattr(scene, '_h2_cpu_fixture', False):
75
+ return bool(node.get('fixture_visible', True))
76
+ from pxr import UsdGeom
77
+ return str(UsdGeom.Imageable(node['prim']).ComputeVisibility()) != 'invisible'
78
+
79
+ def _read_surfaces(scene):
80
+ screen_paths = {_path(n) for slot in getattr(scene, 'screens', {}).values() for n in slot.get('faces', {}).values()}
81
+ rows = {k: v for k, v in scene._h2_picture_prints.items() if _path(v['node']) not in screen_paths and v['text']}
82
+ rows.update(scene._h2_screen_prints)
83
+ return rows
84
+
85
+ def _read_target_rows(scene, node, key):
86
+ path = _path(node)
87
+ rows = _read_surfaces(scene)
88
+ exact = [r for r in rows.values() if _path(r['node']) == path]
89
+ if exact:
90
+ return exact
91
+ label = public_label(scene, key).lower()
92
+ words = (str(key) + ' ' + label).lower()
93
+ if not re.search('paper|card|letter|envelope|booklet|photo|plan|sheet|display|readout|screen', words):
94
+ return []
95
+ if re.search('cabinet|drawer|box|shelf|case|desk|bench|table|socket', words):
96
+ return []
97
+ return [r for r in rows.values() if _path(r['node']).startswith(path + '/')]
98
+
99
+ def _add_read_surfaces(backend):
100
+ scene = backend.scene
101
+ backend.read_surfaces = {}
102
+ for surface_key, row in _read_surfaces(scene).items():
103
+ path = _path(row['node'])
104
+ enclosing = [(len(_path(n)), k, n) for k, n in scene.target_nodes.items() if path == _path(n) or path.startswith(_path(n) + '/')]
105
+ if enclosing:
106
+ _, key, node = max(enclosing, key=lambda v: v[0])
107
+ if _read_target_rows(scene, node, key):
108
+ continue
109
+ if key in backend.key_to_sim and backend.key_to_sim[key] in backend.gadget_sims:
110
+ continue
111
+ name = 'h2_printed_' + hashlib.sha256(surface_key.encode()).hexdigest()[:14]
112
+ label = 'screen' if surface_key.startswith('screen:') else 'paper'
113
+ obj = ObjectView(name, label, backend, node=row['node'])
114
+ backend.objects[name] = obj
115
+ key = '__printed_' + name.rsplit('_', 1)[1]
116
+ if not hasattr(scene, '_h2_explicit_labels'):
117
+ scene._h2_explicit_labels = {}
118
+ scene._h2_explicit_labels[key] = label
119
+ backend.key_to_sim[key] = name
120
+ backend.sim_to_key[name] = key
121
+ backend.read_surfaces[name] = surface_key
122
+ backend.item_metadata[name] = {'item_key': key, 'target_key': key, 'owner_id': None, 'part': None, 'kind': 'loose', 'fixed': True, 'take_gate': [], 'read_only_label': label}
123
+
124
+ def _refresh_read_surfaces(backend):
125
+ rows = _read_surfaces(backend.scene)
126
+ for name, key in backend.read_surfaces.items():
127
+ row = rows.get(key)
128
+ if row is not None:
129
+ backend.objects[name].node = row['node']
130
+
131
+ def instrument_scene(scene):
132
+ from read_content_policy import instrument_scene as install_read_policy
133
+ install_read_policy(scene)
134
+ if getattr(scene, '_h2_instrumented', False):
135
+ return scene
136
+ scene._h2_instrumented = True
137
+ _record_printed_text()
138
+ scene._h2_picture_prints = {}
139
+ scene._h2_screen_prints = {}
140
+ scene._h2_nodes = {}
141
+ scene._h2_parent = {}
142
+ scene._h2_groups = {}
143
+ scene._h2_named_groups = {}
144
+ scene._h2_shapes = {}
145
+ scene._observation_nodes = {}
146
+ scene._h2_explicit_labels = {}
147
+ original_reg = scene.reg
148
+
149
+ def reg(sc, key, node, label=None):
150
+ result = original_reg(key, node, label)
151
+ if label is not None:
152
+ sc._h2_explicit_labels[str(key)] = str(label)
153
+ return result
154
+ scene.reg = types.MethodType(reg, scene)
155
+ scene.label_for = types.MethodType(lambda sc, key: public_label(sc, key), scene)
156
+ original_group = scene.group
157
+
158
+ def group(sc, key, *args, **kwargs):
159
+ node = original_group(key, *args, **kwargs)
160
+ parent = kwargs.get('parent', args[1] if len(args) > 1 else None)
161
+ sc._h2_groups[_path(node)] = node
162
+ sc._h2_named_groups[str(key)] = node
163
+ sc._h2_parent[_path(node)] = parent
164
+ return node
165
+ scene.group = types.MethodType(group, scene)
166
+ for method in ['box', 'cylinder', 'sphere', 'plane']:
167
+ if not hasattr(scene, method):
168
+ continue
169
+ primitive = getattr(scene, method)
170
+
171
+ def shape(sc, key, *args, _primitive=primitive, _method=method, **kwargs):
172
+ node = _primitive(key, *args, **kwargs)
173
+ if isinstance(node, dict) and 'prim' in node:
174
+ sc._h2_shapes[_path(node)] = node
175
+ if _method == 'plane' or str(key) in {'gear_board'}:
176
+ sc._observation_nodes[str(key)] = node
177
+ return node
178
+ setattr(scene, method, types.MethodType(shape, scene))
179
+ for method in ['picture', 'screen', 'outline']:
180
+ if not hasattr(scene, method):
181
+ continue
182
+ original = getattr(scene, method)
183
+
184
+ def observe(sc, key, *args, _original=original, _method=method, **kwargs):
185
+ node = _original(key, *args, **kwargs)
186
+ if isinstance(node, dict) and 'prim' in node:
187
+ sc._observation_nodes[str(key)] = node
188
+ image = args[0] if args else kwargs.get('im')
189
+ printed = '\n'.join(getattr(image, '_h2_printed_rows', [])).strip()
190
+ if _method in ('picture', 'screen'):
191
+ table = sc._h2_screen_prints if _method == 'screen' else sc._h2_picture_prints
192
+ slot = 'screen:' + str(key) if _method == 'screen' else 'picture:' + _path(node)
193
+ from read_content_policy import image_kind
194
+ table[slot] = {'node': node, 'text': printed, 'read_content_kind': image_kind(image)}
195
+ return node
196
+ setattr(scene, method, types.MethodType(observe, scene))
197
+
198
+ def observation_candidates(sc, game, keys=None):
199
+ requested = set(keys) if keys is not None else set(sc._observation_nodes)
200
+ nodes = {k: v for k, v in sc._observation_nodes.items() if k in requested and k not in sc.target_nodes}
201
+ for key in requested:
202
+ if key not in nodes and key not in sc.target_nodes and (key in sc._h2_named_groups):
203
+ nodes[key] = sc._h2_named_groups[key]
204
+ if not nodes:
205
+ return []
206
+ view = copy.copy(sc)
207
+ view.target_nodes = dict(sc.target_nodes)
208
+ view.target_nodes.update(nodes)
209
+ return type(sc).base_candidates(view, list(nodes))
210
+ scene.observation_candidates = types.MethodType(observation_candidates, scene)
211
+ return scene
212
+
213
+ def _snapshot_to_game(game, snapshot):
214
+ game.s = copy.deepcopy(snapshot.get('state', {}))
215
+ game.solved = list(snapshot.get('solved', [False] * 3))
216
+ game.opened = copy.deepcopy(snapshot.get('opened', {'exit': False}))
217
+ game.holding = list(snapshot.get('holding', []))
218
+ game.taken = set(snapshot.get('taken', []))
219
+ game.possessions = copy.deepcopy(snapshot.get('possessions', {}))
220
+ game.exit_unlocked = bool(snapshot.get('exit_unlocked'))
221
+ game.exited = bool(snapshot.get('exited'))
222
+
223
+ def authored_proposal(game, key, verb, item=None, position=None):
224
+ probe = object.__new__(type(game))
225
+ probe.__dict__ = {k: copy.deepcopy(v) for k, v in game.__dict__.items() if not callable(v)}
226
+ a = {'action': verb, '_hit364': key, '_validated364': True}
227
+ if item is not None:
228
+ a['item'] = item
229
+ if position is not None:
230
+ a['_actor_position364'] = list(map(float, position))
231
+ result = type(probe).act(probe, a)
232
+ return (dict(result), probe.snapshot())
233
+
234
+ def column_order(rows):
235
+ if not rows:
236
+ return []
237
+ widths = [max(0.02, float(r.get('local_width', 0.2))) for r in rows]
238
+ tolerance = max(0.025, min(0.15, float(np.median(widths)) * 0.24))
239
+ columns = []
240
+ for row in sorted(rows, key=lambda r: (r['local_x'], -r['local_z'], r['motion_key'])):
241
+ candidates = [(abs(row['local_x'] - c['centre']), i) for i, c in enumerate(columns) if abs(row['local_x'] - c['centre']) <= tolerance]
242
+ if candidates:
243
+ _, index = min(candidates)
244
+ columns[index]['rows'].append(row)
245
+ columns[index]['centre'] = float(np.mean([v['local_x'] for v in columns[index]['rows']]))
246
+ else:
247
+ columns.append({'centre': float(row['local_x']), 'rows': [row]})
248
+ return [r for c in sorted(columns, key=lambda c: c['centre']) for r in sorted(c['rows'], key=lambda r: (-r['local_z'], r['local_x'], r['motion_key']))]
249
+
250
+ def _local_part_geometry(scene, node, parent):
251
+ if getattr(scene, '_h2_cpu_fixture', False):
252
+ points = np.asarray(scene.local_geometry(node, parent), float).reshape(-1, 3)
253
+ else:
254
+ points = np.asarray(scene.triangles(node), float).reshape(-1, 3)
255
+ inverse = scene.G.XformCache().GetLocalToWorldTransform(parent['prim']).GetInverse()
256
+ points = np.array([inverse.Transform(scene.F.Vec3d(*map(float, p))) for p in points], float)
257
+ if not points.size or not np.isfinite(points).all():
258
+ raise UnsupportedBinding('Part lacks finite owner-local physical geometry')
259
+ low, high = (points.min(0), points.max(0))
260
+ return ((low + high) / 2, high - low)
261
+ CUSTOM_PUBLIC_PARTS = {'R24': {'chest_lid': [-100.0, 0.0, 0.0]}, 'R25': {'canister_lid': [0.0, -100.0, 0.0], 'card_box': [-100.0, 0.0, 0.0]}, 'R29': {'case_lid': [-100.0, 0.0, 0.0]}, 'R36': {'chest_lid': [-100.0, 0.0, 0.0], 'cover': [-100.0, 0.0, 0.0]}, 'R38': {'board_cover': [0.0, 0.0, -100.0]}, 'R44': {'table_cover': [0.0, 0.0, -100.0]}}
262
+
263
+ def _physical(scene, source_id=None):
264
+ if not getattr(scene, '_h2_instrumented', False):
265
+ raise UnsupportedBinding('instrument_scene must run before Scene.build')
266
+ parts = []
267
+ for key, (node, closed, opened) in scene.hinges.items():
268
+ parts.append((key, node, {'kind': 'rotate', 'closed': [0.0, 0.0, float(closed)], 'delta': [0.0, 0.0, float(opened - closed)]}))
269
+ for key, (node, c, pull) in scene.slides.items():
270
+ parts.append((key, node, {'kind': 'translate', 'closed': list(map(float, c)), 'delta': [0.0, -float(pull), 0.0]}))
271
+ for key, delta in CUSTOM_PUBLIC_PARTS.get(source_id, {}).items():
272
+ if key not in scene.target_nodes:
273
+ raise UnsupportedBinding('Authored custom part has no real target: ' + key)
274
+ node = scene.target_nodes[key]
275
+ if any((_path(node) == _path(existing) for _, existing, _ in parts)):
276
+ continue
277
+ parts.append((key, node, {'kind': 'rotate', 'closed': list(map(float, node['rotate'].Get())), 'delta': list(delta)}))
278
+ owner_nodes = {}
279
+ part_rows = []
280
+ for key, node, motion in parts:
281
+ parent = scene._h2_parent.get(_path(node))
282
+ if parent is None:
283
+ parent = scene._h2_groups.get(str(node['prim'].GetParent().GetPath()))
284
+ if parent is None and key in CUSTOM_PUBLIC_PARTS.get(source_id, {}):
285
+ parent = node
286
+ if parent is None:
287
+ raise UnsupportedBinding('Openable has no actual recorded parent: ' + key)
288
+ path = _path(parent)
289
+ owner = 'h2_owner_' + hashlib.sha256(path.encode()).hexdigest()[:12]
290
+ owner_nodes[owner] = parent
291
+ aliases = [k for k, n in scene.target_nodes.items() if _path(n) == _path(node)]
292
+ if key in scene.target_nodes and key not in aliases:
293
+ aliases.insert(0, key)
294
+ open_key = key if key in aliases else aliases[0] if aliases else key
295
+ local, size = _local_part_geometry(scene, node, parent)
296
+ part_rows.append({'owner_id': owner, 'node': node, 'motion_key': key, 'open_key': open_key, 'close_key': open_key, 'aliases': aliases, 'motion': motion, 'local_x': float(local[0]), 'local_z': float(local[2]), 'local_width': float(size[0])})
297
+ for path, node in scene._h2_groups.items():
298
+ if scene._h2_parent.get(path) is not None:
299
+ continue
300
+ if node is scene.exit_node or any((node is target for target in scene.target_nodes.values())):
301
+ continue
302
+ try:
303
+ tri = scene.triangles(node)
304
+ except Exception:
305
+ continue
306
+ if np.asarray(tri).size == 0:
307
+ continue
308
+ owner = 'h2_owner_' + hashlib.sha256(path.encode()).hexdigest()[:12]
309
+ owner_nodes.setdefault(owner, node)
310
+ owners = []
311
+ bindings = []
312
+ for owner, node in owner_nodes.items():
313
+ scene._h2_nodes[owner] = node
314
+ rows = column_order([x for x in part_rows if x['owner_id'] == owner])
315
+ ospec = {'owner_id': owner, 'node_access': '_h2_nodes[' + repr(owner) + ']', 'parts': []}
316
+ for index, row in enumerate(rows, 1):
317
+ key = row['motion_key']
318
+ token = 'part_' + owner + '_' + str(index)
319
+ scene._h2_nodes[token] = row['node']
320
+ ospec['parts'].append({'part': index, 'open_key': row['open_key'], 'aliases': row['aliases']})
321
+ rule = {'status': 'executable_structured', 'rule': {'path': '__h2_permission_placeholder', 'value': True}}
322
+ bindings.append({'owner_id': owner, 'part': index, 'node_access': '_h2_nodes[' + repr(token) + ']', 'state_path': '_h2_physical.' + key, 'open_key': row['open_key'], 'close_key': row['close_key'], 'aliases': row['aliases'], 'motion_key': key, 'motion': row['motion'], 'opening_requirements': rule, 'closing_requirements': rule})
323
+ owners.append(ospec)
324
+ scene._h2_nodes['exit'] = scene.exit_node
325
+ return ({'owners': owners}, {'bindings': bindings, 'door_bindings': [{'owner_id': 'h2_exit', 'node_access': "_h2_nodes['exit']", 'open_key': 'exit', 'state_path': 'opened.exit', 'motion': {'kind': 'rotate', 'closed': [0.0, 0.0, 90.0], 'delta': [0.0, 0.0, 100.0]}}]})
326
+ INSIDE_READ_PARTS = {'R24': {'sheet': 'crank_cab', 'grid_plate': 'read_door'}, 'R26': {'grid': 'arch_door'}, 'R27': {'plate': 'case_door'}, 'R29': {'gauge0': 'case_lid', 'gauge1': 'case_lid', 'gauge2': 'case_lid'}, 'R30': {'grid': 'rec_door'}, 'R32': {'ring': 'wheel_door'}, 'R34': {'b_table': 'read_door'}, 'R38': {'nb_face': 'board_cover'}, 'R40': {'base_face': 'locker_door'}, 'R44': {'b_table': 'table_cover'}}
327
+ INSIDE_READ_POSES = {'R40': {'stock_face': {'custom_key': 'hatch', 'component': 'rotate', 'closed': [0.0, 0.0, 0.0], 'open': [90.0, 0.0, 0.0]}}, 'R41': {'numbers': {'custom_key': 'lock_bar', 'component': 'translate', 'closed': [0.0, -0.215, 0.86], 'open': [0.0, -0.215, 0.72]}}}
328
+
329
+ def _bind_read_access(backend):
330
+ backend.read_access = {}
331
+
332
+ def matches(name, selector):
333
+ key = backend.sim_to_key.get(name)
334
+ surface = backend.read_surfaces.get(name, '')
335
+ return key == selector or surface == 'screen:' + selector or bool(re.search('/' + re.escape(selector) + '(?:_|/|$)', _path(backend.objects[name].node)))
336
+ for name in backend.item_metadata:
337
+ rules = []
338
+ for selector, cover in INSIDE_READ_PARTS.get(backend.level, {}).items():
339
+ if not matches(name, selector):
340
+ continue
341
+ if cover not in backend.part_aliases:
342
+ raise UnsupportedBinding('Inside read cover lacks its actual physical part: ' + cover)
343
+ owner, part = backend.part_aliases[cover]
344
+ rules.append({'kind': 'part_open', 'owner_id': owner, 'part': part, 'cover_key': cover, 'source_surface': selector})
345
+ for selector, pose in INSIDE_READ_POSES.get(backend.level, {}).items():
346
+ if not matches(name, selector):
347
+ continue
348
+ node = backend.scene.custom.get(pose['custom_key'])
349
+ if node is None or pose['component'] not in node:
350
+ raise UnsupportedBinding('Inside read cover lacks its actual authored USD op: ' + selector)
351
+ rules.append(dict(pose, kind='pose_equal', source_surface=selector))
352
+ if rules:
353
+ backend.read_access[name] = rules
354
+
355
+ def _read_access_allowed(session, name):
356
+ backend = session.backend
357
+ for rule in backend.read_access.get(name, []):
358
+ if rule['kind'] == 'part_open':
359
+ if not session.esc.is_open(backend.objects[rule['owner_id']], 'j_part_' + str(rule['part'])):
360
+ return False
361
+ elif rule['kind'] == 'pose_equal':
362
+ node = backend.scene.custom[rule['custom_key']]
363
+ if not np.allclose(np.asarray(node[rule['component']].Get(), float), rule['open'], rtol=0.0, atol=1e-05):
364
+ return False
365
+ else:
366
+ raise UnsupportedBinding('Unknown inside-readable access kind')
367
+ return True
368
+
369
+ class H2Backend(RoomsBackend):
370
+
371
+ def __init__(self, driver, working=BASE):
372
+ self.working = Path(working).resolve()
373
+ self.driver = driver
374
+ self.scene = driver.scene
375
+ self.game = driver.game
376
+ self.level = str(getattr(driver.level, 'ID', Path(driver.level.__file__).stem.replace('level_', '')))
377
+ roles = json.loads((self.working / 'H2_TARGET_ROLES.json').read_text('utf8'))['levels'][self.level]
378
+ if roles['source_sha256'] != hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest():
379
+ raise UnsupportedBinding('H2 semantic role source SHA mismatch')
380
+ self.scene._h2_source_id = self.level
381
+ self.scene._h2_source_sha256 = roles['source_sha256']
382
+ self.inventory_items = set(roles['original_inventory_items'])
383
+ fixture = PUBLIC_CATEGORY_FIXTURES.get(self.level, {})
384
+ if fixture.get('source_sha256') != roles['source_sha256']:
385
+ fixture = {}
386
+ self.non_press_targets = set()
387
+ self.non_item_targets = set()
388
+ self.objects = {}
389
+ self.escape = None
390
+ self.query_count = 0
391
+ self.predicates = {}
392
+ self.session = None
393
+ self.key_to_sim = {}
394
+ self.sim_to_key = {}
395
+ self.part_bindings = {}
396
+ self.part_aliases = {}
397
+ self.item_metadata = {}
398
+ self.lock_endpoints = {}
399
+ self.owner_map, self.motion_map = _physical(self.scene, self.level)
400
+ for owner in sorted(self.owner_map['owners'], key=lambda row: row['owner_id']):
401
+ oid = owner['owner_id']
402
+ node = self.scene._h2_nodes[oid]
403
+ label = str(node['prim'].GetName()).lower()
404
+ category = 'table' if any((x in label for x in ['table', 'bench'])) else 'rack' if any((x in label for x in ['shelf', 'rack'])) else 'board' if any((x in label for x in ['board', 'picture', 'frame'])) else 'cabinet'
405
+ obj = ObjectView(oid, category, self, node=node)
406
+ rootpath = _path(node)
407
+ partpaths = [_path(self.scene._h2_nodes['part_' + oid + '_' + str(b['part'])]) for b in self.motion_map['bindings'] if b['owner_id'] == oid]
408
+ excluded = [_path(n) for k, n in self.scene.target_nodes.items() if _path(n) != rootpath and (not any((_path(n) == p or _path(n).startswith(p + '/') for p in partpaths)))]
409
+ geometry = [n for path, n in self.scene._h2_shapes.items() if path.startswith(rootpath + '/') and (not any((path == q or path.startswith(q + '/') for q in excluded)))]
410
+ if geometry:
411
+ obj.nodes = geometry
412
+ owner['public_label'] = category
413
+ self.objects[oid] = obj
414
+ for binding in self.motion_map['bindings']:
415
+ owner = binding['owner_id']
416
+ part = binding['part']
417
+ node = self.scene._h2_nodes['part_' + owner + '_' + str(part)]
418
+ joint = 'j_part_' + str(part)
419
+ obj = self.objects[owner]
420
+ obj.links[joint[2:]] = ObjectView(owner + '_part_' + str(part), 'part', self, node=node)
421
+ obj.joints[joint] = MotionJoint(self, node, binding)
422
+ self.part_bindings[owner, part] = binding
423
+ for key in list(dict.fromkeys([binding['open_key']] + binding['aliases'])):
424
+ self.part_aliases[key] = (owner, part)
425
+ self.door_binding = self.motion_map['door_bindings'][0]
426
+ self.exit_name = 'h2_exit'
427
+ node = self.scene.exit_node
428
+ door = ObjectView(self.exit_name, 'door', self, node=node)
429
+ door.links['panel'] = ObjectView(self.exit_name + '_panel', 'door', self, node=node)
430
+ door.joints['j_panel'] = MotionJoint(self, node, self.door_binding)
431
+ door.metadata['openable_joint_ids'] = {'panel': 'j_panel'}
432
+ self.objects[self.exit_name] = door
433
+ self.key_to_sim['exit'] = self.exit_name
434
+ self.sim_to_key[self.exit_name] = 'exit'
435
+ self.gadget_sims = {}
436
+ self.original_poses = {}
437
+ self.take_geometry_aliases = {}
438
+ for key, node in sorted(self.scene.target_nodes.items()):
439
+ if key in self.part_aliases or key == 'exit':
440
+ continue
441
+ name = 'h2_item_' + key
442
+ category = 'code lock' if key == 'exit_lock' else public_label(self.scene, key) if key in self.inventory_items or key in fixture.get('items', {}) else 'electric switch'
443
+ obj = ObjectView(name, category, self, node=node)
444
+ self.objects[name] = obj
445
+ self.key_to_sim[key] = name
446
+ self.sim_to_key[name] = key
447
+ enclosing = [(len(_path(self.objects[owner].node)), owner) for owner in self.owner_map_ids if _path(node) == _path(self.objects[owner].node) or _path(node).startswith(_path(self.objects[owner].node) + '/')]
448
+ container = max(enclosing)[1] if enclosing else None
449
+ self.item_metadata[name] = {'item_key': key, 'target_key': key, 'owner_id': container, 'part': None, 'kind': 'loose', 'fixed': key == 'exit_lock', 'take_gate': []}
450
+ if key != 'exit_lock':
451
+ self.gadget_sims[name] = key
452
+ if key in fixture.get('non_press_receivers', []):
453
+ self.non_press_targets.add(name)
454
+ if key in fixture.get('non_item_receivers', []):
455
+ if key in self.inventory_items or any((r['text'] for r in _read_target_rows(self.scene, node, key))):
456
+ raise UnsupportedBinding('Use-only receiver is actually a tool/readable: ' + key)
457
+ self.non_item_targets.add(name)
458
+ self.original_poses[name] = self.pose(obj)
459
+ _add_read_surfaces(self)
460
+ _bind_read_access(self)
461
+ self._door_boxes = {self.exit_name: tuple(door.aabb)}
462
+
463
+ def bounds(self, obj):
464
+ alias = self.take_geometry_aliases.get(obj.name)
465
+ if alias is not None and self.escape is not None and (not self.escape.items[obj.name].get('taken')):
466
+ points = self.scene.triangles(alias).reshape(-1, 3)
467
+ if not points.size:
468
+ raise UnsupportedBinding('Take alias has no physical target mesh')
469
+ return np.array([points.min(0), points.max(0)])
470
+ return super().bounds(obj)
471
+
472
+ def pose(self, obj):
473
+ alias = self.take_geometry_aliases.get(obj.name)
474
+ if alias is not None and self.escape is not None and (not self.escape.items[obj.name].get('taken')):
475
+ proxy = ObjectView(obj.name, obj.category, self, node=alias)
476
+ return super().pose(proxy)
477
+ return super().pose(obj)
478
+
479
+ def step(self, n=1):
480
+ for _ in range(max(1, int(n))):
481
+ self.driver.og.sim.step()
482
+
483
+ def visible(self, obj):
484
+ if self.escape is not None and obj.name in getattr(self.escape, '_hidden', []):
485
+ return False
486
+ if obj.name in self.owner_map_ids:
487
+ return True
488
+ if obj.name in self.read_surfaces:
489
+ row = _read_surfaces(self.scene).get(self.read_surfaces[obj.name])
490
+ return bool(row and _node_visible(self.scene, row['node']))
491
+ key = self.sim_to_key.get(obj.name)
492
+ return key is None or bool(self.scene.visible(key, self.game))
493
+
494
+ class H2Session(RoomsSession):
495
+
496
+ def __init__(self, backend, out, E, C):
497
+ self.backend = backend
498
+ backend.session = self
499
+ self.driver = backend.driver
500
+ self.game = backend.game
501
+ self.E = E
502
+ self.C = C
503
+ self.extra_images = []
504
+ self.placements = {}
505
+ self.lock_effects = {}
506
+ self.last_call_trace = []
507
+ self._part_proposals = {}
508
+ self._take_proposals = {}
509
+ self._projecting = False
510
+ self._restoring = False
511
+ self._alias_originals = {}
512
+ self._authored_door_open = self.driver.scene.door_open
513
+ self._authored_h2_lock_feedback = json.loads((backend.working / 'native_runtime/H2_LOCK_FEEDBACK.json').read_text('utf8'))['levels']
514
+ lock_row = self._authored_h2_lock_feedback.get(backend.level)
515
+ if lock_row is None or lock_row['source_sha256'] != hashlib.sha256(Path(self.driver.level.__file__).read_bytes()).hexdigest():
516
+ raise UnsupportedBinding('Lock feedback source SHA mismatch')
517
+ install_mechanism_hooks(E)
518
+ out = Path(out)
519
+ out.mkdir(parents=True, exist_ok=True)
520
+ cfg = {'name': 'native_bridge_' + backend.level, 'scene': 'programmatic_' + backend.level, 'start': {'xy': list(self.driver.pos[:2]), 'yaw_deg': math.degrees(self.driver.yaw)}, 'max_steps': 250, 'recall_budget': 25, 'tip_window': 60, 'native_devices_visual': False, 'native_use_visual': False, 'items': [], 'part_locks': [{'container': o, 'part': p} for o, p in backend.part_bindings], 'doors': [{'name': backend.exit_name, 'lock': str(self.game.SPEC['door_code']), 'exit': True}], 'gadgets': [{'name': name, 'type': 'native_mechanism'} for name in backend.gadget_sims]}
521
+ for name, row in backend.item_metadata.items():
522
+ if name not in backend.non_item_targets:
523
+ cfg['items'].append({'id': row['item_key'], 'name': name, 'kind': 'tool', 'text': ''})
524
+ ctx = {'env': types.SimpleNamespace(scene=types.SimpleNamespace(objects=list(backend.objects.values()), object_registry=lambda k, n: backend.objects.get(n))), 'E': types.SimpleNamespace(quat_from=quat_from), 'pos': list(self.driver.pos), 'shot': backend.capture, 'detect': backend.detect, 'step_sim': backend.step, 'fov_h': lambda: math.pi / 2}
525
+ self.esc = E.Escape(ctx, cfg, out)
526
+ backend.escape = self.esc
527
+ e = self.esc
528
+ e._native_read_only_data_targets = set(backend.read_surfaces)
529
+ e.floor = 0.0
530
+ e._cam_z0 = e.cam_z
531
+ e._hidden = []
532
+ e._native_photo_metadata_hook = backend.photo_metadata
533
+ e._native_front_mesh_guard = backend.front_mesh_guard
534
+ if getattr(getattr(self.driver, 'og', None), 'env', None) is not None:
535
+ e._video_native_scene = self.driver.og.env.scene
536
+ e._native_mechanism_hook = self.mechanism
537
+ e._native_mechanism_targets = set(backend.gadget_sims)
538
+ e._native_press_capabilities = set(backend.gadget_sims) - backend.non_press_targets
539
+ e._native_take_gate = self.take_gate
540
+ e._native_taken_hook = self.on_taken
541
+ e._native_part_gate = self.part_gate
542
+ e._native_part_gate_failure = self.part_gate_failure
543
+ e._native_read_text = self.read_text
544
+ e._native_read_kind = self.read_kind
545
+ e._native_unlock_gate = self.unlock_gate
546
+ e._native_item_alias = self.item_alias
547
+ for index, obj in enumerate(backend.objects.values(), 1):
548
+ e.objs[index] = {'id': index, 'sim': obj.name, 'cat': obj.category, 'center': obj.aabb.mean(0).tolist()}
549
+ e.by_sim[obj.name] = index
550
+ self.key_to_oid = {k: e.by_sim[v] for k, v in backend.key_to_sim.items()}
551
+ self.oid_to_key = {v: k for k, v in self.key_to_oid.items()}
552
+ for key, (owner, part) in backend.part_aliases.items():
553
+ self.key_to_oid[key] = e.by_sim[owner]
554
+ for owner, obj in backend.objects.items():
555
+ if obj.joints:
556
+ e._parts[owner] = [(j, 'drawer' if 'Prismatic' in str(v.joint_type) else 'door') for j, v in obj.joints.items()]
557
+ e._closed_box[owner] = tuple(obj.aabb.copy())
558
+ for name, row in backend.item_metadata.items():
559
+ if name in backend.non_item_targets:
560
+ e._display[name] = public_label(self.driver.scene, row['item_key'])
561
+ continue
562
+ st = {'id': row['item_key'], 'name': name, 'container': row.get('owner_id') or name, 'part': 0, 'joint': None, 'kind': 'loose', 'fixed': row['fixed'], 'text': '', 'lockd': None, 'unlocked': True, 'taken': False}
563
+ if row['item_key'] == 'exit_lock':
564
+ st = LinkedLockItem(st, e.doors[backend.exit_name])
565
+ e.items[name] = st
566
+ e._display[name] = row.get('read_only_label') or self.driver.label(row['item_key'])
567
+ from scipy.spatial.transform import Rotation
568
+ for owner in backend.owner_map_ids:
569
+ key = next((b['open_key'] for (o, p), b in backend.part_bindings.items() if o == owner), None)
570
+ e._display[owner] = self.driver.label(key) if key else backend.objects[owner].category
571
+ e._fronts[owner] = Rotation.from_quat(backend.pose(backend.objects[owner])[1]).apply([0.0, -1.0, 0.0])[:2]
572
+ e._display[backend.exit_name] = 'exit door'
573
+ e._wallmap = np.zeros((640, 640), bool)
574
+ res = e.GUARD_RES
575
+ e._wallmap[320:320 + int(5.0 / res), 320:320 + int(9.6 / res)] = True
576
+ x = 320 + int(round(4.8 / res))
577
+ e._wallmap[320:320 + int(5.0 / res), x - 1:x + 2] = False
578
+ e._wallmap[320 + int(1.8 / res):320 + int(2.95 / res), x - 1:x + 2] = True
579
+ e._door_boxes = backend._door_boxes
580
+ e._window_boxes = {}
581
+ e._semmap = np.ones((3200, 3200), np.uint8)
582
+ e._roomcats = ['room_A', 'room_B']
583
+ self.generic_identity = {name: getattr(E.Escape, name) for name in ['act', 'a_open', 'a_close', 'a_take', 'a_unlock', 'a_use']}
584
+ original = self._authored_door_open
585
+
586
+ def door_open(scene, key, g):
587
+ if g is self.game:
588
+ entry = next(((o, p) for (o, p), b in backend.part_bindings.items() if b['motion_key'] == key), None)
589
+ if entry:
590
+ return bool(e.is_open(backend.objects[entry[0]], 'j_part_' + str(entry[1])))
591
+ return original(key, g)
592
+ self.driver.scene.door_open = types.MethodType(door_open, self.driver.scene)
593
+ self.project()
594
+
595
+ def _proposal(self, key, verb, item=None):
596
+ return authored_proposal(self.game, key, verb, item, self.esc.pos)
597
+
598
+ def _commit(self, snapshot):
599
+ _snapshot_to_game(self.game, snapshot)
600
+
601
+ def part_gate(self, owner, part, verb):
602
+ binding = self.backend.part_bindings[owner, part]
603
+ key = binding['open_key']
604
+ result, state = self._proposal(key, verb)
605
+ if result.get('ok'):
606
+ previous = bool(self.esc.is_open(self.backend.objects[owner], 'j_part_' + str(part)))
607
+ self._part_proposals[owner, part] = {'state': state, 'before_open': previous, 'want_open': verb == 'open'}
608
+ self.esc.part_locks[owner, part]['unlocked'] = True
609
+ return True
610
+ return False
611
+
612
+ def item_alias(self, obj, st, verb):
613
+ key = self.backend.sim_to_key.get(st['name'])
614
+ if key is None:
615
+ return (obj, st, None)
616
+ result, state = self._proposal(key, 'take')
617
+ if not result.get('ok'):
618
+ return (obj, st, None)
619
+ added = [v for v in state['holding'] if v not in self.game.holding]
620
+ if len(added) != 1:
621
+ raise UnsupportedBinding('Authored take has ambiguous inventory identity: ' + key)
622
+ item = added[0]
623
+ if item == key:
624
+ return (obj, st, None)
625
+ canonical = self.backend.key_to_sim.get(item)
626
+ if canonical is None or canonical not in self.esc.items:
627
+ raise UnsupportedBinding('Recovered item lacks an authored original mesh: ' + item)
628
+ target = self.esc.items[canonical]
629
+ self._alias_originals[canonical] = {'state': copy.deepcopy(dict(target)), 'center': copy.deepcopy(self.esc.objs[self.esc.by_sim[canonical]]['center'])}
630
+ target['gone'] = False
631
+ target['taken'] = False
632
+ target['container'] = st['container']
633
+ target.pop('slot', None)
634
+ self.backend.take_geometry_aliases[canonical] = self.backend.objects[st['name']].node
635
+ self._take_proposals[canonical] = state
636
+ newobj = self.esc.objs[self.esc.by_sim[canonical]]
637
+ newobj['center'] = self.backend.bounds(self.backend.objects[canonical]).mean(0).tolist()
638
+ return (newobj, target, None)
639
+
640
+ def take_gate(self, name):
641
+ if name in self.backend.take_geometry_aliases and name in self._take_proposals:
642
+ return True
643
+ key = self.backend.sim_to_key[name]
644
+ result, state = self._proposal(key, 'take')
645
+ if result.get('ok'):
646
+ delta = [v for v in state['holding'] if v not in self.game.holding]
647
+ if len(delta) != 1:
648
+ raise UnsupportedBinding('Authored take must produce one inventory item: ' + key)
649
+ self._take_proposals[name] = state
650
+ self.backend.item_metadata[name]['item_key'] = delta[0]
651
+ self.esc.items[name]['id'] = delta[0]
652
+ return bool(result.get('ok'))
653
+
654
+ def on_taken(self, name):
655
+ state = self._take_proposals.pop(name, None)
656
+ if state is None:
657
+ raise UnsupportedBinding('Canonical take has no successful authored puzzle effect')
658
+ self._commit(state)
659
+ key = self.backend.item_metadata[name]['item_key']
660
+ label = public_label(self.driver.scene, key)
661
+ self.backend.objects[name].category = label
662
+ self.esc.objs[self.esc.by_sim[name]]['cat'] = label
663
+ self.esc._display[name] = label
664
+ self.esc.items[name]['gone'] = False
665
+
666
+ def read_kind(self, name):
667
+ if not _read_access_allowed(self, name):
668
+ return None
669
+ b = self.backend
670
+ scene = b.scene
671
+ if name in b.read_surfaces:
672
+ row = _read_surfaces(scene).get(b.read_surfaces[name])
673
+ rows = [row] if row else []
674
+ else:
675
+ obj = b.objects.get(name)
676
+ rows = _read_target_rows(scene, obj.node, b.sim_to_key.get(name, '')) if obj is not None else []
677
+ rows = [r for r in rows if self.esc.items.get(name, {}).get('taken') or _node_visible(scene, r['node'])]
678
+ if not rows:
679
+ return None
680
+ return 'visual_only' if any((r.get('read_content_kind') != 'text_only' for r in rows)) else 'text_only'
681
+
682
+ def read_text(self, name):
683
+ b = self.backend
684
+ scene = b.scene
685
+ if not _read_access_allowed(self, name):
686
+ return ''
687
+ if name in b.read_surfaces:
688
+ row = _read_surfaces(scene).get(b.read_surfaces[name])
689
+ rows = [row] if row else []
690
+ else:
691
+ obj = b.objects.get(name)
692
+ rows = _read_target_rows(scene, obj.node, b.sim_to_key.get(name, '')) if obj is not None else []
693
+ return '\n'.join((r['text'] for r in rows if r['text'] and _node_visible(scene, r['node']))).strip()
694
+
695
+ def clue_text(self, key):
696
+ return ''
697
+
698
+ def unlock_gate(self, a):
699
+ obj = self.esc.objs.get(a.get('target'), {})
700
+ sim = obj.get('sim')
701
+ key = self.backend.sim_to_key.get(sim)
702
+ if sim == self.backend.exit_name or key == 'exit_lock':
703
+ self.game.possessions['door_input'] = str(a.get('code', ''))
704
+ return True
705
+
706
+ def project(self):
707
+ if self._projecting or self._restoring:
708
+ return
709
+ self._projecting = True
710
+ try:
711
+ e = self.esc
712
+ b = self.backend
713
+ g = self.game
714
+ for (owner, part), proposal in list(self._part_proposals.items()):
715
+ now = bool(e.is_open(b.objects[owner], 'j_part_' + str(part)))
716
+ if now == proposal['want_open'] and now != proposal['before_open']:
717
+ self._commit(proposal['state'])
718
+ self._part_proposals.pop((owner, part), None)
719
+ g.holding = [b.item_metadata[e.objs[i]['sim']]['item_key'] for i in e.holding]
720
+ for name, row in b.item_metadata.items():
721
+ if name in e.items and e.items[name].get('taken'):
722
+ g.taken.add(row['item_key'])
723
+ g.opened['exit'] = b.exit_name in e.passed_doors
724
+ g.exit_unlocked = bool(e.doors[b.exit_name]['unlocked'])
725
+ g.exited = bool(e.success)
726
+ saved = []
727
+ for (owner, part), binding in b.part_bindings.items():
728
+ node = b.objects[owner].links['part_' + str(part)].node
729
+ saved.append((node, list(node['translate'].Get()), list(node['rotate'].Get())))
730
+ node = b.scene.exit_node
731
+ saved.append((node, list(node['translate'].Get()), list(node['rotate'].Get())))
732
+ b.scene.sync(g)
733
+ _refresh_read_surfaces(b)
734
+ for node, pos, rpy in saved:
735
+ b.scene.transform(node, pos=pos, rpy=rpy)
736
+ if b.native:
737
+ from pxr import Usd, UsdPhysics
738
+ with self.driver.og.sim.editing_usd():
739
+ for name, st in e.items.items():
740
+ obj = b.objects[name]
741
+ enabled = not st.get('taken') and (b.visible(obj) if name in b.read_surfaces else bool(b.scene.visible(b.sim_to_key[name], g)))
742
+ for prim in Usd.PrimRange(obj.node['prim']):
743
+ if prim.HasAPI(UsdPhysics.CollisionAPI):
744
+ UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Set(enabled)
745
+ finally:
746
+ self._projecting = False
747
+
748
+ def mechanism(self, kind, name, item_name, a):
749
+ if kind not in ('press', 'use'):
750
+ raise UnsupportedBinding('Only puzzle press/use callbacks may run live Game.act')
751
+ self.project()
752
+ b = self.backend
753
+ g = self.game
754
+ key = b.gadget_sims[name]
755
+ before = g.snapshot()
756
+ logical_before = {entry['motion_key']: bool(self._authored_door_open(entry['motion_key'], g)) for entry in b.part_bindings.values()}
757
+ internal = {'action': kind, '_hit364': key, '_validated364': True, '_actor_position364': self.esc.pos.tolist()}
758
+ if item_name is not None:
759
+ internal['item'] = b.item_metadata[item_name]['item_key']
760
+ result = type(g).act(g, internal)
761
+ if not result.get('ok'):
762
+ return result
763
+ after = g.snapshot()
764
+ for (owner, part), binding in b.part_bindings.items():
765
+ now = bool(self._authored_door_open(binding['motion_key'], g))
766
+ if now != logical_before[binding['motion_key']]:
767
+ self.esc.set_joint(b.objects[owner], 'j_part_' + str(part), now)
768
+ removed = set(before['holding']) - set(after['holding'])
769
+ added = set(after['holding']) - set(before['holding'])
770
+ for item in removed:
771
+ names = [n for n, row in b.item_metadata.items() if row['item_key'] == item and self.esc.items[n].get('taken')]
772
+ if len(names) != 1:
773
+ raise UnsupportedBinding('Inventory effect does not identify one real held object: ' + item)
774
+ st = self.esc.items[names[0]]
775
+ self.esc._slot_place(self.esc.gadgets[name], st)
776
+ st['gone'] = False
777
+ for item in added:
778
+ names = [n for n, row in b.item_metadata.items() if row['item_key'] == item]
779
+ if len(names) != 1:
780
+ raise UnsupportedBinding('Returned item does not identify one authored object: ' + item)
781
+ st = self.esc.items[names[0]]
782
+ st.update(taken=True, gone=False)
783
+ st.pop('slot', None)
784
+ oid = self.esc.by_sim[names[0]]
785
+ if oid not in self.esc.holding:
786
+ self.esc.holding.append(oid)
787
+ if names[0] not in getattr(self.esc, '_hidden', []):
788
+ self.esc._hide(names[0])
789
+ for item in set(before['taken']) - set(after['taken']):
790
+ for n, row in b.item_metadata.items():
791
+ if row['item_key'] != item:
792
+ continue
793
+ st = self.esc.items[n]
794
+ st.update(taken=False, gone=False)
795
+ st.pop('slot', None)
796
+ oid = self.esc.by_sim[n]
797
+ self.esc.holding[:] = [v for v in self.esc.holding if v != oid]
798
+ self.esc._hidden[:] = [v for v in getattr(self.esc, '_hidden', []) if v != n]
799
+ b.set_pose(b.objects[n], *b.original_poses[n])
800
+ self.driver.current_hit = {'key': key, 'source': 'actual_common_legacy_resolution'}
801
+ count = len(getattr(self.driver, 'current_visual_feedback', []))
802
+ self.project()
803
+ if hasattr(b.scene, 'animate'):
804
+ b.scene.animate(self.driver, before)
805
+ self.extra_images.extend(getattr(self.driver, 'current_visual_feedback', [])[count:])
806
+ return result
807
+
808
+ def act(self, action):
809
+ e = self.esc
810
+ self._part_proposals.clear()
811
+ self._take_proposals.clear()
812
+ e._native_public_kind = action.get('action')
813
+ self.extra_images = []
814
+ from observation_group import begin
815
+ begin(self)
816
+ e.t = int(getattr(self.driver, '_legacy_action_step', self.driver.step + 1))
817
+ result = e.act(dict(action))
818
+ for name, prior in self._alias_originals.items():
819
+ if not result.get('ok'):
820
+ e.items[name].clear()
821
+ e.items[name].update(prior['state'])
822
+ if result.get('ok'):
823
+ e.items[name]['container'] = prior['state']['container']
824
+ e.objs[e.by_sim[name]]['center'] = prior['center']
825
+ self._alias_originals.clear()
826
+ self.backend.take_geometry_aliases.clear()
827
+ if action.get('action') == 'unlock' and result.get('unlock_monitor') is not None:
828
+ self.game.possessions['door_input'] = str(action.get('code', ''))
829
+ self.project()
830
+ self.driver.pos = e.pos.copy()
831
+ self.driver.yaw = float(e.yaw)
832
+ self.driver.pitch = math.radians(getattr(e, '_claw_pitch', 0.0))
833
+ result = dict(result)
834
+ if not result.get('images'):
835
+ boxed, _ = self.C.shoot(e, 'h2_current_result')
836
+ e._claw_photos = [boxed]
837
+ result['images'] = [self.C._small(e, boxed)]
838
+ if self.extra_images:
839
+ result['images'] = list(dict.fromkeys(self.extra_images + result['images']))
840
+ from observation_group import finalize
841
+ finalize(self, result['images'])
842
+ self._part_proposals.clear()
843
+ self._take_proposals.clear()
844
+ return result
845
+
846
+ def checkpoint_state(self):
847
+ e = self.esc
848
+ b = self.backend
849
+ return {'bridge_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'roles_sha256': hashlib.sha256((b.working / 'H2_TARGET_ROLES.json').read_bytes()).hexdigest(), 'joint_values': [{'owner': o, 'joint': name, 'position': float(np.asarray(joint.get_state()[0]).ravel()[0]), 'lower': float(joint.lower_limit), 'upper': float(joint.upper_limit), 'max_velocity': float(joint.max_velocity)} for o, obj in b.objects.items() for name, joint in obj.joints.items()], 'door_closed_positions': copy.deepcopy(getattr(e, '_door_closed_pos', {})), 'door_flipped': list(getattr(e, '_door_flipped', set())), 'objects': copy.deepcopy(e.objs), 'display': copy.deepcopy(e._display), 'observation_group': __import__('observation_group').checkpoint(self), 'source_sha256': hashlib.sha256(Path(self.driver.level.__file__).read_bytes()).hexdigest(), 'game': copy.deepcopy(self.game.snapshot()), 'part_open': [{'owner': o, 'part': p, 'open': bool(e.is_open(b.objects[o], 'j_part_' + str(p)))} for o, p in b.part_bindings], 'exit_open': b.exit_name in e.passed_doors, 'exit_unlocked': bool(e.doors[b.exit_name]['unlocked']), 'success': bool(e.success), 'holding_sims': [e.objs[i]['sim'] for i in e.holding], 'items': {n: {k: copy.deepcopy(st[k]) for k in st} for n, st in e.items.items()}, 'inventory_keys': {n: v['item_key'] for n, v in b.item_metadata.items()}, 'part_locks': [{'owner': o, 'part': p, 'record': copy.deepcopy(v)} for (o, p), v in e.part_locks.items()], 'doors': copy.deepcopy(e.doors), 'hidden': list(getattr(e, '_hidden', [])), 'marks': copy.deepcopy(e.marks), 'read_texts': copy.deepcopy(e.read_texts), 'memory': copy.deepcopy(e.memory), 'recalls': int(e.recalls), 't': int(e.t), 'gadgets': copy.deepcopy(e.gadgets)}
850
+
851
+ def restore_checkpoint_state(self, value):
852
+ assert value['source_sha256'] == hashlib.sha256(Path(self.driver.level.__file__).read_bytes()).hexdigest(), 'H2 source changed since checkpoint'
853
+ assert value.get('bridge_sha256') == hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'H2 bridge changed since checkpoint'
854
+ e = self.esc
855
+ b = self.backend
856
+ assert value.get('roles_sha256') == hashlib.sha256((b.working / 'H2_TARGET_ROLES.json').read_bytes()).hexdigest(), 'H2 identity data changed since checkpoint'
857
+ assert set(value['items']) == set(e.items)
858
+ self._restoring = True
859
+ try:
860
+ _snapshot_to_game(self.game, value['game'])
861
+ for row in value['joint_values']:
862
+ joint = b.objects[row['owner']].joints[row['joint']]
863
+ joint.lower_limit = float(row['lower'])
864
+ joint.upper_limit = float(row['upper'])
865
+ joint.max_velocity = float(row['max_velocity'])
866
+ joint.set_pos(float(row['position']), drive=False)
867
+ e._door_closed_pos = copy.deepcopy(value['door_closed_positions'])
868
+ e._door_flipped = set(value['door_flipped'])
869
+ for oid, obj in value['objects'].items():
870
+ oid = int(oid)
871
+ assert e.objs[oid]['sim'] == obj['sim'], 'H2 object identity changed'
872
+ e.objs[oid].update(copy.deepcopy(obj))
873
+ e._display = copy.deepcopy(value['display'])
874
+ for row in value['part_locks']:
875
+ e.part_locks[row['owner'], row['part']].update(copy.deepcopy(row['record']))
876
+ for n, record in value['doors'].items():
877
+ e.doors[n].update(copy.deepcopy(record))
878
+ for n, record in value['items'].items():
879
+ e.items[n].update(copy.deepcopy(record))
880
+ for n, key in value.get('inventory_keys', {}).items():
881
+ b.item_metadata[n]['item_key'] = key
882
+ e.holding = [e.by_sim[n] for n in value['holding_sims']]
883
+ e.passed_doors = {b.exit_name} if value['exit_open'] else set()
884
+ e.success = bool(value['success'])
885
+ e._hidden = list(value['hidden'])
886
+ e.marks = copy.deepcopy(value['marks'])
887
+ e.read_texts = copy.deepcopy(value['read_texts'])
888
+ e.memory = copy.deepcopy(value['memory'])
889
+ e.recalls = int(value['recalls'])
890
+ e.t = int(value['t'])
891
+ for n, record in value.get('gadgets', {}).items():
892
+ e.gadgets[n].update(copy.deepcopy(record))
893
+ finally:
894
+ self._restoring = False
895
+ self.project()
896
+ __import__('observation_group').restore(self, value.get('observation_group'))
897
+
898
+ def attach(driver, out, working=BASE, E=None, C=None):
899
+ if E is None:
900
+ E, C = load_stack(Path(working))
901
+ if not getattr(driver.scene, '_h2_instrumented', False):
902
+ raise UnsupportedBinding('H2 scene was not instrumented before build')
903
+ backend = H2Backend(driver, working=working)
904
+ session = H2Session(backend, out, E, C)
905
+ session.native_gate()
906
+ from observation_group import attach as attach_photos
907
+ attach_photos(driver, session)
908
+ driver.save('H2_COMMON_BINDINGS.json', {'source_id': backend.level, 'source_sha256': hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest(), 'owner_map': backend.owner_map, 'motion_map': backend.motion_map, 'actual_E_file': str(Path(E.__file__).resolve()), 'actual_C_file': str(Path(C.__file__).resolve()), 'public_Game_act_fallback': False, 'model_calls': 0})
909
+ labels = {}
910
+ for key in driver.scene.target_nodes:
911
+ sim = backend.key_to_sim.get(key)
912
+ if sim is None and key in backend.part_aliases:
913
+ sim = backend.part_aliases[key][0]
914
+ oid = session.esc.by_sim.get(sim)
915
+ labels[key] = {'scene_label': driver.scene.label_for(key), 'driver_label': driver.label(key), 'category': session.esc.objs.get(oid, {}).get('cat'), 'public_display': session.esc._display.get(sim), 'original_inventory_item': key in backend.inventory_items, 'explicit_scene_label': getattr(driver.scene, '_h2_explicit_labels', {}).get(key)}
916
+ driver.save('PUBLIC_LABELS.json', {'source_id': backend.level, 'labels': labels, 'owner_public_labels': {x['owner_id']: x['public_label'] for x in backend.owner_map['owners']}, 'private_verification_only': True, 'sent_to_model': False, 'model_calls': 0})
917
+ return session
runtime/native_runtime/legacy_r01_pilot.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import copy
3
+ import sys, os, math, json, types, importlib.util, contextlib, hashlib
4
+ import numpy as np
5
+ from PIL import Image
6
+ from scipy.spatial.transform import Rotation
7
+ ROOT = Path(__file__).resolve().parent
8
+ WORKING = ROOT.parent if (ROOT.parent / 'legacy_entry.py').is_file() else ROOT.parent / 'working'
9
+
10
+ def load_stack(working=WORKING):
11
+ os.environ['ESI_ESCAPE_REFS'] = 'claw'
12
+ os.environ['ESI_ESCAPE_PERSIST'] = '1'
13
+ os.environ['ESI_ESCAPE_VIDEO'] = '0'
14
+ sys.path.insert(0, str(working))
15
+ spec = importlib.util.spec_from_file_location('_pilot_legacy_entry', working / 'legacy_entry.py')
16
+ m = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(m)
18
+ return m.install_stack()[:2]
19
+
20
+ def quat_from(yaw, pitch):
21
+ p = math.radians(pitch)
22
+ f = np.array([math.cos(p) * math.cos(yaw), math.cos(p) * math.sin(yaw), math.sin(p)])
23
+ right = np.array([math.sin(yaw), -math.cos(yaw), 0.0])
24
+ up = np.cross(right, f)
25
+ return Rotation.from_matrix(np.column_stack([right, up, -f])).as_quat()
26
+
27
+ class ObjectView:
28
+
29
+ def __init__(self, name, category, backend, node=None, bounds=None):
30
+ self.name = name
31
+ self.category = category
32
+ self.backend = backend
33
+ self.node = node
34
+ self._bounds = np.array(bounds, float) if bounds is not None else None
35
+ self.links = {}
36
+ self.joints = {}
37
+ self.metadata = {}
38
+
39
+ @property
40
+ def aabb(self):
41
+ return self.backend.bounds(self)
42
+
43
+ def get_position_orientation(self):
44
+ return self.backend.pose(self)
45
+
46
+ def set_position_orientation(self, position=None, orientation=None):
47
+ self.backend.set_pose(self, position, orientation)
48
+
49
+ def keep_still(self):
50
+ pass
51
+
52
+ def disable_gravity(self):
53
+ pass
54
+
55
+ class CpuJoint:
56
+
57
+ def __init__(self, part, kind, upper=0.5):
58
+ self.part = part
59
+ self.joint_type = kind
60
+ self.lower_limit = 0.0
61
+ self.upper_limit = upper
62
+ self.q = 0.0
63
+ self.max_velocity = 0.0
64
+
65
+ def get_state(self):
66
+ return (np.array([self.q]), np.array([0.0]), None)
67
+
68
+ def set_pos(self, q, drive=False):
69
+ delta = float(q) - self.q
70
+ self.q = float(q)
71
+ if 'Prismatic' in self.joint_type:
72
+ self.part._bounds[:, 1] -= delta
73
+
74
+ class XformJoint:
75
+
76
+ def __init__(self, backend, node, kind, axis, sign, upper):
77
+ self.backend = backend
78
+ self.node = node
79
+ self.joint_type = kind
80
+ self.axis = axis
81
+ self.sign = sign
82
+ self.lower_limit = 0.0
83
+ self.upper_limit = float(upper)
84
+ self.max_velocity = 0.0
85
+ self.closed = np.array((node['translate'] if 'Prismatic' in kind else node['rotate']).Get(), float)
86
+
87
+ def get_state(self):
88
+ op = self.node['translate'] if 'Prismatic' in self.joint_type else self.node['rotate']
89
+ now = np.array(op.Get(), float)
90
+ q = (now[self.axis] - self.closed[self.axis]) * self.sign
91
+ if 'Revolute' in self.joint_type:
92
+ q = math.radians(q)
93
+ return (np.array([q]), np.array([0.0]), None)
94
+
95
+ def set_pos(self, q, drive=False):
96
+ op = self.node['translate'] if 'Prismatic' in self.joint_type else self.node['rotate']
97
+ now = np.array(op.Get(), float)
98
+ now[self.axis] = self.closed[self.axis] + self.sign * (float(q) if 'Prismatic' in self.joint_type else math.degrees(float(q)))
99
+ self.backend.scene.transform(self.node, **{'pos': now.tolist()} if 'Prismatic' in self.joint_type else {'rpy': now.tolist()})
100
+
101
+ class CpuBackend:
102
+ native = False
103
+
104
+ def __init__(self):
105
+ self.objects = {}
106
+ self.escape = None
107
+ self.pos = np.array([0.8, 4.0, 1.35])
108
+ self.depth = None
109
+ self.query_count = 0
110
+ self.add('cabinet', 'cabinet', [[0.4, 4.8, 0.1], [1.2, 5.35, 1.45]])
111
+ for i, z in enumerate([1.12, 0.78, 0.44], 1):
112
+ part = self.add('drawer' + str(i), 'drawer', [[0.42, 4.8, z - 0.14], [1.18, 5.32, z + 0.14]])
113
+ j = 'j_drawer' + str(i)
114
+ self.objects['cabinet'].links[j[2:]] = part
115
+ self.objects['cabinet'].joints[j] = CpuJoint(part, 'PrismaticJoint')
116
+ for name, cat, box in [('toolbox', 'cabinet', [[2.4, 4.8, 0.7], [3.3, 5.3, 1.1]]), ('vent', 'cabinet', [[0.65, 0.02, 0.6], [1.6, 0.16, 1.3]]), ('exit', 'door', [[3.18, 0.02, 0], [4.22, 0.12, 2.25]])]:
117
+ o = self.add(name, cat, box)
118
+ o.links['panel'] = o
119
+ o.joints['j_panel'] = CpuJoint(o, 'RevoluteJoint', 1.75)
120
+ self.add('screwdriver', 'screwdriver', [[2.7, 4.9, 0.83], [2.95, 5.05, 0.88]])
121
+ self.add('key', 'key', [[1.0, -0.005, 0.85], [1.18, 0.04, 0.94]])
122
+ self.add('logic_note', 'paper', [[2.0, 2.8, 0.75], [2.3, 3.0, 0.76]])
123
+ self.add('paper', 'paper', [[0.65, 4.98, 0.79], [0.95, 5.17, 0.8]])
124
+ for i in range(1, 5):
125
+ self.add('vent_screw_' + str(i), 'screw', [[0.67 + i // 3 * 0.82, 0.03, 0.64 + (i - 1) % 2 * 0.59], [0.73 + i // 3 * 0.82, 0.1, 0.7 + (i - 1) % 2 * 0.59]])
126
+
127
+ def add(self, name, category, bounds):
128
+ o = ObjectView(name, category, self, bounds=bounds)
129
+ self.objects[name] = o
130
+ return o
131
+
132
+ def bounds(self, o):
133
+ return o._bounds.copy()
134
+
135
+ def pose(self, o):
136
+ return (o._bounds.mean(0), np.array([0.0, 0.0, 0.0, 1.0]))
137
+
138
+ def set_pose(self, o, pos, q):
139
+ if pos is not None:
140
+ o._bounds += np.asarray(pos) - o._bounds.mean(0)
141
+
142
+ def step(self, n=1):
143
+ pass
144
+
145
+ def capture(self, path, pos, q):
146
+ Image.new('RGB', (1280, 720), (120, 120, 120)).save(path)
147
+ self.pos = np.array(pos)
148
+ self.q = np.array(q)
149
+
150
+ def visible(self, o):
151
+ e = self.escape
152
+ if o.name == 'paper' and (not e.is_open(self.objects['cabinet'], 'j_drawer2')):
153
+ return False
154
+ if o.name == 'screwdriver' and (not e.is_open(self.objects['toolbox'], 'j_panel')):
155
+ return False
156
+ return o.name not in getattr(e, '_hidden', [])
157
+
158
+ def detect(self, path, pos, q):
159
+ out = []
160
+ R = Rotation.from_quat(q).as_matrix()
161
+ for o in self.objects.values():
162
+ if o.name.startswith('drawer') or not self.visible(o):
163
+ continue
164
+ lo, hi = o.aabb
165
+ v = np.array([[x, y, z] for x in [lo[0], hi[0]] for y in [lo[1], hi[1]] for z in [lo[2], hi[2]]])
166
+ v = (v - pos) @ R
167
+ d = -v[:, 2]
168
+ if np.any(d <= 0.02):
169
+ continue
170
+ px = 640 + 640 * v[:, 0] / d
171
+ py = 360 - 640 * v[:, 1] / d
172
+ r = [max(0, int(px.min())), max(0, int(py.min())), min(1279, int(px.max())), min(719, int(py.max()))]
173
+ if r[0] < r[2] and r[1] < r[3]:
174
+ out.append({'cat': o.category, 'center': list((lo + hi) / 2), 'bbox': r})
175
+ return (out, np.full((720, 1280), np.inf, np.float32))
176
+
177
+ def overlap_sphere(self, r, pos, callback, flag):
178
+ self.query_count += 1
179
+ p = np.array(pos)
180
+ for o in self.objects.values():
181
+ if o.name.startswith('drawer'):
182
+ continue
183
+ lo, hi = o.aabb
184
+ if np.linalg.norm(p - np.clip(p, lo, hi)) <= r:
185
+ callback(types.SimpleNamespace(rigid_body='/World/redesign364/' + o.name + '/mesh'))
186
+
187
+ class NativeBackend(CpuBackend):
188
+ native = True
189
+
190
+ def __init__(self, driver):
191
+ self.driver = driver
192
+ self.scene = driver.scene
193
+ self.objects = {}
194
+ self.escape = None
195
+ self.query_count = 0
196
+ s = self.scene
197
+
198
+ def add(name, cat, node):
199
+ o = ObjectView(name, cat, self, node=node)
200
+ self.objects[name] = o
201
+ return o
202
+ cab = add('cabinet', 'cabinet', s.furniture_roots['cabinet'])
203
+ for i in range(1, 4):
204
+ node = s.drawers['drawer' + str(i)]
205
+ p = add('drawer' + str(i), 'drawer', node)
206
+ jn = 'j_drawer' + str(i)
207
+ cab.links[jn[2:]] = p
208
+ cab.joints[jn] = XformJoint(self, node, 'PrismaticJoint', 1, -1, 0.5)
209
+ for name, cat, node, part, axis, sign, upper in [('toolbox', 'cabinet', s.case, s.lid, 0, -1, math.radians(80)), ('vent', 'cabinet', s.grille, s.grille, 2, 1, math.radians(105)), ('exit', 'door', s.door_node, s.door_node, 2, -1, math.radians(103))]:
210
+ o = add(name, cat, node)
211
+ link = ObjectView(name + '_panel', cat, self, node=part)
212
+ o.links['panel'] = link
213
+ o.joints['j_panel'] = XformJoint(self, part, 'RevoluteJoint', axis, sign, upper)
214
+ for name in ['screwdriver', 'key', 'paper', 'logic_note'] + ['vent_screw_' + str(i) for i in range(1, 5)]:
215
+ add(name, 'screw' if name.startswith('vent_screw') else 'paper' if name in ('paper', 'logic_note') else name, s.target_nodes[name])
216
+ self.source_module = driver.level
217
+ self.extra_item_defs = []
218
+ source = getattr(driver.level, 'SOURCES', {})
219
+ labels = getattr(driver.level, 'LABELS', {})
220
+ takeable = set(getattr(driver.level, 'TAKEABLE', ()))
221
+ for key, node in s.target_nodes.items():
222
+ if key in self.objects or key.startswith('drawer') or key == 'cabinet_body':
223
+ continue
224
+ if key not in source and key not in ('round_table', 'workbench', 'rack'):
225
+ continue
226
+ category = 'ball' if key.startswith('ball_') else 'table' if key in ('round_table', 'workbench') else 'rack' if key == 'rack' else str(labels.get(key, key))
227
+ add(key, category, node)
228
+ if key in source:
229
+ parent = source[key]
230
+ jn = None
231
+ part = 0
232
+ if parent and parent.startswith('drawer'):
233
+ part = int(parent[-1])
234
+ parent = 'cabinet'
235
+ jn = 'j_drawer' + str(part)
236
+ elif parent in ('toolbox', 'vent'):
237
+ jn = 'j_panel'
238
+ part = 1
239
+ self.extra_item_defs.append((key, parent or key, jn, part, key not in takeable, ''))
240
+
241
+ def visible(self, o):
242
+ e = self.escape
243
+ if o.name in getattr(e, '_hidden', []):
244
+ return False
245
+ source = getattr(self.source_module, 'SOURCES', {})
246
+ parent = source.get(o.name)
247
+ if o.name == 'key':
248
+ return True
249
+ if parent and parent.startswith('drawer'):
250
+ return e.is_open(self.objects['cabinet'], 'j_drawer' + parent[-1])
251
+ if parent in ('toolbox', 'vent'):
252
+ return e.is_open(self.objects[parent], 'j_panel')
253
+ return True
254
+
255
+ def bounds(self, o):
256
+ tri = self.scene.triangles(o.node).reshape(-1, 3)
257
+ return np.array([tri.min(0), tri.max(0)])
258
+
259
+ def pose(self, o):
260
+ mat = self.scene.G.XformCache().GetLocalToWorldTransform(o.node['prim'])
261
+ p = np.array(mat.ExtractTranslation())
262
+ M = np.array(mat)[:3, :3].T
263
+ M = M / np.maximum(np.linalg.norm(M, axis=0), 1e-12)
264
+ return (p, Rotation.from_matrix(M).as_quat())
265
+
266
+ def set_pose(self, o, pos, q):
267
+ node = o.node
268
+ parent = node['prim'].GetParent()
269
+ mat = self.scene.G.XformCache().GetLocalToWorldTransform(parent)
270
+ kwargs = {}
271
+ if pos is not None:
272
+ kwargs['pos'] = list(mat.GetInverse().Transform(self.scene.F.Vec3d(*map(float, pos))))
273
+ if q is not None:
274
+ M = np.array(mat)[:3, :3].T
275
+ M = M / np.maximum(np.linalg.norm(M, axis=0), 1e-12)
276
+ kwargs['rpy'] = (Rotation.from_matrix(M).inv() * Rotation.from_quat(q)).as_euler('xyz', degrees=True).tolist()
277
+ self.scene.transform(node, **kwargs)
278
+
279
+ def reconcile(self):
280
+ e = self.escape
281
+ if e is None:
282
+ return
283
+ g = self.driver.game
284
+ nodes = list(self.scene.drawers.values()) + [self.scene.lid, self.scene.grille, self.scene.door_node]
285
+ poses = [(n, np.array(n['translate'].Get()), np.array(n['rotate'].Get())) for n in nodes]
286
+ for i in range(1, 4):
287
+ g.opened['drawer' + str(i)] = e.is_open(self.objects['cabinet'], 'j_drawer' + str(i))
288
+ for name in ['toolbox', 'vent']:
289
+ g.opened[name] = e.is_open(self.objects[name], 'j_panel')
290
+ g.opened['exit'] = 'exit' in e.passed_doors
291
+ e.items['key']['behind_glass'] = not e.is_open(self.objects['vent'], 'j_panel')
292
+ g.drawer_unlocked = e.part_locks['cabinet', 2]['unlocked']
293
+ g.toolbox_unlocked = e.part_locks['toolbox', 1]['unlocked']
294
+ g.vent_freed = e.part_locks['vent', 1]['unlocked']
295
+ g.exit_unlocked = e.doors['exit']['unlocked']
296
+ g.exited = bool(e.success)
297
+ g.holding = [e.objs[i]['sim'] for i in e.holding]
298
+ g.taken = {st['name'] for st in e.items.values() if st['taken']}
299
+ self.scene.sync(g)
300
+ for n, p, q in poses:
301
+ self.scene.transform(n, p.tolist(), q.tolist())
302
+
303
+ def step(self, n=1):
304
+ self.reconcile()
305
+ for _ in range(max(1, int(n))):
306
+ self.driver.og.sim.step()
307
+
308
+ def capture(self, path, pos, q):
309
+ self.reconcile()
310
+ R = Rotation.from_quat(q).as_matrix()
311
+ self.driver.raw(pos, np.array(pos) - R[:, 2], warm=8)
312
+ self.driver.clean.save(path)
313
+ self.pos = np.array(pos)
314
+ self.q = np.array(q)
315
+
316
+ def detect(self, path, pos, q):
317
+ out, _ = CpuBackend.detect(self, path, np.asarray(pos, float), np.asarray(q, float))
318
+ pos = np.asarray(pos, float)
319
+ R = Rotation.from_quat(q).as_matrix()
320
+ near = 0.02
321
+ guard_geometry = {}
322
+ for obj in self.objects.values():
323
+ if obj.name.startswith('drawer') or not self.visible(obj):
324
+ continue
325
+ lo, hi = obj.aabb
326
+ corners = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])])
327
+ corner_depth = -((corners - pos) @ R)[:, 2]
328
+ if not (np.any(corner_depth <= near) and np.any(corner_depth > near)):
329
+ continue
330
+ arrays = [self.scene.triangles(n) for n in getattr(obj, 'nodes', [obj.node])]
331
+ arrays = [a for a in arrays if a.size]
332
+ if not arrays:
333
+ continue
334
+ triangles = np.concatenate(arrays)
335
+ world = triangles.reshape(-1, 3)
336
+ guard_geometry[obj.name] = triangles.copy()
337
+ camera = (triangles - pos) @ R
338
+ distance = -camera[:, :, 2]
339
+ points = [camera[distance >= near]]
340
+ for a, b in ((0, 1), (1, 2), (2, 0)):
341
+ da, db = (distance[:, a], distance[:, b])
342
+ crossing = (da >= near) != (db >= near)
343
+ if crossing.any():
344
+ fraction = ((near - da[crossing]) / (db[crossing] - da[crossing]))[:, None]
345
+ points.append(camera[crossing, a] + fraction * (camera[crossing, b] - camera[crossing, a]))
346
+ points = np.concatenate(points)
347
+ if not len(points):
348
+ continue
349
+ px = 640 + 640 * points[:, 0] / -points[:, 2]
350
+ py = 360 - 640 * points[:, 1] / -points[:, 2]
351
+ rect = [max(0, int(px.min())), max(0, int(py.min())), min(1279, int(px.max())), min(719, int(py.max()))]
352
+ if rect[0] < rect[2] and rect[1] < rect[3]:
353
+ out.append({'cat': obj.category, 'center': list((world.min(0) + world.max(0)) / 2), 'bbox': rect})
354
+ self._native_detection_snapshot = {'clean': str(path), 'geometry': guard_geometry}
355
+ depth = np.asarray(self.driver.depth, np.float32)
356
+ return (out, np.repeat(np.repeat(depth, 2, 0), 2, 1))
357
+
358
+ def photo_metadata(self, boxed):
359
+ snapshot = getattr(self, '_native_detection_snapshot', None)
360
+ if snapshot is None:
361
+ return
362
+ boxed = str(boxed)
363
+ path = Path(boxed)
364
+ clean = str(path.with_name(path.stem + '_clean' + path.suffix))
365
+ if clean != snapshot['clean']:
366
+ raise RuntimeError('Native triangle guard is not from this observation')
367
+ self.escape._photo_dets[boxed]['native_near_geometry'] = copy.deepcopy(snapshot['geometry'])
368
+
369
+ def front_mesh_guard(self, esc, C, photo, px, py, oid):
370
+ record = (getattr(esc, '_photo_dets', {}) or {}).get(str(photo), {})
371
+ sim = esc.objs.get(oid, {}).get('sim')
372
+ triangles = (record.get('native_near_geometry') or {}).get(sim)
373
+ if triangles is None:
374
+ return True
375
+ triangles = np.asarray(triangles, float)
376
+ origin, direction, raw = C._ray_at(esc, photo, px, py)
377
+ depth = C._depth_at(esc, photo, px, py)
378
+ if depth is None or not len(triangles):
379
+ return False
380
+ v0 = triangles[:, 0]
381
+ a = triangles[:, 1] - v0
382
+ b = triangles[:, 2] - v0
383
+ cross = np.cross(direction, b)
384
+ det = np.sum(a * cross, axis=1)
385
+ inv = np.divide(1.0, det, out=np.zeros_like(det), where=np.abs(det) > 1e-09)
386
+ relative = origin - v0
387
+ u = np.sum(relative * cross, axis=1) * inv
388
+ q = np.cross(relative, a)
389
+ v = np.sum(q * direction, axis=1) * inv
390
+ t = np.sum(b * q, axis=1) * inv
391
+ hit = (np.abs(det) > 1e-09) & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0)
392
+ if not hit.any():
393
+ return False
394
+ visible = float(depth) * float(np.linalg.norm(raw))
395
+ return bool(np.any(np.abs(t[hit] - visible) <= float(C.FRONT_MARGIN)))
396
+
397
+ def install_colliders(self):
398
+ from pxr import Usd, UsdGeom, UsdPhysics
399
+ og = self.driver.og
400
+ stage = og.sim.stage
401
+ if getattr(og.sim, 'psqi', None) is None:
402
+ raise RuntimeError('Live PhysX query service is required; no silent grid fallback')
403
+ count = 0
404
+ with og.sim.editing_usd():
405
+ root = stage.GetPrimAtPath('/World/redesign364')
406
+ for prim in Usd.PrimRange(root):
407
+ if prim.IsA(UsdGeom.Mesh):
408
+ UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(True)
409
+ UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr('convexHull')
410
+ count += 1
411
+ for name in ['cabinet', 'toolbox', 'vent', 'exit']:
412
+ for link in self.objects[name].links.values():
413
+ api = UsdPhysics.RigidBodyAPI.Apply(link.node['prim'])
414
+ api.CreateKinematicEnabledAttr(True)
415
+ api.CreateRigidBodyEnabledAttr(True)
416
+ og.sim.play()
417
+ og.sim.update_handles()
418
+ self.step(30)
419
+ return count
420
+
421
+ class PilotSession:
422
+
423
+ def __init__(self, backend, out, working=WORKING, E=None, C=None):
424
+ if E is None:
425
+ E, C = load_stack(working)
426
+ from legacy_rooms_bridge import install_mechanism_hooks
427
+ install_mechanism_hooks(E)
428
+ self.E, self.C, self.backend = (E, C, backend)
429
+ self.out = Path(out)
430
+ self.out.mkdir(parents=True, exist_ok=True)
431
+ scene = types.SimpleNamespace(objects=list(backend.objects.values()), object_registry=lambda key, name: backend.objects.get(name))
432
+ ctx = {'env': types.SimpleNamespace(scene=scene), 'E': types.SimpleNamespace(quat_from=quat_from), 'pos': [2.25, 2.25, 1.35], 'shot': backend.capture, 'detect': backend.detect, 'step_sim': backend.step, 'fov_h': lambda: math.pi / 2}
433
+ source = getattr(backend, 'source_module', None)
434
+ note = getattr(source, 'COUNT_NOTE', 'Count coloured balls: RED BLUE YELLOW GREEN.')
435
+ code = getattr(source, 'CODE', '4826')
436
+ drawer_code = getattr(source, 'DRAWER_CODE', '2314')
437
+ item_defs = [('logic_note', 'logic_note', None, 0, True, note), ('paper', 'cabinet', 'j_drawer2', 2, True, code), ('screwdriver', 'toolbox', 'j_panel', 1, False, ''), ('key', 'vent', 'j_panel', 1, False, '')] + list(getattr(backend, 'extra_item_defs', []))
438
+ cfg = {'name': 'legacy_bridge_R01', 'scene': 'programmatic_R01', 'start': {'xy': [2.25, 2.25], 'yaw_deg': 90}, 'max_steps': 150, 'native_use_visual': False, 'native_devices_visual': False, 'items': [{'id': n, 'name': n, 'kind': 'tool' if not fixed else 'paper', 'text': text} for n, parent, jn, part, fixed, text in item_defs], 'part_locks': [{'container': 'cabinet', 'part': 2, 'lock': drawer_code}, {'container': 'toolbox', 'part': 1, 'lock': code}, {'container': 'vent', 'part': 1}], 'doors': [{'name': 'exit', 'key': 'key', 'exit': True}], 'gadgets': [{'name': 'vent_screw_' + str(i), 'type': 'reveal', 'tool': 'screwdriver', 'flag': 'vent_screws_freed'} for i in range(1, 5)]}
439
+
440
+ class NativeEscape(E.Escape):
441
+
442
+ def _visual_flag_complete(esc, flag, on):
443
+ if flag == 'vent_screws_freed':
444
+ esc._unlock_parts([['vent', 1]])
445
+ return True
446
+ return super()._visual_flag_complete(flag, on)
447
+ self.esc = NativeEscape(ctx, cfg, self.out)
448
+ backend.escape = self.esc
449
+ e = self.esc
450
+ for attribute, method in (('_native_photo_metadata_hook', 'photo_metadata'), ('_native_front_mesh_guard', 'front_mesh_guard')):
451
+ hook = getattr(backend, method, None)
452
+ if callable(hook):
453
+ setattr(e, attribute, hook)
454
+ for i, o in enumerate(backend.objects.values(), 1):
455
+ e.objs[i] = {'id': i, 'sim': o.name, 'cat': getattr(source, 'LABELS', {}).get('toolbox', 'metal toolbox') if o.name == 'toolbox' else o.category, 'center': o.aabb.mean(0).tolist()}
456
+ e.by_sim[o.name] = i
457
+ for name, parent, jn, part, fixed, text in item_defs:
458
+ st = {'id': name, 'name': name, 'container': parent, 'joint': jn, 'part': part, 'kind': 'drawer' if name == 'paper' else 'loose', 'taken': False, 'fixed': fixed, 'text': text, 'lockd': None, 'unlocked': True}
459
+ if jn:
460
+ st['rel'] = e._rel(backend.objects[parent].links[jn[2:]], backend.objects[name])
461
+ e.items[name] = st
462
+ e._wallmap = np.zeros((320, 320), bool)
463
+ e._wallmap[160:270, 160:250] = True
464
+ e._door_boxes = {'exit': tuple(backend.objects['exit'].aabb)}
465
+ e._window_boxes = {}
466
+ e._semmap = np.ones((1600, 1600), np.uint8)
467
+ e._roomcats = ['workroom']
468
+ e._fronts.update({name: np.array([0.0, -1.0]) for name in ['cabinet', 'toolbox', 'vent']})
469
+ e.items['key']['behind_glass'] = True
470
+ self.key_to_oid = {name: oid for name, oid in e.by_sim.items()}
471
+ self.key_to_oid.update({key: e.by_sim['cabinet'] for key in ['drawer1', 'drawer2', 'drawer3', 'cabinet_body']})
472
+ self.backend.key_to_sim = {key: e.objs[oid]['sim'] for key, oid in self.key_to_oid.items()}
473
+ self.backend.sim_to_key = {name: name for name in self.backend.objects}
474
+ self.backend.part_aliases = {key: ('cabinet', i) for i, key in enumerate(['drawer1', 'drawer2', 'drawer3'], 1)}
475
+ self.identity = {name: getattr(E.Escape, name) for name in ['act', 'a_open', 'a_close', 'a_take', 'a_unlock', 'a_use']}
476
+
477
+ def observe(self, pos, yaw, pitch=0.0):
478
+ e = self.esc
479
+ e.pos = np.array(pos, float)
480
+ e.cam_z = float(pos[2])
481
+ e.yaw = float(yaw)
482
+ e._claw_pitch = float(pitch)
483
+ path, _ = self.C.shoot(e, 'pilot_observe')
484
+ e._claw_photos = [path]
485
+ return path
486
+
487
+ def point_for(self, name):
488
+ e = self.esc
489
+ oid = e.by_sim[name]
490
+ box = e._photo_dets[e._claw_photos[-1]]['rects'][oid]
491
+ return [(box[0] + box[2]) / 4, (box[1] + box[3]) / 4]
492
+
493
+ def act(self, a):
494
+ e = self.esc
495
+ e.t += 1
496
+ trace = []
497
+
498
+ def profile(frame, event, arg):
499
+ if event == 'call' and frame.f_code.co_name in ('engine_act', 'act', '_act_core', '_at_point', '_front_thing', '_layer', '_lock_target', 'a_open', 'a_close', 'a_unlock', 'a_take', 'a_use', '_move', '_body_hits', 'set_joint') and frame.f_code.co_filename.endswith(('_escape_bind_ownedvisual1010.py', '_escape_claw_nativefresh1009.py', 'unified_protocol.py')):
500
+ trace.append([frame.f_code.co_name, frame.f_code.co_filename, frame.f_code.co_firstlineno])
501
+ previous = sys.getprofile()
502
+ sys.setprofile(profile)
503
+ try:
504
+ result = e.act(dict(a))
505
+ finally:
506
+ sys.setprofile(previous)
507
+ e.items['key']['behind_glass'] = not e.is_open(self.backend.objects['vent'], 'j_panel')
508
+ self.last_call_trace = trace
509
+ if not e.turns or e.turns[-1].get('turn') != e.t:
510
+ e.turns.append({'turn': e.t, 'action': dict(a), 'result': dict(result)})
511
+ if isinstance(self.backend, NativeBackend):
512
+ self.backend.reconcile()
513
+ return result
514
+
515
+ def notes(self):
516
+ return self.esc.notes()
517
+
518
+ def native_gate(self):
519
+ if not self.backend.native:
520
+ raise RuntimeError('CPU fixture cannot pass native gate')
521
+ count = self.backend.install_colliders()
522
+ hits = self.C._body_hits(self.esc, 2.15, 2.9)
523
+ if not hits:
524
+ raise RuntimeError('R01 central table produced no PhysX body hit; colliders are not verified')
525
+ return {'collision_meshes': count, 'physx_obstacle_probe': sorted(hits), 'native_visual_verified': False}
526
+
527
+ def attach(driver, out, working=WORKING, E=None, C=None):
528
+ session = PilotSession(NativeBackend(driver), out, working, E, C)
529
+ session.native_gate()
530
+ return session
531
+
532
+ def cpu_test():
533
+ import tempfile
534
+ backend = CpuBackend()
535
+ stub = types.SimpleNamespace(sim=types.SimpleNamespace(is_playing=lambda: False, psqi=types.SimpleNamespace(overlap_sphere=backend.overlap_sphere)))
536
+ original = sys.modules.get('omnigibson')
537
+ sys.modules['omnigibson'] = stub
538
+ utilities = types.ModuleType('omnigibson.utils')
539
+ assets = types.ModuleType('omnigibson.utils.asset_utils')
540
+ assets.get_dataset_path = lambda *a: (_ for _ in ()).throw(RuntimeError('CPU fixture attempted dataset access'))
541
+ prior_utils = sys.modules.get('omnigibson.utils')
542
+ prior_assets = sys.modules.get('omnigibson.utils.asset_utils')
543
+ sys.modules['omnigibson.utils'] = utilities
544
+ sys.modules['omnigibson.utils.asset_utils'] = assets
545
+ try:
546
+ with tempfile.TemporaryDirectory(prefix='cpu_', dir=ROOT) as td:
547
+ s = PilotSession(backend, td)
548
+ s.observe([0.8, 4.0, 1.35], math.pi / 2, -30)
549
+ p = s.point_for('cabinet')
550
+ checks = []
551
+
552
+ def ck(name, value):
553
+ assert value, name
554
+ checks.append(name)
555
+ ck('actual inherited a_open', type(s.esc).a_open is s.E.Escape.a_open)
556
+ ck('actual inherited a_take', type(s.esc).a_take is s.E.Escape.a_take)
557
+ ck('missing part rejected', not s.act({'action': 'open', 'point': p, 'target': 'cabinet'})['ok'])
558
+ ck('wrong part rejected', not s.act({'action': 'open', 'point': p, 'target': 'cabinet', 'part': 99})['ok'])
559
+ ck('locked middle drawer rejected', not s.act({'action': 'open', 'point': p, 'target': 'cabinet', 'part': 2})['ok'])
560
+ ck('wrong code rejected', not s.act({'action': 'unlock', 'point': p, 'target': 'cabinet', 'part': 2, 'code': '0000'})['ok'])
561
+ ck('correct code uses old unlock', s.act({'action': 'unlock', 'point': p, 'target': 'cabinet', 'part': 2, 'code': '2314'})['ok'])
562
+ ck('open explicit middle part', s.act({'action': 'open', 'point': p, 'target': 'cabinet', 'part': 2})['ok'])
563
+ trace = s.last_call_trace
564
+ ck('actual E/C dispatch frames present', all((any((x[0] == n for x in trace)) for n in ['_act_core', '_at_point', 'a_open', '_layer', 'set_joint'])))
565
+ ck('actual old joint state open', s.esc.is_open(backend.objects['cabinet'], 'j_drawer2'))
566
+ p = s.point_for('cabinet')
567
+ ck('close explicit middle part', s.act({'action': 'close', 'point': p, 'target': 'cabinet', 'part': 2})['ok'])
568
+ ck('unheld key cannot be used even with a part field', not s.act({'action': 'use', 'point': p, 'target': 'cabinet', 'item': 'key', 'part': 1})['ok'])
569
+ s.observe([0.8, 2.25, 1.35], math.pi / 2, -15)
570
+ far = s.point_for('cabinet')
571
+ ck('old reach denies far cabinet', not s.act({'action': 'open', 'point': far, 'target': 'cabinet', 'part': 1})['ok'])
572
+ s.observe([0.8, 4.0, 1.35], math.pi / 2, -15)
573
+ moved = s.act({'action': 'walk', 'distance': 1.0})
574
+ move_trace = s.last_call_trace
575
+ ck('old movement stops partway at fixture obstacle', bool(moved.get('blocked')) and 0 < float(moved.get('moved', 0)) < 1)
576
+ ck('old PhysX query branch executed against explicit CPU fixture', backend.query_count > 0 and any((x[0] == '_body_hits' for x in move_trace)))
577
+ s.observe([2.8, 4.0, 1.35], math.pi / 2, -30)
578
+ tb = s.point_for('toolbox')
579
+ ck('toolbox wrong code denied', not s.act({'action': 'unlock', 'point': tb, 'target': 'cabinet', 'part': 1, 'code': '1111'})['ok'])
580
+ ck('toolbox correct code accepted', s.act({'action': 'unlock', 'point': tb, 'target': 'cabinet', 'part': 1, 'code': '4826'})['ok'])
581
+ ck('toolbox lid opens through old dispatcher', s.act({'action': 'open', 'point': tb, 'target': 'cabinet', 'part': 1})['ok'])
582
+ driver_point = s.point_for('screwdriver')
583
+ take = s.act({'action': 'take', 'point': driver_point, 'target': 'screwdriver'})
584
+ take_trace = s.last_call_trace
585
+ ck('old a_take stores real legacy inventory id', take['ok'] and s.esc.by_sim['screwdriver'] in s.esc.holding)
586
+ ck('old take call stack executed', any((x[0] == 'a_take' for x in take_trace)))
587
+ ck('taken object hidden by old _hide', 'screwdriver' in s.esc._hidden)
588
+ return {'movement_call_trace': move_trace, 'take_call_trace': take_trace, 'passed': len(checks), 'checks': checks, 'scope': 'CPU fixture geometry and transport; actual legacy functions by reference, not native acceptance', 'call_trace': trace, 'native_visual_verified': False, 'source_files': {str(Path(s.E.__file__)): hashlib.sha256(Path(s.E.__file__).read_bytes()).hexdigest(), str(Path(s.C.__file__)): hashlib.sha256(Path(s.C.__file__).read_bytes()).hexdigest()}}
589
+ finally:
590
+ if original is None:
591
+ sys.modules.pop('omnigibson', None)
592
+ else:
593
+ sys.modules['omnigibson'] = original
594
+ for name, old in [('omnigibson.utils', prior_utils), ('omnigibson.utils.asset_utils', prior_assets)]:
595
+ if old is None:
596
+ sys.modules.pop(name, None)
597
+ else:
598
+ sys.modules[name] = old
599
+ if __name__ == '__main__':
600
+ result = cpu_test()
601
+ (ROOT / 'CPU_RESULT.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf8')
602
+ print(json.dumps({k: v for k, v in result.items() if not k.endswith('call_trace')}, ensure_ascii=False))
runtime/native_runtime/legacy_r02_bridge.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import copy, hashlib, importlib.util, json, math, sys, types
3
+ import numpy as np
4
+ from scipy.spatial.transform import Rotation
5
+ from legacy_r01_pilot import ObjectView, CpuBackend, quat_from, load_stack
6
+ from legacy_rooms_bridge import RoomsBackend, RoomsSession, UnsupportedBinding, path_object, read, put, rule_matches, install_mechanism_hooks
7
+ BASE = Path(__file__).resolve().parent.parent
8
+ COMMON_NAMES = ('act', 'a_open', 'a_close', 'a_take', 'a_unlock', 'a_use', 'reach_item')
9
+ TILES = ('tile_1', 'tile_2', 'tile_3')
10
+
11
+ class R02Backend(RoomsBackend):
12
+
13
+ def __init__(self, driver, owners, motions, predicates=None):
14
+ self.labels = dict(driver.level.LABELS)
15
+ if not hasattr(driver.game, 'LABELS'):
16
+ driver.game.LABELS = self.labels
17
+ super().__init__(driver, 'R02', owners, motions, predicates)
18
+ for key, owner in [('cabinet_body', 'low_drawer_cabinet'), ('light_table', 'central_light_table')]:
19
+ old = self.key_to_sim.pop(key, None)
20
+ if old:
21
+ self.objects.pop(old, None)
22
+ self.sim_to_key.pop(old, None)
23
+ self.key_to_sim[key] = owner
24
+ for key in TILES:
25
+ name = self.key_to_sim.get(key)
26
+ if name is None:
27
+ raise UnsupportedBinding('Missing actual photo panel ' + key)
28
+ self.objects[name].category = 'electric switch'
29
+ if 'battery_slot' not in self.key_to_sim:
30
+ raise UnsupportedBinding('Missing actual battery socket')
31
+
32
+ def visible(self, o):
33
+ e = self.escape
34
+ if e is not None and o.name in getattr(e, '_hidden', []):
35
+ return False
36
+ row = self.item_metadata.get(o.name)
37
+ if row and e is not None:
38
+ st = e.items.get(o.name, {})
39
+ if st.get('gone'):
40
+ return False
41
+ owner = row.get('owner_id')
42
+ part = row.get('part')
43
+ if owner and part and (not e.is_open(self.objects[owner], 'j_part_' + str(part))):
44
+ return False
45
+ return super().visible(o)
46
+
47
+ class R02Session(RoomsSession):
48
+
49
+ def __init__(self, backend, out, E, C):
50
+ install_mechanism_hooks(E)
51
+ identities = {n: getattr(E.Escape, n) for n in COMMON_NAMES}
52
+ point_identity = C._at_point
53
+ self.backend = backend
54
+ backend.session = self
55
+ self.driver = backend.driver
56
+ self.game = backend.game
57
+ self.E = E
58
+ self.C = C
59
+ self.extra_images = []
60
+ self.last_call_trace = []
61
+ self.source_mechanism = self.game.act
62
+ self.mechanism_state = {'powered': bool(self.game.powered), 'tiles': list(self.game.tiles), 'puzzle_solved': bool(self.game.puzzle_solved)}
63
+ out = Path(out)
64
+ out.mkdir(parents=True, exist_ok=True)
65
+ cfg = {'name': 'legacy_bridge_R02', 'scene': 'programmatic_R02', 'start': {'xy': list(self.driver.pos[:2]), 'yaw_deg': math.degrees(self.driver.yaw)}, 'max_steps': 150, 'native_devices_visual': False, 'native_use_visual': False, 'items': [], 'part_locks': [], 'doors': [{'name': backend.exit_name, 'key': 'key', 'exit': True}], 'gadgets': []}
66
+ for owner, part in backend.part_bindings:
67
+ row = {'container': owner, 'part': part}
68
+ if owner == 'camera_storage_case':
69
+ row['lock'] = str(self.driver.level.CODE)
70
+ cfg['part_locks'].append(row)
71
+ for name, row in backend.item_metadata.items():
72
+ cfg['items'].append({'id': row['item_key'], 'name': name, 'kind': 'tool', 'text': self.clue_text(row['item_key'])})
73
+ for key in TILES + ('battery_slot',):
74
+ cfg['gadgets'].append({'name': backend.key_to_sim[key], 'type': 'native_mechanism'})
75
+ ctx = {'env': types.SimpleNamespace(scene=types.SimpleNamespace(objects=list(backend.objects.values()), object_registry=lambda k, n: backend.objects.get(n))), 'E': types.SimpleNamespace(quat_from=quat_from), 'pos': list(self.driver.pos), 'shot': backend.capture, 'detect': backend.detect, 'step_sim': backend.step, 'fov_h': lambda: math.pi / 2}
76
+ e = self.esc = E.Escape(ctx, cfg, out)
77
+ backend.escape = e
78
+ for attribute, method in (('_native_photo_metadata_hook', 'photo_metadata'), ('_native_front_mesh_guard', 'front_mesh_guard')):
79
+ hook = getattr(backend, method, None)
80
+ if callable(hook):
81
+ setattr(e, attribute, hook)
82
+ e._native_mechanism_hook = self.mechanism
83
+ e._native_mechanism_targets = {backend.key_to_sim[k] for k in TILES + ('battery_slot',)}
84
+ for i, o in enumerate(backend.objects.values(), 1):
85
+ e.objs[i] = {'id': i, 'sim': o.name, 'cat': o.category, 'center': o.aabb.mean(0).tolist()}
86
+ e.by_sim[o.name] = i
87
+ self.key_to_oid = {k: e.by_sim[name] for k, name in backend.key_to_sim.items()}
88
+ for key, (owner, part) in backend.part_aliases.items():
89
+ self.key_to_oid[key] = e.by_sim[owner]
90
+ for name, o in backend.objects.items():
91
+ if o.joints:
92
+ e._parts[name] = [(jn, 'drawer' if 'Prismatic' in str(j.joint_type) else 'door') for jn, j in o.joints.items()]
93
+ e._closed_box[name] = tuple(o.aabb.copy())
94
+ for name, row in backend.item_metadata.items():
95
+ owner = row.get('owner_id') or name
96
+ part = row.get('part') or 0
97
+ jn = 'j_part_' + str(part) if part else None
98
+ st = {'id': row['item_key'], 'name': name, 'container': owner, 'part': part, 'joint': jn, 'kind': row.get('kind', 'loose'), 'fixed': bool(row.get('fixed')), 'text': self.clue_text(row['item_key']), 'lockd': None, 'unlocked': True, 'taken': False}
99
+ if owner not in backend.objects:
100
+ raise UnsupportedBinding('Unknown item container ' + owner)
101
+ if jn:
102
+ st['rel'] = e._rel(backend.objects[owner].links[jn[2:]], backend.objects[name])
103
+ e.items[name] = st
104
+ e._wallmap = np.zeros((640, 640), bool)
105
+ res = e.GUARD_RES
106
+ e._wallmap[320:320 + int(5.2 / res), 320:320 + int(5.2 / res)] = True
107
+ e._semmap = np.ones((3200, 3200), np.uint8)
108
+ e._roomcats = ['photographic_studio']
109
+ e._door_boxes = backend._door_boxes
110
+ e._window_boxes = {}
111
+ e._fronts.update({'low_drawer_cabinet': np.array([1.0, 0.0]), 'central_light_table': np.array([0.0, -1.0]), 'camera_storage_case': np.array([0.0, -1.0])})
112
+ self.generic_identity = identities
113
+ self.point_identity = point_identity
114
+ assert all((getattr(E.Escape, n) is f for n, f in identities.items()))
115
+ assert C._at_point is point_identity
116
+ self.project()
117
+
118
+ def clue_text(self, key):
119
+ for k, date, number in self.driver.level.PHOTOS:
120
+ if k == key:
121
+ return date + '\nFILE ' + number
122
+ if key == 'rotation_note':
123
+ return 'Press a panel to rotate it 90°.'
124
+ return ''
125
+
126
+ def project(self):
127
+ e = getattr(self, 'esc', None)
128
+ b = self.backend
129
+ g = self.game
130
+ if e is None:
131
+ return
132
+ saved = []
133
+ for binding in list(b.part_bindings.values()) + [b.door_binding]:
134
+ node = path_object(b.scene, binding['node_access'])
135
+ saved.append((node, list(node['translate'].Get()), list(node['rotate'].Get())))
136
+ for (owner, part), binding in b.part_bindings.items():
137
+ put(g.__dict__, binding['state_path'], bool(e.is_open(b.objects[owner], 'j_part_' + str(part))))
138
+ for key, val in self.mechanism_state.items():
139
+ setattr(g, key, copy.deepcopy(val))
140
+ g.case_unlocked = bool(e.part_locks['camera_storage_case', 1]['unlocked'])
141
+ g.opened['exit'] = bool(e.is_open(b.objects[b.exit_name], 'j_panel'))
142
+ g.exit_unlocked = bool(e.doors[b.exit_name]['unlocked'])
143
+ g.exited = bool(e.success)
144
+ g.holding = [b.sim_to_key[e.objs[i]['sim']] for i in e.holding]
145
+ g.taken = {b.sim_to_key[name] for name, st in e.items.items() if st.get('taken') or st.get('gone') or e.marks.get('took ' + st['id']) is not None}
146
+ for name, row in b.item_metadata.items():
147
+ owner = row.get('owner_id')
148
+ part = row.get('part')
149
+ if owner and part:
150
+ e.items[name]['behind_glass'] = not e.is_open(b.objects[owner], 'j_part_' + str(part))
151
+ state = g.snapshot()
152
+ for (owner, part), binding in b.part_bindings.items():
153
+ rec = e.part_locks[owner, part]
154
+ req = binding['opening_requirements']
155
+ if req.get('status') != 'executable_structured':
156
+ raise UnsupportedBinding('Unvalidated R02 opening gate')
157
+ if not rec.get('lockd'):
158
+ rec['unlocked'] = bool(rule_matches(req['rule'], state, b.predicates))
159
+ b.scene.sync(g)
160
+ for node, t, r in saved:
161
+ b.scene.transform(node, t, r)
162
+
163
+ def mechanism(self, kind, name, item_name=None, a=None):
164
+ b = self.backend
165
+ e = self.esc
166
+ g = self.game
167
+ key = b.sim_to_key.get(name)
168
+ item = b.sim_to_key.get(item_name)
169
+ self.driver.current_hit = {'key': key, 'source': 'actual_common_legacy_resolution'}
170
+ if kind == 'press':
171
+ if key not in TILES:
172
+ raise UnsupportedBinding('Unsupported R02 press ' + str(key))
173
+ elif kind == 'use':
174
+ if key != 'battery_slot' or item != 'battery':
175
+ return {'ok': False, 'text': 'You cannot use this item on this object.', 'images': []}
176
+ else:
177
+ raise UnsupportedBinding('Unsupported R02 mechanism action ' + str(kind))
178
+ self.project()
179
+ before = g.snapshot()
180
+ a = {'action': kind, '_hit364': key, '_validated364': True}
181
+ if item is not None:
182
+ a['item'] = b.labels[item]
183
+ result = self.source_mechanism(a)
184
+ if not result.get('ok'):
185
+ self.project()
186
+ return result
187
+ if kind == 'use':
188
+ st = e.items[item_name]
189
+ try:
190
+ e._slot_place(e.gadgets[name], st)
191
+ except Exception as exc:
192
+ self.project()
193
+ raise UnsupportedBinding('Old battery placement failed; no Game fallback') from exc
194
+ st['gone'] = True
195
+ e._hide(item_name)
196
+ e.gadgets[name]['done'] = True
197
+ self.mechanism_state.update(powered=bool(g.powered), tiles=list(g.tiles), puzzle_solved=bool(g.puzzle_solved))
198
+ self.project()
199
+ if hasattr(b.scene, 'animate'):
200
+ b.scene.animate(self.driver, before)
201
+ return result
202
+
203
+ def act(self, action):
204
+ self.esc._native_public_kind = action.get('action')
205
+ self.esc.t = int(getattr(self.driver, '_legacy_action_step', int(getattr(self.driver, 'step', 0)) + 1))
206
+ trace = []
207
+
208
+ def profile(frame, event, arg):
209
+ if event == 'call' and frame.f_code.co_name in ('engine_act', 'act', '_act_core', '_at_point', '_layer', '_lock_target', 'a_open', 'a_close', 'a_unlock', 'a_take', 'a_use', 'reach_item', '_move', '_body_hits', 'set_joint', '_slot_place'):
210
+ trace.append([frame.f_code.co_name, frame.f_code.co_filename, frame.f_code.co_firstlineno])
211
+ prior = sys.getprofile()
212
+ sys.setprofile(profile)
213
+ try:
214
+ result = self.esc.act(dict(action))
215
+ finally:
216
+ sys.setprofile(prior)
217
+ self.last_call_trace = trace
218
+ self.project()
219
+ self.driver.pos = self.esc.pos.copy()
220
+ self.driver.yaw = float(self.esc.yaw)
221
+ self.driver.pitch = math.radians(getattr(self.esc, '_claw_pitch', 0.0))
222
+ assert all((getattr(self.E.Escape, n) is f for n, f in self.generic_identity.items()))
223
+ assert self.C._at_point is self.point_identity
224
+ return result
225
+
226
+ def attach(driver, out, working=BASE / 'working', owner_map=BASE / 'OWNER_PART_MAP.json', motion_map=BASE / 'MOTION_BINDINGS.json', predicates=None, E=None, C=None):
227
+ if Path(driver.level.__file__).stem != 'level_R02':
228
+ raise UnsupportedBinding('R02 bridge refuses another room')
229
+ owners = read(owner_map)['levels']['R02']
230
+ motions = read(motion_map)['levels']['R02']
231
+ if hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest() != motions['source_sha256']:
232
+ raise UnsupportedBinding('R02 source differs frozen motion SHA')
233
+ if E is None:
234
+ E, C = load_stack(working)
235
+ if C is None:
236
+ raise UnsupportedBinding('Both actual legacy E and C are required')
237
+ backend = R02Backend(driver, owners, motions, predicates)
238
+ session = R02Session(backend, out, E, C)
239
+ session.native_gate()
240
+ return session
241
+
242
+ def static_check(owner_map=BASE / 'OWNER_PART_MAP.json', motion_map=BASE / 'MOTION_BINDINGS.json'):
243
+ owners = read(owner_map)['levels']['R02']
244
+ motions = read(motion_map)['levels']['R02']
245
+ expected = {(o['owner_id'], p['part']) for o in owners['owners'] for p in o['parts']}
246
+ actual = {(x['owner_id'], x['part']) for x in motions['bindings']}
247
+ assert expected == actual and len(actual) == 4
248
+ assert {x['target_key'] for x in motions['contents']} == {'battery', 'key', 'photo_1', 'photo_2', 'photo_3', 'photo_4', 'rotation_note'}
249
+ return {'room': 'R02', 'owners': 3, 'parts': 4, 'contents': 7, 'common_methods_overridden': [], 'SDK_or_GPU_started': False, 'native_verified': False}
250
+
251
+ def cpu_test(working=BASE / 'working', owner_map=BASE / 'OWNER_PART_MAP.json', motion_map=BASE / 'MOTION_BINDINGS.json'):
252
+ import contextlib, tempfile
253
+ from legacy_r01_pilot import PilotSession
254
+
255
+ class Op:
256
+
257
+ def __init__(self, v):
258
+ self.v = list(v)
259
+
260
+ def Get(self):
261
+ return tuple(self.v)
262
+
263
+ def Set(self, v):
264
+ self.v = list(map(float, v))
265
+
266
+ class FixtureScene:
267
+
268
+ def __init__(self, motions):
269
+ self.groups = {}
270
+ self.target_nodes = {}
271
+ boxes = {'low_drawer_cabinet': [[0.07, 3.4, 0], [0.6, 4.4, 0.7]], 'central_light_table': [[2.0, 2.2, 0], [3.3, 3.03, 0.78]], 'camera_storage_case': [[1.2, 4.5, 0.58], [2.1, 5.05, 0.92]], 'room_exit_door': [[0.03, 0.65, 0], [0.12, 1.75, 2.27]]}
272
+ aliases = {'low_drawer_cabinet': 'cabinet_body', 'central_light_table': 'light_table', 'camera_storage_case': 'camera_case'}
273
+ for owner, key in aliases.items():
274
+ n = self.node(key, boxes[owner])
275
+ self.groups[key] = n
276
+ self.target_nodes[key] = n
277
+ self.groups['cabinet_root'] = self.groups['cabinet_body']
278
+ self.door_node = self.node('door_node', boxes['room_exit_door'])
279
+ for row in motions['bindings'] + motions['door_bindings']:
280
+ name = row['node_access']
281
+ owner = row['owner_id']
282
+ node = self.node(name, boxes[owner], row['motion']['closed'] if row['motion']['kind'] == 'translate' else row['pivot_local'], row['motion']['closed'] if row['motion']['kind'] == 'rotate' else [0, 0, 0])
283
+ if name in ('battery_drawer', 'storage_drawer'):
284
+ node['parent_R'] = Rotation.from_euler('z', 90, degrees=True).as_matrix()
285
+ setattr(self, name, node)
286
+ self.groups['case_lid'] = self.lid
287
+ content = {'battery': [[0.29, 3.84, 0.47], [0.39, 3.96, 0.54]], 'key': [[1.58, 4.79, 0.66], [1.73, 4.91, 0.69]], 'rotation_note': [[2.07, 2.33, 0.81], [2.93, 2.47, 0.82]]}
288
+ for i in range(1, 5):
289
+ x = 2.42 if i % 2 else 2.88
290
+ y = 2.4 if i < 3 else 2.76
291
+ content['photo_' + str(i)] = [[x - 0.16, y - 0.07, 0.53], [x + 0.16, y + 0.07, 0.54]]
292
+ for key, box in content.items():
293
+ self.target_nodes[key] = self.node(key, box)
294
+ for i, x in enumerate([2.12, 2.48, 2.84], 1):
295
+ self.target_nodes['tile_' + str(i)] = self.node('tile_' + str(i), [[x - 0.12, 2.6, 0.82], [x + 0.12, 2.84, 0.85]])
296
+ self.target_nodes['battery_slot'] = self.node('battery_slot', [[3.06, 2.59, 0.82], [3.26, 2.73, 0.89]])
297
+ self.target_nodes['case_lid'] = self.lid
298
+
299
+ def node(self, name, box, t=(0, 0, 0), r=(0, 0, 0)):
300
+ t = [0, 0, 0] if t is None else t
301
+ return {'_name': name, 'box': np.array(box, float), 'offset': np.zeros(3), 'base_t': np.array(t, float), 'translate': Op(t), 'rotate': Op(r), 'parent_R': np.eye(3)}
302
+
303
+ def transform(self, node, pos=None, rpy=None):
304
+ if pos is not None:
305
+ node['translate'].Set(pos)
306
+ if rpy is not None:
307
+ node['rotate'].Set(rpy)
308
+
309
+ def triangles(self, node):
310
+ shift = node['offset'] + node['parent_R'] @ (np.array(node['translate'].Get()) - node['base_t'])
311
+ lo, hi = node['box'] + shift
312
+ return np.array([[x, y, z] for x in [lo[0], hi[0]] for y in [lo[1], hi[1]] for z in [lo[2], hi[2]]])
313
+
314
+ def sync(self, g):
315
+ pass
316
+
317
+ def animate(self, *a):
318
+ pass
319
+
320
+ class FixtureBackend(R02Backend):
321
+ native = False
322
+
323
+ def pose(self, o):
324
+ return (self.bounds(o).mean(0), np.array([0.0, 0.0, 0.0, 1.0]))
325
+
326
+ def set_pose(self, o, pos, q):
327
+ if pos is not None:
328
+ o.node['offset'] += np.asarray(pos) - self.bounds(o).mean(0)
329
+
330
+ def step(self, n=1):
331
+ pass
332
+
333
+ def capture(self, *a):
334
+ return CpuBackend.capture(self, *a)
335
+
336
+ def detect(self, *a):
337
+ return CpuBackend.detect(self, *a)
338
+
339
+ def overlap_sphere(self, *a):
340
+ return CpuBackend.overlap_sphere(self, *a)
341
+ sp = Path(read(motion_map)['levels']['R02']['source_path'])
342
+ sys.path.insert(0, str(working / 'native_runtime'))
343
+ spec = importlib.util.spec_from_file_location('_r02_fixture_level', sp)
344
+ level = importlib.util.module_from_spec(spec)
345
+ spec.loader.exec_module(level)
346
+ motions = read(motion_map)['levels']['R02']
347
+ owners = read(owner_map)['levels']['R02']
348
+ driver = types.SimpleNamespace(level=level, game=level.Game(), scene=FixtureScene(motions), pos=np.array([1.25, 3.9, 1.35]), yaw=math.pi, pitch=0.0, step=0)
349
+ ordinary_calls = []
350
+ original_game_act = driver.game.act
351
+
352
+ def mechanism_only(a):
353
+ if not (a.get('action') == 'press' and a.get('_hit364') in TILES or (a.get('action') == 'use' and a.get('_hit364') == 'battery_slot')):
354
+ ordinary_calls.append(dict(a))
355
+ raise AssertionError('Native Game ordinary-action fallback')
356
+ return original_game_act(a)
357
+ driver.game.act = mechanism_only
358
+ backend = FixtureBackend(driver, owners, motions)
359
+ prior = {name: sys.modules.get(name) for name in ['omnigibson', 'omnigibson.utils', 'omnigibson.utils.asset_utils']}
360
+ stub = types.SimpleNamespace(sim=types.SimpleNamespace(is_playing=lambda: False, psqi=types.SimpleNamespace(overlap_sphere=backend.overlap_sphere)))
361
+ sys.modules['omnigibson'] = stub
362
+ sys.modules['omnigibson.utils'] = types.ModuleType('omnigibson.utils')
363
+ assets = types.ModuleType('omnigibson.utils.asset_utils')
364
+ assets.get_dataset_path = lambda *a: (_ for _ in ()).throw(AssertionError('SDK/dataset in CPU fixture'))
365
+ sys.modules['omnigibson.utils.asset_utils'] = assets
366
+ try:
367
+ with tempfile.TemporaryDirectory(prefix='r02_legacy_cpu_') as td:
368
+ E, C = load_stack(working)
369
+ s = R02Session(backend, td, E, C)
370
+ e = s.esc
371
+ checks = []
372
+
373
+ def ck(name, value):
374
+ if not value:
375
+ raise AssertionError(name)
376
+ checks.append(name)
377
+ ck('common legacy methods identical', all((getattr(E.Escape, n) is f for n, f in s.generic_identity.items())))
378
+ ck('point parser unchanged', C._at_point is s.point_identity)
379
+ ck('four old native part joints', len(backend.part_bindings) == 4)
380
+ ck('fixed photographs and paper remain fixed', all((e.items[backend.key_to_sim[k]]['fixed'] for k in ['photo_1', 'photo_2', 'photo_3', 'photo_4', 'rotation_note'])))
381
+ PilotSession.observe(s, [1.25, 3.9, 1.35], math.pi, -45)
382
+ p = PilotSession.point_for(s, 'low_drawer_cabinet')
383
+ ck('old public missing-part rejection', not s.act(dict(action='open', point=p, target='cabinet'))['ok'])
384
+ ck('old public part99 rejection', not s.act(dict(action='open', point=p, target='cabinet', part=99))['ok'])
385
+ opened = s.act(dict(action='open', point=p, target='cabinet', part=1))
386
+ ck('old public upper drawer opens', opened['ok'])
387
+ trace = list(s.last_call_trace)
388
+ ck('old open call frames', all((any((v[0] == n for v in trace)) for n in ['_at_point', 'a_open', '_layer', 'set_joint'])))
389
+ bid = e.by_sim[backend.key_to_sim['battery']]
390
+ ck('old a_take actual battery inventory', e.a_take({'item': bid})['ok'] and bid in e.holding)
391
+ s.project()
392
+ e.pos = np.array([2.65, 1.65, 1.35])
393
+ tid = e.by_sim[backend.key_to_sim['tile_1']]
394
+ ck('unpowered panel rejected after old press reach', not e.a_press({'object': tid})['ok'])
395
+ slot = e.by_sim[backend.key_to_sim['battery_slot']]
396
+ used = e.a_use({'item': bid, 'target': slot})
397
+ ck('old a_use commits battery slot', used['ok'] and bid not in e.holding)
398
+ ck('battery inserted through old slot helper', e.items[backend.key_to_sim['battery']].get('gone') and s.mechanism_state['powered'])
399
+ ck('power alone does not open archive', not e.part_locks['central_light_table', 1]['unlocked'])
400
+ for key, times in [('tile_1', 3), ('tile_2', 1), ('tile_3', 2)]:
401
+ for _ in range(times):
402
+ ck('old press ' + key, e.a_press({'object': e.by_sim[backend.key_to_sim[key]]})['ok'])
403
+ s.project()
404
+ ck('three panels release archive lock', s.mechanism_state['puzzle_solved'] and e.part_locks['central_light_table', 1]['unlocked'])
405
+ ck('panel solution never autoopens archive', not e.is_open(backend.objects['central_light_table'], 'j_part_1'))
406
+ e.pos = np.array([1.65, 3.75, 1.35])
407
+ case = e.by_sim['camera_storage_case']
408
+ ck('wrong code old a_unlock rejected', not e.a_unlock({'target': case, 'part': 1, 'code': '0000'})['ok'])
409
+ ck('right code old a_unlock accepted', e.a_unlock({'target': case, 'part': 1, 'code': level.CODE})['ok'])
410
+ s.project()
411
+ ck('code projects case flag without autoopen', driver.game.case_unlocked and (not driver.game.opened['camera_case']))
412
+ ck('old case open uses native joint', e.a_open({'object': case, 'part': 1})['ok'])
413
+ s.project()
414
+ kid = e.by_sim[backend.key_to_sim['key']]
415
+ ck('old take actual case key', e.a_take({'item': kid})['ok'] and kid in e.holding)
416
+ s.project()
417
+ e.pos = np.array([0.85, 1.2, 1.35])
418
+ door = e.by_sim[backend.exit_name]
419
+ ck('old use key unlocks room door', e.a_use({'item': kid, 'target': door})['ok'])
420
+ s.project()
421
+ ck('door not autoopened by key', not driver.game.opened['exit'])
422
+ ck('old door open completes R02', e.a_open({'object': door})['ok'])
423
+ s.project()
424
+ ck('legacy joint and victory projection match', driver.game.opened['exit'] and driver.game.exited)
425
+ ck('ordinary Native Game calls never used', not ordinary_calls)
426
+ return dict(room='R02', passed=len(checks), checks=checks, open_call_trace=trace, scope='synthetic transport CPU, actual old E/C references; not native visual acceptance', ordinary_Game_action_fallbacks=ordinary_calls, model_calls=0, SDK_or_GPU_started=False)
427
+ finally:
428
+ for name, old in prior.items():
429
+ if old is None:
430
+ sys.modules.pop(name, None)
431
+ else:
432
+ sys.modules[name] = old
433
+ if __name__ == '__main__':
434
+ print(json.dumps(cpu_test() if '--cpu' in sys.argv else static_check(), ensure_ascii=False))
runtime/native_runtime/legacy_rooms_bridge.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import ast, math, re, json, hashlib, types, copy, sys
3
+ import numpy as np
4
+ from scipy.spatial.transform import Rotation
5
+ from legacy_r01_pilot import ObjectView, NativeBackend, PilotSession, load_stack
6
+ ROOT = Path(__file__).resolve().parent
7
+ BASE = ROOT.parent
8
+
9
+ class UnsupportedBinding(RuntimeError):
10
+ pass
11
+ AUTHORED_CAPABILITIES = {'R07': {'source_sha256': '3ed2133b8ba82738d58ed80172e23e65f028ab29517d256970de25d119996c7b', 'part_use_aliases': ['s3_cover']}, 'R12': {'source_sha256': 'cf5ee49adab4073489ff7a52b2a6a0600d0f594d64a19c48a8f63ea00894a854', 'use_targets': ['s2_lock']}, 'R14': {'source_sha256': 'd87ae2aaf89f179159901234cd66b331657f653982b0afa1d68b83e3af000392', 'part_use_aliases': ['s3_cover'], 'press_targets': ['s2_move_0_down', 's2_move_0_up', 's2_move_1_left', 's2_move_1_right', 's2_move_2_down', 's2_move_2_up']}, 'R19': {'source_sha256': '499e51e3b4dec685517dccf16c06b44f180afb0d2dcff8534d88acca7e6ce05b', 'item_categories': {'s3_tool_0': 'tracing sheet', 's3_tool_1': 'tracing sheet'}}, 'R21': {'source_sha256': '54106c2bda66f7943ffb7b6958f266385f8a033b68403db8c2fbbb1f5d7ea7d8', 'part_use_aliases': ['s2_cover']}}
12
+
13
+ def read(p):
14
+ return json.loads(Path(p).read_text('utf-8-sig'))
15
+
16
+ def get(state, path):
17
+ value = state
18
+ for token in path.split('.'):
19
+ if isinstance(value, dict):
20
+ value = value.get(token, value.get(int(token)) if token.isdigit() else None)
21
+ elif isinstance(value, (list, tuple)) and token.isdigit():
22
+ value = value[int(token)]
23
+ else:
24
+ return None
25
+ return value
26
+
27
+ def put(state, path, value):
28
+ tokens = path.split('.')
29
+ obj = state
30
+ for token in tokens[:-1]:
31
+ if isinstance(obj, dict):
32
+ obj = obj.setdefault(token, {})
33
+ else:
34
+ obj = obj[int(token)]
35
+ if isinstance(obj, dict):
36
+ obj[tokens[-1]] = value
37
+ else:
38
+ obj[int(tokens[-1])] = value
39
+
40
+ def path_object(scene, path):
41
+ expr = ast.parse(path, mode='eval').body
42
+
43
+ def visit(node):
44
+ if isinstance(node, ast.Name):
45
+ return getattr(scene, node.id)
46
+ if isinstance(node, ast.Attribute):
47
+ return getattr(visit(node.value), node.attr)
48
+ if isinstance(node, ast.Subscript):
49
+ return visit(node.value)[visit(node.slice)]
50
+ if isinstance(node, ast.Constant):
51
+ return node.value
52
+ raise UnsupportedBinding('Unsafe node access: ' + path)
53
+ return visit(expr)
54
+
55
+ def rule_matches(rule, state, predicates=None):
56
+ if 'all' in rule:
57
+ return all((rule_matches(x, state, predicates) for x in rule['all']))
58
+ if 'any' in rule:
59
+ return any((rule_matches(x, state, predicates) for x in rule['any']))
60
+ if 'predicate' in rule:
61
+ fn = (predicates or {}).get(rule['predicate'])
62
+ if fn is None:
63
+ raise UnsupportedBinding('Predicate not installed: ' + rule['predicate'])
64
+ args = [get(state, x['path']) if isinstance(x, dict) and 'path' in x else x for x in rule.get('args', [])]
65
+ return bool(fn(*args))
66
+ if 'path' not in rule:
67
+ raise UnsupportedBinding('Unknown rule: ' + str(rule))
68
+ value = get(state, rule['path'])
69
+ target = rule.get('value', True)
70
+ op = rule.get('op', 'eq')
71
+ if op == 'eq':
72
+ return value == target
73
+ if op == 'contains':
74
+ return target in (value or [])
75
+ if op == 'not_contains':
76
+ return target not in (value or [])
77
+ if op == 'gte':
78
+ return value is not None and value >= target
79
+ raise UnsupportedBinding('Unsupported rule operation: ' + op)
80
+
81
+ class LinkedLockItem(dict):
82
+ SHARED = {'unlocked', 'lockd', 'power', 'multi', 'derived', 'concat', 'clue_items'}
83
+
84
+ def __init__(self, base, record):
85
+ super().__init__(base)
86
+ self.record = record
87
+
88
+ def __getitem__(self, key):
89
+ return self.record[key] if key in self.SHARED else super().__getitem__(key)
90
+
91
+ def __setitem__(self, key, value):
92
+ if key in self.SHARED:
93
+ self.record[key] = value
94
+ else:
95
+ super().__setitem__(key, value)
96
+
97
+ def get(self, key, default=None):
98
+ return self.record.get(key, default) if key in self.SHARED else super().get(key, default)
99
+
100
+ def update(self, *a, **k):
101
+ for key, value in dict(*a, **k).items():
102
+ self[key] = value
103
+
104
+ class MotionJoint:
105
+
106
+ def __init__(self, backend, node, binding):
107
+ self.backend = backend
108
+ self.node = node
109
+ self.binding = binding
110
+ m = binding['motion']
111
+ self.kind = m['kind']
112
+ self.joint_type = 'PrismaticJoint' if self.kind == 'translate' else 'RevoluteJoint'
113
+ self.closed = np.array(m['closed'], float)
114
+ self.delta = np.array(m['delta'], float)
115
+ self.length = float(np.linalg.norm(self.delta))
116
+ assert self.length > 1e-09
117
+ self.axis = self.delta / self.length
118
+ self.travel = self.length if self.kind == 'translate' else math.radians(self.length)
119
+ self.coordinate_scale = self.travel / float(m['legacy_coordinate_open']) if self.kind != 'translate' and 'legacy_coordinate_open' in m else 1.0
120
+ self.lower_limit = 0.0
121
+ self.upper_limit = self.travel / 0.9 if self.kind == 'translate' else self.travel / self.coordinate_scale
122
+ self.max_velocity = 0.0
123
+
124
+ def get_state(self):
125
+ op = self.node['translate'] if self.kind == 'translate' else self.node['rotate']
126
+ v = np.array(op.Get(), float) - self.closed
127
+ q = float(np.dot(v, self.axis))
128
+ return (np.array([q if self.kind == 'translate' else math.radians(q) / self.coordinate_scale]), np.array([0.0]), None)
129
+
130
+ def set_pos(self, q, drive=False):
131
+ amount = float(q) if self.kind == 'translate' else math.degrees(float(q) * self.coordinate_scale)
132
+ v = self.closed + self.axis * amount
133
+ self.backend.scene.transform(self.node, **{'pos': v.tolist()} if self.kind == 'translate' else {'rpy': v.tolist()})
134
+
135
+ def install_mechanism_hooks(E):
136
+ if getattr(E, '_native_rooms_hook_v1', False):
137
+ return
138
+ old_observe = E.Escape.observe
139
+
140
+ def observe(esc, *args, **kwargs):
141
+ result = old_observe(esc, *args, **kwargs)
142
+ hook = getattr(esc, '_native_photo_metadata_hook', None)
143
+ if hook is not None:
144
+ hook(result[0])
145
+ return result
146
+ E.Escape.observe = observe
147
+ old_press = E.Escape.a_press
148
+ old_use = E.Escape._gadget_use_without_visual
149
+ old_reach = E.Escape.reach_item
150
+ old_taken = E.Escape._on_taken
151
+ old_layer = E.Escape._layer
152
+ old_item = E.Escape._item
153
+ old_lock_target = E.Escape._lock_target
154
+ old_press_visual = E.Escape._press_switch_button
155
+
156
+ def press(esc, a):
157
+ obj = esc.objs.get(a.get('object'), {})
158
+ name = obj.get('sim')
159
+ category = obj.get('cat')
160
+ capability = name in getattr(esc, '_native_press_capabilities', set())
161
+ if capability:
162
+ obj['cat'] = 'electric switch'
163
+ try:
164
+ result = old_press(esc, a)
165
+ finally:
166
+ if capability:
167
+ obj['cat'] = category
168
+ hook = getattr(esc, '_native_mechanism_hook', None)
169
+ if hook is None or not result.get('ok'):
170
+ return result
171
+ if name not in getattr(esc, '_native_mechanism_targets', set()):
172
+ return result
173
+ return hook('press', name, None, a)
174
+
175
+ def gadget_use(esc, g, st, o, tgt):
176
+ result = old_use(esc, g, st, o, tgt)
177
+ hook = getattr(esc, '_native_mechanism_hook', None)
178
+ if hook is None or g.get('type') != 'native_mechanism' or (not result.get('ok')):
179
+ return result
180
+ return hook('use', g['name'], st['name'], {'item': o['id'], 'target': tgt['id']})
181
+
182
+ def reach(esc, st):
183
+ result = old_reach(esc, st)
184
+ gate = getattr(esc, '_native_take_gate', None)
185
+ if not result[0] or gate is None or getattr(esc, '_native_public_kind', None) != 'take':
186
+ return result
187
+ return result if gate(st['name']) else (False, 'This object cannot be taken.')
188
+
189
+ def taken(esc, st):
190
+ result = old_taken(esc, st)
191
+ hook = getattr(esc, '_native_taken_hook', None)
192
+ if hook is not None:
193
+ hook(st['name'])
194
+ return result
195
+
196
+ def layer(esc, a, verb):
197
+ got, error = old_layer(esc, a, verb)
198
+ gate = getattr(esc, '_native_part_gate', None)
199
+ if error is not None or gate is None:
200
+ return (got, error)
201
+ o, so, joint, part = got
202
+ if not gate(so.name, part, verb):
203
+ kind = getattr(esc, '_native_part_gate_failure', None)
204
+ text = kind(so.name, part, verb) if kind is not None else None
205
+ return (None, {'ok': False, 'text': text or 'This object cannot be ' + verb + 'ed.', 'images': []})
206
+ return (got, error)
207
+
208
+ def item(esc, oid, verb):
209
+ obj, st, error = old_item(esc, oid, verb)
210
+ reader = getattr(esc, '_native_read_text', None)
211
+ alias = getattr(esc, '_native_item_alias', None)
212
+ if error is None and st is not None and (verb == 'take') and (alias is not None):
213
+ obj, st, error = alias(obj, st, verb)
214
+ if error is None and st is not None and (verb == 'read') and (reader is not None):
215
+ from read_content_policy import visual_only
216
+ if not visual_only(esc, st):
217
+ st['text'] = reader(st['name'])
218
+ return (obj, st, error)
219
+
220
+ def lock_target(esc, a):
221
+ rec, name, error = old_lock_target(esc, a)
222
+ gate = getattr(esc, '_native_unlock_gate', None)
223
+ part_use = getattr(esc, '_native_part_use_hook', None)
224
+ if error is None and getattr(esc, '_native_public_kind', None) == 'use' and (part_use is not None):
225
+ intercept_result = part_use(a, rec)
226
+ if intercept_result is not None:
227
+ return (None, None, intercept_result)
228
+ if error is None and gate is not None and (a.get('item') is None) and (not gate(a)):
229
+ return (None, None, {'ok': False, 'text': 'This object cannot be unlocked.', 'images': []})
230
+ return (rec, name, error)
231
+
232
+ def press_visual(esc, so):
233
+ if so.name in getattr(esc, '_native_mechanism_targets', set()):
234
+ return None
235
+ return old_press_visual(esc, so)
236
+ E.Escape.a_press = press
237
+ E.Escape._gadget_use_without_visual = gadget_use
238
+ E.Escape.reach_item = reach
239
+ E.Escape._on_taken = taken
240
+ E.Escape._layer = layer
241
+ E.Escape._item = item
242
+ E.Escape._lock_target = lock_target
243
+ E.Escape._press_switch_button = press_visual
244
+ C = sys.modules.get('_escape_claw')
245
+ if C is not None and (not getattr(C, '_native_press_capability_v1', False)):
246
+ old_kind = C._kind_ok
247
+
248
+ def kind_ok(esc, obj, kind):
249
+ if obj.get('sim') in getattr(esc, '_native_read_only_data_targets', set()) and kind != 'read':
250
+ return False
251
+ if kind == 'press' and obj.get('sim') in getattr(esc, '_native_press_capabilities', set()):
252
+ return True
253
+ return old_kind(esc, obj, kind)
254
+ C._kind_ok = kind_ok
255
+ C._native_press_capability_v1 = True
256
+ if C is not None and (not getattr(C, '_native_front_mesh_guard_v1', False)):
257
+ old_front = C._front_thing
258
+
259
+ def front(esc, photo, px, py, oid):
260
+ result = old_front(esc, photo, px, py, oid)
261
+ candidate = oid if result is None else result[1] if result[0] == 'named' else None
262
+ guard = getattr(esc, '_native_front_mesh_guard', None)
263
+ if candidate is not None and guard is not None and (not guard(esc, C, photo, px, py, candidate)):
264
+ return ('nothing', None, None)
265
+ return result
266
+ C._front_thing = front
267
+ C._native_front_mesh_guard_v1 = True
268
+ E._native_rooms_hook_v1 = True
269
+ E._native_rooms_originals = {'a_press': old_press, 'gadget_use': old_use, 'reach_item': old_reach, 'on_taken': old_taken, 'layer': old_layer, 'item': old_item, 'lock_target': old_lock_target}
270
+
271
+ class RoomsBackend(NativeBackend):
272
+
273
+ def __init__(self, driver, level, owner_level, motion_level, predicates=None):
274
+ self.driver = driver
275
+ self.scene = driver.scene
276
+ self.game = driver.game
277
+ self.level = level
278
+ self.objects = {}
279
+ self.escape = None
280
+ self.query_count = 0
281
+ self.predicates = predicates or {}
282
+ self.session = None
283
+ self.key_to_sim = {}
284
+ self.sim_to_key = {}
285
+ self.part_bindings = {}
286
+ self.part_aliases = {}
287
+ self.item_metadata = {}
288
+ self.owner_map = owner_level
289
+ self.motion_map = motion_level
290
+ self.authored_capabilities = copy.deepcopy(AUTHORED_CAPABILITIES.get(level, {}))
291
+ if self.authored_capabilities:
292
+ actual = hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest()
293
+ if actual != self.authored_capabilities['source_sha256']:
294
+ raise UnsupportedBinding('Authored capability source SHA changed: ' + level)
295
+ grouped = {}
296
+ for b in motion_level['bindings']:
297
+ typed_sha = b.get('post_open_effect_source_sha256') or b.get('gate_failure_source_sha256')
298
+ if typed_sha is not None:
299
+ actual = hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest()
300
+ if typed_sha != actual:
301
+ raise UnsupportedBinding('Typed gate feedback source SHA changed: ' + level)
302
+ grouped.setdefault(b['owner_id'], []).append(b)
303
+ for owner in owner_level['owners']:
304
+ oid = owner['owner_id']
305
+ rows = grouped.get(oid, [])
306
+ if not rows:
307
+ raise UnsupportedBinding('Owner has no motions: ' + oid)
308
+ nodes = []
309
+ for name in owner.get('geometry_components', []):
310
+ node = getattr(self.scene, 'groups', {}).get(name) or getattr(self.scene, 'target_nodes', {}).get(name)
311
+ if node is not None and node not in nodes:
312
+ nodes.append(node)
313
+ for binding in rows:
314
+ node = path_object(self.scene, binding['node_access'])
315
+ if not any((node is existing for existing in nodes)):
316
+ nodes.append(node)
317
+ o = ObjectView(oid, 'cabinet', self, node=nodes[0])
318
+ o.nodes = nodes
319
+ self.objects[oid] = o
320
+ for b in sorted(rows, key=lambda x: x['part']):
321
+ node = path_object(self.scene, b['node_access'])
322
+ joint = 'j_part_' + str(b['part'])
323
+ link = ObjectView(oid + '_part_' + str(b['part']), 'part', self, node=node)
324
+ o.links[joint[2:]] = link
325
+ o.joints[joint] = MotionJoint(self, node, b)
326
+ self.part_bindings[oid, b['part']] = b
327
+ for key in [b['open_key'], b.get('close_key'), next((p.get('unlock_key') for p in owner['parts'] if p['part'] == b['part']), None)] + next((p.get('aliases', []) for p in owner['parts'] if p['part'] == b['part']), []):
328
+ if key:
329
+ self.part_aliases[key] = (oid, b['part'])
330
+ doors = motion_level.get('door_bindings', [])
331
+ if len(doors) != 1:
332
+ raise UnsupportedBinding('Exactly one room exit binding is required')
333
+ b = doors[0]
334
+ node = path_object(self.scene, b['node_access'])
335
+ name = b['owner_id']
336
+ o = ObjectView(name, 'door', self, node=node)
337
+ o.links['panel'] = ObjectView(name + '_panel', 'door', self, node=node)
338
+ o.joints['j_panel'] = MotionJoint(self, node, b)
339
+ self.objects[name] = o
340
+ self.door_binding = b
341
+ self.exit_name = name
342
+ self.key_to_sim[b['open_key']] = name
343
+ self.sim_to_key[name] = b['open_key']
344
+ contents = motion_level.get('contents', [])
345
+ for row in contents:
346
+ key = row['target_key']
347
+ node = self.scene.target_nodes.get(key)
348
+ if node is None:
349
+ raise UnsupportedBinding('Content has no actual Scene target: ' + key)
350
+ category = self.authored_capabilities.get('item_categories', {}).get(key, self.game.LABELS.get(key, key))
351
+ name = 'native_item_' + key
352
+ o = ObjectView(name, str(category), self, node=node)
353
+ self.objects[name] = o
354
+ self.key_to_sim[key] = name
355
+ self.sim_to_key[name] = key
356
+ self.item_metadata[name] = row
357
+ self.lock_endpoints = {}
358
+ for owner in owner_level['owners']:
359
+ for part in owner['parts']:
360
+ alias = part.get('unlock_key')
361
+ node = self.scene.target_nodes.get(alias)
362
+ if not alias or node is None:
363
+ continue
364
+ probe = ObjectView('_terminal_probe', 'code lock', self, node=node)
365
+ lo, hi = self.bounds(probe)
366
+ ol, oh = self.objects[owner['owner_id']].aabb
367
+ if np.all(lo >= ol - 0.04) and np.all(hi <= oh + 0.04):
368
+ continue
369
+ physical = []
370
+ centre = (lo + hi) / 2
371
+ for name in self.owner_map_ids:
372
+ a, z = self.objects[name].aabb
373
+ if np.all(centre >= a - 0.03) and np.all(centre <= z + 0.03):
374
+ physical.append((float(np.prod(np.maximum(z - a, 0.001))), name))
375
+ container = min(physical)[1] if physical else None
376
+ name = 'native_lock_terminal_' + alias
377
+ self.objects[name] = ObjectView(name, 'code lock', self, node=node)
378
+ self.key_to_sim[alias] = name
379
+ self.sim_to_key[name] = alias
380
+ self.item_metadata[name] = {'item_key': alias, 'target_key': alias, 'owner_id': container, 'part': None, 'kind': 'surface', 'fixed': True, 'take_gate': [], 'container_is_initial_source_not_permanent': False}
381
+ self.lock_endpoints[name] = {'owner_id': owner['owner_id'], 'part': part['part'], 'unlock_key': alias}
382
+ for key, node in self.scene.target_nodes.items():
383
+ if key in self.part_aliases or key in self.key_to_sim:
384
+ continue
385
+ name = 'native_mechanism_' + key
386
+ category = 'electric switch' if 'choice_' in key or 'control_' in key or 'tile_' in key or key.endswith(('_confirm', '_reset', '_play')) or (key in ['s2_setup']) else 'mechanism'
387
+ self.objects[name] = ObjectView(name, category, self, node=node)
388
+ self.key_to_sim[key] = name
389
+ self.sim_to_key[name] = key
390
+ self.gadget_sims = {}
391
+ for key, name in self.key_to_sim.items():
392
+ if key == self.door_binding['open_key']:
393
+ continue
394
+ if re.search('_(choice|control|slot|overlay|tile)_', key) or key.endswith(('_setup', '_tap', '_confirm', '_reset', '_play', '_feed')):
395
+ self.gadget_sims[name] = key
396
+ if re.search('_(choice|control|tile)_', key) or key.endswith(('_confirm', '_reset', '_play')) or (key.endswith('_setup') and (self.game.SPEC['stages'][int(key[1]) - 1].get('setup') or {}).get('item') is None):
397
+ self.objects[name].category = 'electric switch'
398
+ for key, (owner, part) in self.part_aliases.items():
399
+ if key.endswith(('_confirm', '_reset', '_play')):
400
+ if len(self.objects[owner].joints) != 1:
401
+ raise UnsupportedBinding('Press alias spans multiple parts: ' + key)
402
+ self.gadget_sims[owner] = key
403
+ self.objects[owner].category = 'electric switch'
404
+ m = re.fullmatch('s([123])_setup', key)
405
+ if m and (self.game.SPEC['stages'][int(m[1]) - 1].get('setup') or {}).get('kind') != 'key':
406
+ if len(self.objects[owner].joints) != 1:
407
+ raise UnsupportedBinding('Mechanism part alias is ambiguous: ' + key)
408
+ self.gadget_sims[owner] = key
409
+ declared_press = self.authored_capabilities.get('press_targets', [])
410
+ for key in dict.fromkeys(self.authored_capabilities.get('use_targets', []) + declared_press):
411
+ name = self.key_to_sim.get(key)
412
+ if name is None:
413
+ raise UnsupportedBinding('Authored action target has no real registered mesh: ' + key)
414
+ self.gadget_sims[name] = key
415
+ if key in declared_press:
416
+ self.objects[name].category = 'electric switch'
417
+ self._door_boxes = {name: tuple(o.aabb) for name, o in self.objects.items() if o.category == 'door'}
418
+
419
+ def bounds(self, o):
420
+ arrays = [self.scene.triangles(n).reshape(-1, 3) for n in getattr(o, 'nodes', [o.node])]
421
+ arrays = [v for v in arrays if v.size]
422
+ if not arrays:
423
+ raise UnsupportedBinding('Object has no actual mesh: ' + o.name)
424
+ points = np.concatenate(arrays)
425
+ return np.array([points.min(0), points.max(0)])
426
+
427
+ def visible(self, o):
428
+ if self.escape is not None and o.name in getattr(self.escape, '_hidden', []):
429
+ return False
430
+ if o.name in self.owner_map_ids:
431
+ return True
432
+ key = self.sim_to_key.get(o.name)
433
+ if key is None:
434
+ return True
435
+ return bool(self.scene.visible(key, self.game)) if hasattr(self.scene, 'visible') else key in self.scene.target_nodes
436
+
437
+ def refresh_gadget_semantics(self):
438
+ current = {}
439
+ for key, node in self.scene.target_nodes.items():
440
+ current.setdefault(str(node['prim'].GetPath()), []).append(key)
441
+ updates = {}
442
+ for name, old_key in self.gadget_sims.items():
443
+ if name in self.owner_map_ids:
444
+ continue
445
+ node = self.objects[name].node
446
+ keys = current.get(str(node['prim'].GetPath()), [])
447
+ if old_key in keys:
448
+ updates[name] = old_key
449
+ elif len(keys) == 1:
450
+ updates[name] = keys[0]
451
+ elif len(keys) > 1:
452
+ raise UnsupportedBinding('Ambiguous authored target aliases for ' + name)
453
+ changed = {name: key for name, key in updates.items() if self.gadget_sims[name] != key}
454
+ if not changed:
455
+ return False
456
+ mapping = {key: name for key, name in self.key_to_sim.items() if name not in updates}
457
+ for name, key in updates.items():
458
+ if key in mapping and mapping[key] != name:
459
+ raise UnsupportedBinding('Authored target registration collision: ' + key)
460
+ mapping[key] = name
461
+ self.key_to_sim = mapping
462
+ for name, key in updates.items():
463
+ self.gadget_sims[name] = key
464
+ self.sim_to_key[name] = key
465
+ return True
466
+
467
+ @property
468
+ def owner_map_ids(self):
469
+ return {x['owner_id'] for x in self.owner_map['owners']}
470
+
471
+ def step(self, n=1):
472
+ for _ in range(max(1, int(n))):
473
+ self.driver.og.sim.step()
474
+
475
+ def reconcile(self):
476
+ if self.session is not None:
477
+ self.session.project()
478
+
479
+ def install_colliders(self):
480
+ from pxr import Usd, UsdGeom, UsdPhysics
481
+ sim = self.driver.og.sim
482
+ if getattr(sim, 'psqi', None) is None:
483
+ raise UnsupportedBinding('Live PhysX service missing; no fallback')
484
+ count = 0
485
+ with sim.editing_usd():
486
+ for prim in Usd.PrimRange(sim.stage.GetPrimAtPath('/World/redesign364')):
487
+ if prim.IsA(UsdGeom.Mesh):
488
+ UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(True)
489
+ UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr('convexHull')
490
+ count += 1
491
+ for (owner, part), b in self.part_bindings.items():
492
+ node = path_object(self.scene, b['node_access'])
493
+ api = UsdPhysics.RigidBodyAPI.Apply(node['prim'])
494
+ api.CreateKinematicEnabledAttr(True)
495
+ api.CreateRigidBodyEnabledAttr(True)
496
+ node = path_object(self.scene, self.door_binding['node_access'])
497
+ api = UsdPhysics.RigidBodyAPI.Apply(node['prim'])
498
+ api.CreateKinematicEnabledAttr(True)
499
+ api.CreateRigidBodyEnabledAttr(True)
500
+ sim.play()
501
+ sim.update_handles()
502
+ self.step(30)
503
+ return count
504
+
505
+ class RoomsSession:
506
+
507
+ def __init__(self, backend, out, E, C):
508
+ self.backend = backend
509
+ backend.session = self
510
+ self.driver = backend.driver
511
+ self.game = backend.game
512
+ self.E = E
513
+ self.C = C
514
+ self.extra_images = []
515
+ self.placements = {}
516
+ self.lock_effects = {}
517
+ self.last_call_trace = []
518
+ install_mechanism_hooks(E)
519
+ out = Path(out)
520
+ out.mkdir(parents=True, exist_ok=True)
521
+ cfg = {'name': 'native_bridge_' + backend.level, 'scene': 'programmatic_' + backend.level, 'start': {'xy': list(self.driver.pos[:2]), 'yaw_deg': math.degrees(self.driver.yaw)}, 'max_steps': 150, 'native_devices_visual': False, 'native_use_visual': False, 'items': [], 'part_locks': [], 'doors': [{'name': backend.exit_name, 'key': 'key', 'exit': True}], 'gadgets': []}
522
+ stages = getattr(self.game, 'SPEC', {}).get('stages', [])
523
+ for (owner, part), b in backend.part_bindings.items():
524
+ original = next((p for o in backend.owner_map['owners'] if o['owner_id'] == owner for p in o['parts'] if p['part'] == part))
525
+ key = original.get('unlock_key')
526
+ entry = {'container': owner, 'part': part}
527
+ effects = []
528
+ if key:
529
+ index = int(key[1]) - 1
530
+ stage = stages[index]
531
+ if stage.get('answer') is None:
532
+ raise UnsupportedBinding('Code lock has no declared answer: ' + key)
533
+ entry['lock'] = str(stage['answer'])
534
+ effects = ['solved.' + str(index)]
535
+ match = re.fullmatch('s([123])_setup', b['open_key'])
536
+ if match:
537
+ i = int(match[1]) - 1
538
+ setup = stages[i].get('setup') or {}
539
+ if setup.get('kind') == 'key':
540
+ entry['key'] = 's' + str(i + 1) + '_tool'
541
+ effects = ['states.' + str(i) + '.setup_unlocked', 'states.' + str(i) + '.setup_used']
542
+ if backend.level == 'R13' and b['open_key'] == 's3_cover':
543
+ entry['key'] = 's3_tool'
544
+ effects = ['states.2.cover_key_used']
545
+ if backend.level == 'R04' and b['open_key'] == 's3_cover':
546
+ entry['key'] = 's2_float_key'
547
+ effects = ['solved.1']
548
+ cfg['part_locks'].append(entry)
549
+ self.lock_effects[owner, part] = effects
550
+ for name, row in backend.item_metadata.items():
551
+ cfg['items'].append({'id': row['item_key'], 'name': name, 'kind': 'tool', 'text': ''})
552
+ for name in backend.gadget_sims:
553
+ cfg['gadgets'].append({'name': name, 'type': 'native_mechanism'})
554
+ from legacy_r01_pilot import quat_from
555
+ ctx = {'env': types.SimpleNamespace(scene=types.SimpleNamespace(objects=list(backend.objects.values()), object_registry=lambda k, n: backend.objects.get(n))), 'E': types.SimpleNamespace(quat_from=quat_from), 'pos': list(self.driver.pos), 'shot': backend.capture, 'detect': backend.detect, 'step_sim': backend.step, 'fov_h': lambda: math.pi / 2}
556
+ self.esc = E.Escape(ctx, cfg, out)
557
+ backend.escape = self.esc
558
+ e = self.esc
559
+ e._native_photo_metadata_hook = backend.photo_metadata
560
+ e._native_front_mesh_guard = backend.front_mesh_guard
561
+ e._native_part_use_hook = self.part_use
562
+ e._native_part_gate_failure = self.part_gate_failure
563
+ e._native_mechanism_hook = self.mechanism
564
+ e._native_mechanism_targets = {g['name'] for g in cfg['gadgets']}
565
+ e._native_take_gate = self.take_gate
566
+ e._native_taken_hook = self.on_taken
567
+ e._native_part_gate = self.part_gate
568
+ e._native_read_text = self.read_text
569
+ e._native_read_kind = self.read_kind
570
+ e._native_unlock_gate = self.unlock_gate
571
+ for i, o in enumerate(backend.objects.values(), 1):
572
+ e.objs[i] = {'id': i, 'sim': o.name, 'cat': o.category, 'center': o.aabb.mean(0).tolist()}
573
+ e.by_sim[o.name] = i
574
+ self.key_to_oid = {k: e.by_sim[v] for k, v in backend.key_to_sim.items()}
575
+ self.oid_to_key = {v: k for k, v in self.key_to_oid.items()}
576
+ for key, (owner, part) in backend.part_aliases.items():
577
+ if backend.key_to_sim.get(key) not in backend.lock_endpoints:
578
+ self.key_to_oid[key] = e.by_sim[owner]
579
+ for owner, o in backend.objects.items():
580
+ if o.joints:
581
+ e._parts[owner] = [(j, 'drawer' if 'Prismatic' in str(v.joint_type) else 'door') for j, v in o.joints.items()]
582
+ e._closed_box[owner] = tuple(o.aabb.copy())
583
+ for name, row in backend.item_metadata.items():
584
+ parent = row.get('owner_id') or name
585
+ part = row.get('part') or 0
586
+ jn = 'j_part_' + str(part) if part else None
587
+ kind = row.get('kind', 'loose')
588
+ st = {'id': row['item_key'], 'name': name, 'container': parent, 'part': part, 'joint': jn, 'kind': kind, 'fixed': bool(row.get('fixed')), 'text': self.clue_text(row['item_key']), 'lockd': None, 'unlocked': True, 'taken': False}
589
+ if parent not in backend.objects:
590
+ raise UnsupportedBinding('Unknown content owner ' + str(parent))
591
+ if jn:
592
+ st['rel'] = e._rel(backend.objects[parent].links[jn[2:]], backend.objects[name])
593
+ if name in backend.lock_endpoints:
594
+ endpoint = backend.lock_endpoints[name]
595
+ st = LinkedLockItem(st, e.part_locks[endpoint['owner_id'], endpoint['part']])
596
+ e.items[name] = st
597
+ e._wallmap = np.zeros((640, 640), bool)
598
+ size = getattr(self.game, 'SPEC', {}).get('size', [6.0, 6.0])
599
+ res = e.GUARD_RES
600
+ e._wallmap[320:320 + int(size[1] / res), 320:320 + int(size[0] / res)] = True
601
+ e._door_boxes = backend._door_boxes
602
+ e._window_boxes = {}
603
+ e._semmap = np.ones((3200, 3200), np.uint8)
604
+ e._roomcats = ['native_room']
605
+ for owner in backend.owner_map_ids:
606
+ e._fronts[owner] = np.array([0.0, -1.0])
607
+ self.generic_identity = {name: getattr(E.Escape, name) for name in ['act', 'a_open', 'a_close', 'a_take', 'a_unlock', 'a_use']}
608
+ self.project()
609
+
610
+ def clue_text(self, key):
611
+ match = re.fullmatch('s([123])_clue', key)
612
+ return str(self.game.SPEC['stages'][int(match[1]) - 1].get('clue_text', '')) if match else ''
613
+
614
+ def take_gate(self, name):
615
+ row = self.backend.item_metadata[name]
616
+ st = self.esc.items[name]
617
+ if st.get('slot') and row.get('container_is_initial_source_not_permanent'):
618
+ return True
619
+ state = self.game.snapshot()
620
+ return all((rule_matches(x, state, self.backend.predicates) for x in row.get('take_gate', [])))
621
+
622
+ def part_gate(self, owner, part, verb):
623
+ binding = self.backend.part_bindings.get((owner, part))
624
+ if binding is None:
625
+ raise UnsupportedBinding('Missing part capability binding')
626
+ req = binding['opening_requirements' if verb == 'open' else 'closing_requirements']
627
+ if req.get('status') != 'executable_structured':
628
+ raise UnsupportedBinding('Part capability rule not validated')
629
+ return rule_matches(req['rule'], self.game.snapshot(), self.backend.predicates)
630
+
631
+ def part_gate_failure(self, owner, part, verb):
632
+ if verb != 'open':
633
+ return None
634
+ binding = self.backend.part_bindings.get((owner, part), {})
635
+ if getattr(self.backend, 'level', '') in getattr(self, '_authored_h2_lock_feedback', {}):
636
+ row = self._authored_h2_lock_feedback[self.backend.level]
637
+ rule = row['rules'].get(binding.get('open_key'))
638
+ if rule is None:
639
+ return None
640
+ return None if rule_matches(rule, self.game.snapshot(), self.backend.predicates) else 'This object is locked.'
641
+ if binding.get('gate_failure_kind') != 'locked' or not binding.get('locked_if_release_rule_false'):
642
+ return None
643
+ if rule_matches(binding['lock_release_rule'], self.game.snapshot(), self.backend.predicates):
644
+ return None
645
+ return 'This object is locked.'
646
+
647
+ def unlock_gate(self, a):
648
+ obj = self.esc.objs.get(a.get('target'), {})
649
+ owner = obj.get('sim')
650
+ part = a.get('part')
651
+ if owner in self.backend.lock_endpoints:
652
+ endpoint = self.backend.lock_endpoints[owner]
653
+ owner = endpoint['owner_id']
654
+ part = endpoint['part']
655
+ alias = next((p.get('unlock_key') for o in self.backend.owner_map['owners'] if o['owner_id'] == owner for p in o['parts'] if p['part'] == part), None)
656
+ if alias and re.fullmatch('s[123]_lock', alias):
657
+ return bool(self.game.states[int(alias[1]) - 1].get('setup_ready', True))
658
+ return True
659
+
660
+ def read_kind(self, name):
661
+ from read_content_policy import node_kind
662
+ obj = self.backend.objects.get(name)
663
+ return node_kind(self.backend.scene, obj.node, include_hidden=bool(self.esc.items.get(name, {}).get('taken'))) if obj is not None else None
664
+
665
+ def read_text(self, name):
666
+ key = self.backend.sim_to_key[name]
667
+ result = self.game.act({'action': 'read', '_hit364': key, '_validated364': True})
668
+ return str(result.get('text', '')) if result.get('ok') else ''
669
+
670
+ def on_taken(self, name):
671
+ key = self.backend.sim_to_key.get(name, '')
672
+ match = re.fullmatch('s([123])_item_(\\d+)', key)
673
+ if match:
674
+ assignment = self.game.states[int(match[1]) - 1].get('assignment', {})
675
+ item = int(match[2])
676
+ for slot, v in list(assignment.items()):
677
+ if int(v) == item:
678
+ assignment.pop(slot)
679
+
680
+ def project(self):
681
+ e = self.esc
682
+ g = self.game
683
+ b = self.backend
684
+ for owner, part in b.part_bindings:
685
+ rec = e.part_locks[owner, part]
686
+ if rec['unlocked']:
687
+ for path in self.lock_effects[owner, part]:
688
+ put(g.__dict__, path, True)
689
+ saved = []
690
+ for (owner, part), binding in b.part_bindings.items():
691
+ node = path_object(b.scene, binding['node_access'])
692
+ saved.append((node, list(node['translate'].Get()), list(node['rotate'].Get())))
693
+ opened = bool(e.is_open(b.objects[owner], 'j_part_' + str(part)))
694
+ put(g.__dict__, binding['state_path'], opened)
695
+ if opened:
696
+ for effect in binding.get('post_open_state_effects', []):
697
+ put(g.__dict__, effect['path'], copy.deepcopy(effect['value']))
698
+ setup_match = re.fullmatch('states\\.(\\d+)\\.setup_open', binding['state_path'])
699
+ if setup_match:
700
+ g.states[int(setup_match[1])]['setup_ready'] = opened
701
+ door_node = path_object(b.scene, b.door_binding['node_access'])
702
+ saved.append((door_node, list(door_node['translate'].Get()), list(door_node['rotate'].Get())))
703
+ g.opened['exit'] = b.exit_name in e.passed_doors
704
+ g.exit_unlocked = e.doors[b.exit_name]['unlocked']
705
+ g.exited = bool(e.success)
706
+ g.holding = [b.sim_to_key[e.objs[i]['sim']] for i in e.holding]
707
+ g.taken = {b.sim_to_key[n] for n, st in e.items.items() if st.get('taken') or e.marks.get('took ' + st['id']) is not None}
708
+ state = g.snapshot()
709
+ for (owner, part), binding in b.part_bindings.items():
710
+ rec = e.part_locks[owner, part]
711
+ req = binding['opening_requirements']
712
+ if req.get('status') != 'executable_structured':
713
+ raise UnsupportedBinding('Unvalidated open gate')
714
+ if not rec.get('lockd') and rule_matches(req['rule'], state, b.predicates):
715
+ rec['unlocked'] = True
716
+ b.scene.sync(g)
717
+ if b.refresh_gadget_semantics():
718
+ self.key_to_oid = {key: e.by_sim[name] for key, name in b.key_to_sim.items()}
719
+ self.oid_to_key = {value: key for key, value in self.key_to_oid.items()}
720
+ for key, (owner, part) in b.part_aliases.items():
721
+ if b.key_to_sim.get(key) not in b.lock_endpoints:
722
+ self.key_to_oid[key] = e.by_sim[owner]
723
+ for name, key in b.gadget_sims.items():
724
+ label = getattr(b.scene, 'labels', {}).get(key)
725
+ if label:
726
+ e._display[name] = str(label)
727
+ for node, t, r in saved:
728
+ b.scene.transform(node, t, r)
729
+ if b.native:
730
+ from pxr import Usd, UsdPhysics
731
+ with self.driver.og.sim.editing_usd():
732
+ for name, st in e.items.items():
733
+ obj = b.objects[name]
734
+ enabled = not st.get('taken') and (not st.get('gone'))
735
+ for prim in Usd.PrimRange(obj.node['prim']):
736
+ if prim.HasAPI(UsdPhysics.CollisionAPI):
737
+ UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Set(enabled)
738
+
739
+ def part_use(self, action, record):
740
+ b = self.backend
741
+ owner = record.get('container')
742
+ part = record.get('part')
743
+ aliases = [key for key in getattr(b, 'authored_capabilities', {}).get('part_use_aliases', []) if b.part_aliases.get(key) == (owner, part)]
744
+ if not aliases:
745
+ return None
746
+ if len(aliases) != 1:
747
+ raise UnsupportedBinding('Ambiguous authored part-use capability')
748
+ item = self.esc.objs.get(action.get('item'), {}).get('sim')
749
+ if item is None:
750
+ return None
751
+ return self.mechanism('use', owner, item, action, authored_key=aliases[0])
752
+
753
+ def mechanism(self, kind, name, item_name, a, authored_key=None):
754
+ b = self.backend
755
+ g = self.game
756
+ key = authored_key if authored_key is not None else b.gadget_sims[name]
757
+ self.project()
758
+ before = g.snapshot()
759
+ item = b.sim_to_key.get(item_name)
760
+ internal = {'action': kind, '_hit364': key, '_validated364': True, '_actor_position364': self.esc.pos.tolist()}
761
+ if item is not None:
762
+ internal['item'] = g.LABELS.get(item, item)
763
+ result = g.act(internal)
764
+ result['native_resolved_key_private'] = key
765
+ if not result.get('ok'):
766
+ self.project()
767
+ return result
768
+ after = g.snapshot()
769
+ for (owner, part), binding in b.part_bindings.items():
770
+ old = get(before, binding['state_path'])
771
+ new = get(after, binding['state_path'])
772
+ if old != new:
773
+ req = binding['opening_requirements' if new else 'closing_requirements']
774
+ if not rule_matches(req['rule'], after, b.predicates):
775
+ raise UnsupportedBinding('Mechanism requested a forbidden part movement')
776
+ self.esc.set_joint(b.objects[owner], 'j_part_' + str(part), bool(new))
777
+ removed = set(before['holding']) - set(g.holding)
778
+ for consumed in removed:
779
+ sim = b.key_to_sim.get(consumed)
780
+ if sim is None:
781
+ raise UnsupportedBinding('Unknown inventory effect ' + consumed)
782
+ st = self.esc.items[sim]
783
+ target = self.esc.gadgets.get(name)
784
+ if target is None:
785
+ if authored_key is None:
786
+ raise UnsupportedBinding('Consumed tool has no canonical placement target')
787
+ target = {'name': name, 'type': 'native_mechanism'}
788
+ self.esc._slot_place(target, st)
789
+ setup = {}
790
+ m = re.match('s([123])_', key)
791
+ if m:
792
+ setup = g.SPEC['stages'][int(m[1]) - 1].get('setup') or {}
793
+ if setup.get('consume') or '_overlay_' in key or '_slot_' not in key:
794
+ st['gone'] = True
795
+ if authored_key is not None and name not in self.esc.gadgets:
796
+ if not st.get('gone'):
797
+ raise UnsupportedBinding('Persistent part placement needs a declared native slot')
798
+ st.pop('slot', None)
799
+ self.driver.current_hit = {'key': key, 'source': 'actual_common_legacy_resolution'}
800
+ extra_before = len(getattr(self.driver, 'current_visual_feedback', []))
801
+ self.project()
802
+ if hasattr(b.scene, 'animate'):
803
+ b.scene.animate(self.driver, before)
804
+ self.extra_images.extend(getattr(self.driver, 'current_visual_feedback', [])[extra_before:])
805
+ return result
806
+
807
+ def act(self, action):
808
+ e = self.esc
809
+ e._native_public_kind = action.get('action')
810
+ self.extra_images = []
811
+ e.t = int(getattr(self.driver, '_legacy_action_step', self.driver.step + 1))
812
+ result = e.act(dict(action))
813
+ code_alias = None
814
+ if action.get('action') == 'unlock':
815
+ ids = result.get('action_ids') or result.get('action_ids_private') or {}
816
+ oid = ids.get('target')
817
+ part = ids.get('part')
818
+ if oid in e.objs:
819
+ owner = e.objs[oid]['sim']
820
+ if owner in self.backend.lock_endpoints:
821
+ endpoint = self.backend.lock_endpoints[owner]
822
+ owner = endpoint['owner_id']
823
+ part = endpoint['part']
824
+ binding = self.backend.part_bindings.get((owner, part))
825
+ alias = next((p.get('unlock_key') for o in self.backend.owner_map['owners'] if o['owner_id'] == owner for p in o['parts'] if p['part'] == part), None)
826
+ if alias and re.match('s[123]_lock$', alias):
827
+ self.game.states[int(alias[1]) - 1]['entered_code'] = str(action.get('code', ''))
828
+ code_alias = alias
829
+ self.project()
830
+ self.driver.pos = e.pos.copy()
831
+ self.driver.yaw = float(e.yaw)
832
+ self.driver.pitch = math.radians(getattr(e, '_claw_pitch', 0.0))
833
+ if code_alias is not None or not result.get('images'):
834
+ boxed, _ = self.C.shoot(e, 'native_code_entry' if code_alias else 'native_current_result')
835
+ e._claw_photos = [boxed]
836
+ result['images'] = [self.C._small(e, boxed)]
837
+ if self.extra_images:
838
+ result['images'] = list(dict.fromkeys(self.extra_images + list(result.get('images') or [])))
839
+ result['native_mechanism_sequence_preserved'] = True
840
+ return result
841
+
842
+ def native_gate(self):
843
+ count = self.backend.install_colliders()
844
+ tested = []
845
+ for owner in list(self.backend.owner_map_ids)[:3]:
846
+ obj = self.backend.objects[owner]
847
+ nodes = getattr(obj, 'nodes', [obj.node])
848
+ expected = set()
849
+ samples = []
850
+ for node in nodes:
851
+ path = str(node['prim'].GetPath())
852
+ parts = path.split('/')
853
+ if len(parts) > 3:
854
+ expected.add(parts[3])
855
+ tri = self.backend.scene.triangles(node)
856
+ if tri.size:
857
+ centroids = tri.mean(axis=1)
858
+ centroids = centroids[(centroids[:, 2] > 0.18) & (centroids[:, 2] < 1.45)]
859
+ for centre in centroids[:3]:
860
+ samples.append(centre[:2])
861
+ lo, hi = obj.aabb
862
+ samples.insert(0, (lo + hi)[:2] / 2)
863
+ for xy in samples[:4]:
864
+ hits = self.C._body_hits(self.esc, *xy)
865
+ matched = expected.intersection(hits or set())
866
+ tested.append({'owner': owner, 'xy': list(map(float, xy)), 'expected_actual_prim_ancestors': sorted(expected), 'hits': sorted(hits or []), 'matched': sorted(matched)})
867
+ if matched:
868
+ return {'collision_meshes': count, 'body_probe': tested, 'native_visual_verified': False}
869
+ raise UnsupportedBinding('No PhysX hit on an actual registered owner prim ancestor; cannot use old movement safely')
870
+
871
+ def attach(driver, out, working=BASE / 'working', owner_map=BASE / 'OWNER_PART_MAP.json', motion_map=BASE / 'MOTION_BINDINGS.json', predicates=None, E=None, C=None):
872
+ if E is None:
873
+ E, C = load_stack(working)
874
+ level = Path(getattr(driver.level, '__file__', '')).stem.replace('level_', '')
875
+ if level in ('R01', 'R02'):
876
+ raise UnsupportedBinding(level + ' uses its dedicated data bridge; not silently adapted as EasyScene')
877
+ owners = read(owner_map)['levels'][level]
878
+ motions = read(motion_map)['levels'][level]
879
+ actual = hashlib.sha256(Path(driver.level.__file__).read_bytes()).hexdigest()
880
+ if actual != motions['source_sha256']:
881
+ raise UnsupportedBinding('Source SHA does not match frozen motion bindings: ' + level)
882
+ predicates = dict(predicates or {})
883
+
884
+ def scan(rule):
885
+ if isinstance(rule, dict):
886
+ if 'predicate' in rule:
887
+ name = rule['predicate']
888
+ prefix, _, symbol = name.partition('.')
889
+ if prefix == level and callable(getattr(driver.level, symbol, None)):
890
+ predicates.setdefault(name, getattr(driver.level, symbol))
891
+ for value in rule.values():
892
+ scan(value)
893
+ elif isinstance(rule, list):
894
+ for value in rule:
895
+ scan(value)
896
+ scan(motions)
897
+ backend = RoomsBackend(driver, level, owners, motions, predicates)
898
+ session = RoomsSession(backend, out, E, C)
899
+ session.native_gate()
900
+ return session
901
+
902
+ def validate_static(owner_map=BASE / 'OWNER_PART_MAP.json', motion_map=BASE / 'MOTION_BINDINGS.json'):
903
+ owners = read(owner_map)
904
+ motions = read(motion_map)
905
+ rows = []
906
+ for level, data in motions['levels'].items():
907
+ expected = {(o['owner_id'], p['part']) for o in owners['levels'][level]['owners'] for p in o['parts']}
908
+ actual = {(b['owner_id'], b['part']) for b in data['bindings']}
909
+ if actual != expected:
910
+ raise UnsupportedBinding('Owner/part mismatch ' + level)
911
+ for b in data['bindings']:
912
+ if b['opening_requirements'].get('status') != 'executable_structured':
913
+ raise UnsupportedBinding('Unknown gate ' + level)
914
+ ast.parse(b['node_access'], mode='eval')
915
+ rows.append({'level': level, 'parts': len(actual), 'contents': len(data.get('contents', [])), 'source_sha256': data['source_sha256']})
916
+ return {'levels': len(rows), 'parts': sum((x['parts'] for x in rows)), 'contents': sum((x['contents'] for x in rows)), 'rows': rows, 'runtime_installed': False, 'native_verified': False, 'unsupported_explicit': ['R01/R02 require dedicated bridge', 'Any predicate without supplied implementation', 'Missing actual Scene node/content owner or mismatched source SHA']}
917
+ if __name__ == '__main__':
918
+ print(json.dumps(validate_static(), ensure_ascii=False))
runtime/native_runtime/model_content554.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from PIL import Image
3
+ import json, base64
4
+ from observation1280 import WIDTH, HEIGHT, rules_for_budget
5
+ ACTION_FIELDS = ('action', 'distance', 'direction', 'degrees', 'part', 'code', 'point', 'photo', 'target', 'item', 'query')
6
+
7
+ def _paths(row, decision=False):
8
+ if decision:
9
+ value = row.get('decision_images') or ([row['decision_image']] if row.get('decision_image') else None)
10
+ if value:
11
+ return tuple((Path(p) for p in value))
12
+ return tuple((Path(p) for p in row.get('images') or ([row['image']] if row.get('image') else [])))
13
+
14
+ def _body(row):
15
+ action = {k: v for k, v in row.get('action', {}).items() if k in ACTION_FIELDS}
16
+ feedback = row.get('feedback', row.get('result', ''))
17
+ if isinstance(feedback, dict):
18
+ feedback = feedback.get('text', '')
19
+ return json.dumps(action, ensure_ascii=False) + ' -> ' + str(feedback or '')
20
+
21
+ def build_prompt_parts(packet, include_recent=True):
22
+ cap = int(packet.get('action_limit', 80))
23
+ holding = ', '.join(packet.get('holding', [])) or 'nothing'
24
+ notes = packet.get('notes', [])
25
+ note_text = '\nYour notes:\n' + ('\n'.join((f"{n['number']}. [step {n['step']}] {n['text']}" for n in notes)) if notes else '(none yet)')
26
+ header = rules_for_budget(cap) + f"\n\nYou are holding: {holding}.\nActions left: {packet.get('actions_left', max(0, cap - int(packet.get('step', 0))))}.\nRecalls left: {packet.get('recalls_left', 8)}.\n" + note_text + '\n\nYour last 10 steps:'
27
+ parts = [header]
28
+ now = _paths(packet)
29
+ shown = {}
30
+ recent = packet.get('recent', [])[-10:] if include_recent else []
31
+ if not recent:
32
+ parts.append('\n(none yet)')
33
+ for row in recent:
34
+ views = _paths(row, decision=True)
35
+ step = row['step']
36
+ body = _body(row)
37
+ if not views:
38
+ parts.append(f'\n[step {step}] ' + body)
39
+ elif views == now:
40
+ parts.append(f'\n[step {step}] (same view as your current view) ' + body)
41
+ elif views in shown:
42
+ parts.append(f'\n[step {step}] (same view as step {shown[views]}) ' + body)
43
+ else:
44
+ shown[views] = step
45
+ parts.extend([f'\n[step {step}]\n', *views, '\n' + body])
46
+ recalls = packet.get('recall_log', [])
47
+ if recalls:
48
+ agg = {}
49
+ for r in recalls:
50
+ query = str(r.get('query', '')).strip()
51
+ if query:
52
+ agg[query] = (int(r.get('found', 0)), agg.get(query, (0, 0))[1] + 1)
53
+ if agg:
54
+
55
+ def entry(q, n, c):
56
+ return json.dumps(q, ensure_ascii=False) + ' -> ' + (str(n) + (' entry' if n == 1 else ' entries') if n else 'nothing found') + (f' (asked {c} times)' if c > 1 else '')
57
+ parts.append('\nRecalls so far this game: ' + '; '.join((entry(q, n, c) for q, (n, c) in agg.items())) + '.')
58
+ if packet.get('recall_requested'):
59
+ parts.append('\n\nResult of the recall you just made:\n' + str(packet.get('recall_feedback', '')))
60
+ for row in packet.get('recall', []):
61
+ parts.extend([f"\n [step {row['step']}]\n", *_paths(row, decision=True), '\n ' + _body(row)])
62
+ if now:
63
+ parts.extend(['\n\nYour current view:\n', *now, '\nThe last photo above is your current view; you can only act on things in it. Reply with one JSON object.'])
64
+ else:
65
+ parts.append('\n\nThere is no photo in front of you yet. Reply with one JSON object.')
66
+ return parts
67
+
68
+ def build_model_user_content(packet, include_recent=True):
69
+ content = []
70
+ for value in build_prompt_parts(packet, include_recent):
71
+ if isinstance(value, Path):
72
+ if value.suffix.lower() not in ('.png', '.jpg', '.jpeg'):
73
+ raise ValueError('Expected a local PNG/JPEG observation')
74
+ with Image.open(value) as im:
75
+ if im.size != (WIDTH, HEIGHT):
76
+ raise ValueError('Model input must remain640x360; no resizing fallback')
77
+ mime = 'image/png' if value.suffix.lower() == '.png' else 'image/jpeg'
78
+ content.append({'type': 'image_url', 'image_url': {'url': 'data:' + mime + ';base64,' + base64.b64encode(value.read_bytes()).decode('ascii')}})
79
+ else:
80
+ content.append({'type': 'text', 'text': str(value)})
81
+ return content
runtime/native_runtime/native_primitives364.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import math
3
+ import numpy as np
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ from font_utils import load_font
6
+
7
+ class Art:
8
+
9
+ def __init__(self, og, run):
10
+ from pxr import UsdGeom, UsdShade, Gf, Sdf
11
+ self.og = og
12
+ self.stage = og.sim.stage
13
+ self.G = UsdGeom
14
+ self.S = UsdShade
15
+ self.F = Gf
16
+ self.D = Sdf
17
+ self.run = Path(run)
18
+ self.tex = self.run / 'textures'
19
+ self.tex.mkdir(exist_ok=True)
20
+ self.nodes = {}
21
+ self.groups = {}
22
+ self.mats = {}
23
+ self.count = 0
24
+ self.textures()
25
+ self.palette()
26
+
27
+ def textures(self):
28
+ rng = np.random.default_rng(361)
29
+ h = w = 768
30
+ y, x = np.mgrid[:h, :w]
31
+ grain = np.sin(x * 0.065 + np.sin(y * 0.007) * 5) + 0.5 * np.sin(x * 0.2 + np.sin(y * 0.012) * 3) + 0.2 * rng.normal(size=(h, w))
32
+ bands = 2.5 * np.sin(y * 0.004) + grain * 9
33
+ wood = np.clip(np.array([132, 87, 48])[None, None, :] + bands[:, :, None] * np.array([1.0, 0.78, 0.52]), 0, 255).astype('uint8')
34
+ Image.fromarray(wood).save(self.tex / 'wood.png')
35
+ wall = np.clip(np.array([151, 156, 147])[None, None, :] + rng.normal(0, 2, (h, w, 1)) + 3 * np.sin(x * 0.009)[:, :, None], 0, 255).astype('uint8')
36
+ Image.fromarray(wall).save(self.tex / 'plaster.png')
37
+ paint = np.clip(np.array([70, 96, 107])[None, None, :] + rng.normal(0, 2.2, (h, w, 1)), 0, 255).astype('uint8')
38
+ im = Image.fromarray(paint)
39
+ d = ImageDraw.Draw(im)
40
+ for _ in range(220):
41
+ a, b = rng.integers(0, 768, 2)
42
+ d.line((int(a), int(b), int(a + rng.integers(2, 14)), int(b + rng.integers(-3, 4))), fill=(76, 84, 82), width=1)
43
+ im.save(self.tex / 'paint.png')
44
+ from scipy.ndimage import gaussian_filter
45
+ grime = gaussian_filter(rng.normal(0, 1, (h, w)), 24)
46
+ grime = (grime - grime.mean()) / (grime.std() + 1e-06)
47
+ fine = rng.normal(0, 2, (h, w))
48
+ dirt = np.clip(np.array([147, 130, 99])[None, None, :] + grime[:, :, None] * np.array([11, 10, 8]) + fine[:, :, None], 0, 255).astype('uint8')
49
+ im = Image.fromarray(dirt)
50
+ d = ImageDraw.Draw(im)
51
+ for _ in range(900):
52
+ a, b = rng.integers(0, 768, 2)
53
+ rad = int(rng.integers(1, 5))
54
+ d.ellipse((int(a), int(b), int(a + rad), int(b + rad)), fill=(111, 99, 78))
55
+ im.save(self.tex / 'dust.png')
56
+
57
+ def mat(self, name, color=(0.5, 0.5, 0.5), rough=0.6, metal=0.0, texture=None, emission=None, opacity=1.0):
58
+ if name in self.mats:
59
+ return self.mats[name]
60
+ with self.og.sim.editing_usd():
61
+ p = '/World/redesign364/materials/' + name
62
+ m = self.S.Material.Define(self.stage, p)
63
+ s = self.S.Shader.Define(self.stage, p + '/surface')
64
+ s.CreateIdAttr('UsdPreviewSurface')
65
+ s.CreateInput('diffuseColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(*color))
66
+ s.CreateInput('roughness', self.D.ValueTypeNames.Float).Set(rough)
67
+ s.CreateInput('metallic', self.D.ValueTypeNames.Float).Set(metal)
68
+ if opacity < 1:
69
+ s.CreateInput('opacity', self.D.ValueTypeNames.Float).Set(opacity)
70
+ if name == 'dust':
71
+ s.CreateInput('useSpecularWorkflow', self.D.ValueTypeNames.Int).Set(1)
72
+ s.CreateInput('specularColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(0, 0, 0))
73
+ if emission:
74
+ s.CreateInput('emissiveColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(*emission))
75
+ if texture:
76
+ t = self.S.Shader.Define(self.stage, p + '/texture')
77
+ t.CreateIdAttr('UsdUVTexture')
78
+ t.CreateInput('file', self.D.ValueTypeNames.Asset).Set(str(texture))
79
+ t.CreateOutput('rgb', self.D.ValueTypeNames.Float3)
80
+ st = self.S.Shader.Define(self.stage, p + '/st')
81
+ st.CreateIdAttr('UsdPrimvarReader_float2')
82
+ st.CreateInput('varname', self.D.ValueTypeNames.Token).Set('st')
83
+ t.CreateInput('st', self.D.ValueTypeNames.Float2).ConnectToSource(st.ConnectableAPI(), 'result')
84
+ s.CreateInput('diffuseColor', self.D.ValueTypeNames.Color3f).ConnectToSource(t.ConnectableAPI(), 'rgb')
85
+ m.CreateSurfaceOutput().ConnectToSource(s.ConnectableAPI(), 'surface')
86
+ self.mats[name] = m
87
+ return m
88
+
89
+ def palette(self):
90
+ self.mat('wood', texture=self.tex / 'wood.png', rough=0.65)
91
+ self.mat('darkwood', (0.17, 0.095, 0.045), rough=0.7)
92
+ self.mat('paint', texture=self.tex / 'paint.png', rough=0.52, metal=0.22)
93
+ self.mat('plaster', texture=self.tex / 'plaster.png', rough=0.94)
94
+ self.mat('steel', (0.46, 0.52, 0.55), rough=0.38, metal=0.55)
95
+ self.mat('iron', (0.055, 0.066, 0.07), rough=0.5, metal=0.7)
96
+ self.mat('brass', (0.7, 0.47, 0.16), rough=0.38, metal=0.65)
97
+ self.mat('rubber', (0.035, 0.043, 0.045), rough=0.84)
98
+ self.mat('paper', (0.78, 0.74, 0.62), rough=0.95)
99
+ self.mat('cloth', (0.16, 0.23, 0.22), rough=0.98)
100
+ self.mat('red', (0.4, 0.12, 0.065), rough=0.6)
101
+ self.mat('bristle', (0.61, 0.43, 0.23), rough=0.94)
102
+ self.mat('glass', (0.15, 0.23, 0.24), rough=0.12, metal=0.1, opacity=0.12)
103
+ self.mat('lamp', (0.92, 0.68, 0.34), rough=0.3, emission=(3.0, 1.6, 0.55))
104
+ self.mat('green', (0.09, 0.25, 0.12), rough=0.3, emission=(0.08, 0.55, 0.13))
105
+ self.mat('dust', texture=self.tex / 'dust.png', rough=1.0, opacity=1.0)
106
+ self.mat('drawer_felt', (0.24, 0.38, 0.41), rough=1.0)
107
+ self.mat('key_gold', (0.9, 0.57, 0.13), rough=0.44, metal=0.45)
108
+
109
+ def group(self, key, pos=(0, 0, 0), parent=None):
110
+ with self.og.sim.editing_usd():
111
+ base = str(parent['prim'].GetPath()) if parent else '/World/redesign364'
112
+ x = self.G.Xform.Define(self.stage, base + '/' + key)
113
+ t = x.AddTranslateOp()
114
+ t.Set(self.F.Vec3d(*pos))
115
+ rot = x.AddRotateXYZOp()
116
+ rot.Set(self.F.Vec3f(0, 0, 0))
117
+ node = {'prim': x.GetPrim(), 'translate': t, 'rotate': rot, 'meshes': []}
118
+ self.groups[key] = node
119
+ return node
120
+
121
+ def transform(self, group, pos=None, rpy=None):
122
+ with self.og.sim.editing_usd():
123
+ xform = self.G.Xformable(group['prim'])
124
+
125
+ def operation(key, kind, create):
126
+ if group.get(key) is not None:
127
+ return group[key]
128
+ ops = [op for op in xform.GetOrderedXformOps() if op.GetOpType() == kind and (not op.IsInverseOp())]
129
+ preferred = [op for op in ops if str(op.GetOpName()) == 'xformOp:' + key]
130
+ if len(preferred) == 1:
131
+ op = preferred[0]
132
+ elif len(ops) == 1:
133
+ op = ops[0]
134
+ elif ops:
135
+ raise ValueError('Ambiguous authored ' + key + ' xform ops')
136
+ else:
137
+ op = create()
138
+ group[key] = op
139
+ return op
140
+
141
+ def vector(op, values):
142
+ vector_type = self.F.Vec3d if op.GetPrecision() == self.G.XformOp.PrecisionDouble else self.F.Vec3f
143
+ op.Set(vector_type(*map(float, values)))
144
+ if pos is not None:
145
+ vector(operation('translate', self.G.XformOp.TypeTranslate, xform.AddTranslateOp), pos)
146
+ if rpy is not None:
147
+ vector(operation('rotate', self.G.XformOp.TypeRotateXYZ, xform.AddRotateXYZOp), rpy)
148
+
149
+ def mesh(self, key, points, faces, material='wood', parent=None, uv=None):
150
+ mat = self.mats[material] if isinstance(material, str) else material
151
+ self.count += 1
152
+ base = str(parent['prim'].GetPath()) if parent else '/World/redesign364/geometry'
153
+ path = base + '/' + key + '_' + str(self.count)
154
+ points = np.asarray(points, float)
155
+ indices = [int(i) for f in faces for i in f]
156
+ if uv is None:
157
+ lo = points.min(0)
158
+ size = np.maximum(points.max(0) - lo, 0.001)
159
+ uv = []
160
+ for face in faces:
161
+ pp = points[list(face)]
162
+ normal = np.abs(np.cross(pp[1] - pp[0], pp[2] - pp[0]))
163
+ axes = [i for i in range(3) if i != int(normal.argmax())]
164
+ uv.extend([((points[i, axes[0]] - lo[axes[0]]) / size[axes[0]], (points[i, axes[1]] - lo[axes[1]]) / size[axes[1]]) for i in face])
165
+ with self.og.sim.editing_usd():
166
+ m = self.G.Mesh.Define(self.stage, path)
167
+ m.CreatePointsAttr([self.F.Vec3f(*v) for v in points])
168
+ m.CreateFaceVertexCountsAttr([len(f) for f in faces])
169
+ m.CreateFaceVertexIndicesAttr(indices)
170
+ m.CreateSubdivisionSchemeAttr('none')
171
+ m.CreateDoubleSidedAttr(True)
172
+ self.G.PrimvarsAPI(m).CreatePrimvar('st', self.D.ValueTypeNames.TexCoord2fArray, self.G.Tokens.faceVarying).Set(uv)
173
+ self.S.MaterialBindingAPI.Apply(m.GetPrim()).Bind(mat)
174
+ node = {'prim': m.GetPrim(), 'points': points, 'faces': faces, 'meshes': []}
175
+ if parent:
176
+ parent['meshes'].append(node)
177
+ self.nodes[key] = node
178
+ return node
179
+
180
+ def box(self, key, c, size, mat='wood', parent=None, bevel=0.008):
181
+ from scipy.spatial import ConvexHull
182
+ c = np.asarray(c, float)
183
+ h = np.asarray(size, float) / 2
184
+ b = min(bevel, float(min(h)) * 0.35)
185
+ pts = []
186
+ for axis in range(3):
187
+ for sx in [-1, 1]:
188
+ for sy in [-1, 1]:
189
+ for sz in [-1, 1]:
190
+ v = (h - b) * np.array([sx, sy, sz])
191
+ v[axis] = h[axis] * [sx, sy, sz][axis]
192
+ pts.append(c + v)
193
+ pts = np.array(pts)
194
+ hull = ConvexHull(pts)
195
+ faces = []
196
+ for tri, eq in zip(hull.simplices, hull.equations):
197
+ f = list(map(int, tri))
198
+ p = pts[f]
199
+ if np.dot(np.cross(p[1] - p[0], p[2] - p[0]), eq[:3]) < 0:
200
+ f = f[::-1]
201
+ faces.append(f)
202
+ return self.mesh(key, pts, faces, mat, parent)
203
+
204
+ def cylinder(self, key, c, radius, length, mat='steel', axis='z', parent=None, n=18):
205
+ c = np.array(c, float)
206
+ pts = []
207
+ for end in [-0.5, 0.5]:
208
+ for i in range(n):
209
+ a = 2 * math.pi * i / n
210
+ v = np.array([radius * math.cos(a), radius * math.sin(a), length * end])
211
+ if axis == 'x':
212
+ v = v[[2, 0, 1]]
213
+ if axis == 'y':
214
+ v = v[[0, 2, 1]]
215
+ pts.append(c + v)
216
+ faces = [list(range(n - 1, -1, -1)), list(range(n, n * 2))]
217
+ faces += [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)]
218
+ return self.mesh(key, pts, faces, mat, parent)
219
+
220
+ def tube(self, key, a, b, radius=0.025, mat='steel', parent=None):
221
+ from scipy.spatial.transform import Rotation
222
+ a = np.array(a, float)
223
+ b = np.array(b, float)
224
+ delta = b - a
225
+ ln = np.linalg.norm(delta)
226
+ z = delta / ln
227
+ right = np.cross(z, [0, 0, 1] if abs(z[2]) < 0.95 else [0, 1, 0])
228
+ right /= np.linalg.norm(right)
229
+ up = np.cross(z, right)
230
+ pts = []
231
+ n = 16
232
+ for end in [a, b]:
233
+ for i in range(n):
234
+ t = 2 * math.pi * i / n
235
+ pts.append(end + radius * (right * math.cos(t) + up * math.sin(t)))
236
+ faces = [list(range(n - 1, -1, -1)), list(range(n, n * 2))] + [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)]
237
+ return self.mesh(key, pts, faces, mat, parent)
238
+
239
+ def plane(self, key, c, w, h, right, up, texture, parent=None, material=None):
240
+ c = np.array(c, float)
241
+ r = np.array(right, float) * w / 2
242
+ u = np.array(up, float) * h / 2
243
+ if material is None:
244
+ material = self.mat('image_' + key, texture=texture, rough=0.9, emission=None)
245
+ return self.mesh(key, [c - r - u, c + r - u, c + r + u, c - r + u], [[0, 1, 2, 3]], material, parent, uv=[(0, 0), (1, 0), (1, 1), (0, 1)])
246
+
247
+ def visibility(self, node, on):
248
+ with self.og.sim.editing_usd():
249
+ self.G.Imageable(node['prim']).GetVisibilityAttr().Set(self.G.Tokens.inherited if on else self.G.Tokens.invisible)
250
+
251
+ def triangles(self, node):
252
+ result = []
253
+ cache = self.G.XformCache()
254
+ meshes = node['meshes'] if node.get('meshes') else [node]
255
+ for mesh in meshes:
256
+ if 'points' not in mesh:
257
+ continue
258
+ T = cache.GetLocalToWorldTransform(mesh['prim'])
259
+ pts = np.array([list(T.Transform(self.F.Vec3d(*p))) for p in mesh['points']])
260
+ for f in mesh['faces']:
261
+ for i in range(1, len(f) - 1):
262
+ result.append(pts[[f[0], f[i], f[i + 1]]])
263
+ return np.array(result)
264
+
265
+ def candidate(self, key, node):
266
+ tri = self.triangles(node)
267
+ p = tri.reshape(-1, 3)
268
+ return {'key': key, 'room': 'workshop', 'lo': p.min(0).tolist(), 'hi': p.max(0).tolist(), 'triangles': tri.tolist()}
269
+
270
+ def label_image(self, key, text, width=800, height=200):
271
+ im = Image.new('RGB', (width, height), (202, 187, 152))
272
+ d = ImageDraw.Draw(im)
273
+ f = load_font(int(height * 0.35))
274
+ d.text((height * 0.12, height * 0.25), text, font=f, fill=(38, 48, 47))
275
+ p = self.tex / (key + '.png')
276
+ im.save(p)
277
+ return p
278
+
279
+ def framed(self, key, c, w, h, right, up, texture, parent=None):
280
+ c = np.array(c, float)
281
+ r = np.array(right, float)
282
+ u = np.array(up, float)
283
+ normal = np.cross(r, u)
284
+ if abs(normal[1]) > 0.9:
285
+ for i in [-1, 1]:
286
+ self.box(key + '_side', c + r * i * (w / 2 + 0.025), [0.045, 0.06, h + 0.1], 'darkwood', parent)
287
+ for i in [-1, 1]:
288
+ self.box(key + '_edge', c + u * i * (h / 2 + 0.025), [w + 0.1, 0.06, 0.045], 'darkwood', parent)
289
+ elif abs(normal[0]) > 0.9:
290
+ for i in [-1, 1]:
291
+ self.box(key + '_side', c + r * i * (w / 2 + 0.025), [0.06, 0.045, h + 0.1], 'darkwood', parent)
292
+ for i in [-1, 1]:
293
+ self.box(key + '_edge', c + u * i * (h / 2 + 0.025), [0.06, w + 0.1, 0.045], 'darkwood', parent)
294
+ return self.plane(key, c + normal * 0.007, w, h, right, up, texture, parent)
295
+
296
+ def tool(self, key):
297
+ g = self.group('tool_' + key, [0, 0, -8])
298
+ if key == 'hammer':
299
+ self.box('hammer_handle', [0, 0, -0.035], [0.034, 0.04, 0.29], 'wood', g, bevel=0.012)
300
+ self.box('hammer_collar', [0, 0, 0.095], [0.045, 0.05, 0.055], 'iron', g)
301
+ self.box('hammer_head', [0, 0, 0.13], [0.19, 0.065, 0.065], 'steel', g)
302
+ self.cylinder('hammer_face', [-0.115, 0, 0.13], 0.047, 0.045, 'steel', 'x', g)
303
+ for y in [-0.022, 0.022]:
304
+ self.tube('hammer_claw', [0.07, y, 0.14], [0.13, y, 0.15], 0.019, 'steel', g)
305
+ self.tube('hammer_claw_tip', [0.13, y, 0.15], [0.18, y, 0.095], 0.013, 'steel', g)
306
+ elif key == 'screwdriver':
307
+ self.cylinder('driver_handle', [0, 0, -0.075], 0.032, 0.145, 'red', 'z', g)
308
+ for x in [-0.024, 0.024]:
309
+ self.box('driver_grip', [x, -0.012, -0.075], [0.008, 0.045, 0.105], 'iron', g, bevel=0.002)
310
+ self.cylinder('driver_collar', [0, 0, 0.005], 0.023, 0.025, 'steel', 'z', g)
311
+ self.cylinder('driver_shaft', [0, 0, 0.08], 0.008, 0.15, 'steel', 'z', g)
312
+ self.box('driver_flat_tip', [0, 0, 0.165], [0.022, 0.008, 0.035], 'steel', g, bevel=0.002)
313
+ elif key == 'brush':
314
+ self.box('brush_handle', [0, 0, -0.075], [0.037, 0.035, 0.17], 'wood', g, bevel=0.012)
315
+ self.box('brush_ferrule', [0, 0, 0.027], [0.105, 0.035, 0.07], 'steel', g)
316
+ self.box('brush_bristles', [0, 0, 0.105], [0.115, 0.035, 0.1], 'bristle', g, bevel=0.002)
317
+ for x in np.linspace(-0.049, 0.049, 10):
318
+ self.box('bristle_line', [float(x), -0.019, 0.105], [0.003, 0.003, 0.095], 'darkwood', g, bevel=0.0004)
319
+ elif key == 'wrench':
320
+ self.box('wrench_handle', [0, 0, -0.035], [0.042, 0.025, 0.26], 'steel', g, bevel=0.01)
321
+ self.box('wrench_neck', [0, 0, 0.1], [0.06, 0.028, 0.07], 'steel', g)
322
+ for side in [-1, 1]:
323
+ self.box('wrench_jaw', [side * 0.046, 0, 0.15], [0.035, 0.032, 0.09], 'steel', g, bevel=0.008)
324
+ self.box('wrench_tip', [side * 0.037, 0, 0.195], [0.04, 0.032, 0.024], 'steel', g, bevel=0.005)
325
+ self.cylinder('wrench_eye', [0, 0, -0.17], 0.035, 0.026, 'steel', 'y', g)
326
+ self.cylinder('wrench_eye_hole', [0, -0.015, -0.17], 0.013, 0.004, 'iron', 'y', g)
327
+ elif key == 'key':
328
+ n = 32
329
+ pts = []
330
+ for y in [-0.009, 0.009]:
331
+ for radius in [0.035, 0.021]:
332
+ for i in range(n):
333
+ t = 2 * math.pi * i / n
334
+ pts.append([radius * math.cos(t), y, 0.055 + radius * math.sin(t)])
335
+ faces = []
336
+ for i in range(n):
337
+ j = (i + 1) % n
338
+ faces += [[i, j, n + j, n + i], [2 * n + i, 3 * n + i, 3 * n + j, 2 * n + j], [i, 2 * n + i, 2 * n + j, j], [n + i, n + j, 3 * n + j, 3 * n + i]]
339
+ self.mesh('key_ring', pts, faces, 'key_gold', g)
340
+ self.box('key_shaft', [0, 0, -0.025], [0.015, 0.016, 0.12], 'key_gold', g, bevel=0.003)
341
+ self.box('key_bit', [0.022, 0, -0.065], [0.045, 0.016, 0.04], 'key_gold', g, bevel=0.003)
342
+ with self.og.sim.editing_usd():
343
+ self.G.Xformable(g['prim']).AddScaleOp().Set(self.F.Vec3f(1.35, 1.35, 1.35))
344
+ return g
345
+
346
+ def build(self, photo_paths=None):
347
+ for i in range(24):
348
+ self.box('floor_plank', [0.125 + i * 0.25, 2.5, -0.02], [0.247, 5.02, 0.05], 'wood', bevel=0.002)
349
+ for c, size in [([0, 2.5, 1.4], [0.14, 5.2, 2.8]), ([6, 2.5, 1.4], [0.14, 5.2, 2.8]), ([3, 5, 1.4], [6.1, 0.14, 2.8]), ([1.2, 0, 1.4], [2.4, 0.14, 2.8]), ([4.8, 0, 1.4], [2.4, 0.14, 2.8])]:
350
+ self.box('wall', c, size, 'plaster')
351
+ self.box('door_header', [3, 0, 2.58], [1.25, 0.16, 0.44], 'darkwood')
352
+ for c, size in [([0.09, 2.5, 0.45], [0.05, 5.0, 0.9]), ([5.91, 2.5, 0.45], [0.05, 5.0, 0.9]), ([3, 4.91, 0.45], [5.85, 0.05, 0.9])]:
353
+ self.box('wainscot', c, size, 'paint')
354
+ for x in [0.12, 5.88]:
355
+ self.box('skirting', [x, 2.5, 0.09], [0.08, 4.9, 0.16], 'darkwood')
356
+ self.box('dado', [x, 2.5, 0.92], [0.08, 4.9, 0.055], 'darkwood')
357
+ self.box('north_skirting', [3, 4.88, 0.09], [5.9, 0.09, 0.16], 'darkwood')
358
+ self.box('north_dado', [3, 4.88, 0.92], [5.9, 0.09, 0.055], 'darkwood')
359
+ for y in [0.35, 2.5, 4.65]:
360
+ self.box('ceiling_beam', [3, y, 2.72], [6, 0.12, 0.16], 'darkwood')
361
+ self.box('ceiling', [3, 2.5, 2.84], [6.2, 5.2, 0.1], 'plaster')
362
+ self.box('bench_top', [2.85, 4.55, 0.88], [1.65, 0.72, 0.1], 'wood', bevel=0.025)
363
+ for x in [2.12, 3.58]:
364
+ for y in [4.28, 4.82]:
365
+ self.box('bench_leg', [x, y, 0.44], [0.075, 0.075, 0.83], 'iron')
366
+ self.box('bench_stretcher', [2.85, 4.62, 0.2], [1.48, 0.06, 0.07], 'iron')
367
+ self.box('bench_shelf', [2.85, 4.55, 0.27], [1.48, 0.6, 0.06], 'wood')
368
+ for i in range(3):
369
+ self.cylinder('parts_tin', [2.15 + i * 0.19, 4.73, 0.99], 0.065, 0.15, 'paint')
370
+ self.cylinder('tin_lid', [2.15 + i * 0.19, 4.73, 1.07], 0.068, 0.02, 'steel')
371
+ self.box('folded_rag', [3.48, 4.55, 0.95], [0.28, 0.24, 0.035], 'cloth')
372
+ self.cylinder('lamp_base', [3.48, 4.77, 0.98], 0.11, 0.05, 'iron')
373
+ self.tube('lamp_stem', [3.48, 4.77, 1.0], [3.48, 4.77, 1.42], 0.018, 'steel')
374
+ self.tube('lamp_arm', [3.48, 4.77, 1.42], [3.22, 4.58, 1.48], 0.022, 'steel')
375
+ self.cylinder('lamp_shade', [3.22, 4.58, 1.46], 0.13, 0.1, 'paint')
376
+ self.cylinder('lamp_diffuser', [3.22, 4.58, 1.4], 0.105, 0.008, 'lamp')
377
+ self.box('case_stand_top', [1.0, 0.95, 0.46], [0.95, 0.62, 0.07], 'wood')
378
+ for x in [0.6, 1.4]:
379
+ for y in [0.71, 1.19]:
380
+ self.box('stand_leg', [x, y, 0.23], [0.07, 0.07, 0.44], 'iron')
381
+ for c, size in [([1.0, 0.7, 0.64], [0.72, 0.045, 0.28]), ([1.0, 1.2, 0.64], [0.72, 0.045, 0.28]), ([0.66, 0.95, 0.64], [0.045, 0.5, 0.28]), ([1.34, 0.95, 0.64], [0.045, 0.5, 0.28]), ([1.0, 0.95, 0.515], [0.72, 0.5, 0.035])]:
382
+ self.box('case_body', c, size, 'wood')
383
+ case = self.group('case_lid', [1.0, 1.21, 0.79])
384
+ self.box('case_lid_leaf', [0, -0.26, 0], [0.78, 0.56, 0.055], 'darkwood', case)
385
+ for x in [-0.29, 0.29]:
386
+ self.box('case_hinge', [x, -0.015, 0.028], [0.1, 0.06, 0.025], 'brass', case)
387
+ self.box('case_latch', [0, -0.54, -0.055], [0.08, 0.04, 0.085], 'brass', case)
388
+ for c, size in [([0.18, 4.0, 1.03], [0.08, 0.85, 2.05]), ([0.5, 3.58, 1.03], [0.66, 0.07, 2.05]), ([0.5, 4.42, 1.03], [0.66, 0.07, 2.05]), ([0.5, 4.0, 2.02], [0.66, 0.9, 0.06]), ([0.5, 4.0, 0.1], [0.66, 0.9, 0.1])]:
389
+ self.box('locker_body', c, size, 'paint')
390
+ for z in [0.55, 1.05, 1.55]:
391
+ self.box('locker_shelf', [0.5, 4.0, z], [0.6, 0.78, 0.035], 'steel')
392
+ locker = self.group('locker_door', [0.84, 4.43, 0])
393
+ self.box('locker_leaf', [0, -0.43, 1.05], [0.055, 0.86, 1.93], 'paint', locker)
394
+ self.box('locker_handle', [0.06, -0.71, 1.13], [0.08, 0.04, 0.18], 'brass', locker)
395
+ for z in [1.1, 1.25]:
396
+ self.cylinder('brush_clip', [-0.045, -0.43, z], 0.022, 0.065, 'brass', 'x', locker)
397
+ for z in [1.7, 1.78, 1.86]:
398
+ self.box('locker_vent', [0.032, -0.43, z], [0.008, 0.38, 0.018], 'iron', locker, bevel=0.002)
399
+ for z in [0.2, 0.36, 0.52, 0.68]:
400
+ self.box('crate_front', [0.82, 2.08, z], [0.06, 0.73, 0.145], 'wood')
401
+ self.box('crate_back', [0.16, 2.08, z], [0.06, 0.73, 0.145], 'wood')
402
+ for y in [1.71, 2.45]:
403
+ self.box('crate_side', [0.49, y, z], [0.66, 0.06, 0.145], 'wood')
404
+ self.box('crate_bottom', [0.49, 2.08, 0.12], [0.66, 0.72, 0.06], 'darkwood')
405
+ self.box('crate_padded_insert', [0.49, 2.08, 0.49], [0.59, 0.64, 0.045], 'cloth')
406
+ crate = self.group('crate_lid', [0.49, 2.47, 0.78])
407
+ self.box('crate_top', [0, -0.39, 0], [0.78, 0.82, 0.065], 'wood', crate)
408
+ for x in [-0.28, 0.28]:
409
+ self.box('crate_batten', [x, -0.39, 0.05], [0.07, 0.76, 0.035], 'darkwood', crate)
410
+ nail = self.group('crate_fasteners', [0.49, 2.47, 0.78])
411
+ for x in [-0.28, 0.28]:
412
+ self.cylinder('raised_nail', [x, -0.7, 0.085], 0.02, 0.055, 'iron', 'z', nail)
413
+ self.cylinder('nail_head', [x, -0.7, 0.115], 0.03, 0.012, 'steel', 'z', nail)
414
+ for c, size in [([5.7, 2.3, 0.72], [0.1, 1.15, 1.35]), ([5.3, 1.75, 0.72], [0.86, 0.08, 1.35]), ([5.3, 2.85, 0.72], [0.86, 0.08, 1.35]), ([5.3, 2.3, 0.1], [0.9, 1.2, 0.15]), ([5.3, 2.3, 1.38], [0.9, 1.2, 0.1])]:
415
+ self.box('pump_body', c, size, 'paint')
416
+ self.cylinder('pump_motor', [5.35, 2.3, 1.65], 0.24, 0.55, 'iron', 'x')
417
+ for x in [5.05, 5.2, 5.35, 5.5, 5.65]:
418
+ self.cylinder('motor_rib', [x, 2.3, 1.65], 0.255, 0.035, 'steel', 'x')
419
+ self.tube('pipe_a', [5.6, 2.3, 1.7], [5.6, 2.3, 2.2], 0.065)
420
+ self.tube('pipe_b', [5.6, 2.3, 2.2], [5.88, 2.3, 2.2], 0.065)
421
+ self.cylinder('pipe_flange', [5.6, 2.3, 2.05], 0.12, 0.06, 'brass', 'z')
422
+ self.box('service_ledge', [5.28, 2.3, 0.55], [0.65, 0.9, 0.06], 'steel')
423
+ hatch = self.group('pump_hatch', [4.86, 2.88, 0])
424
+ self.box('hatch_leaf', [0, -0.58, 0.78], [0.055, 1.13, 1.12], 'paint', hatch)
425
+ self.box('hatch_handle', [-0.06, -0.85, 0.78], [0.06, 0.06, 0.21], 'steel', hatch)
426
+ screw = self.group('hatch_screw', [4.82, 2.3, 1.13])
427
+ self.cylinder('screw_head', [0, 0, 0], 0.044, 0.025, 'steel', 'x', screw)
428
+ self.box('screw_slot', [-0.014, 0, 0], [0.004, 0.058, 0.01], 'iron', screw, bevel=0.0005)
429
+ self.box('rack_board', [4.7, 4.86, 1.63], [1.25, 0.1, 1.25], 'wood', bevel=0.025)
430
+ for x in [4.07, 5.33]:
431
+ self.box('rack_rail', [x, 4.79, 1.63], [0.055, 0.07, 1.29], 'darkwood')
432
+ for z in [1.0, 2.26]:
433
+ self.box('rack_rail', [4.7, 4.79, z], [1.3, 0.07, 0.055], 'darkwood')
434
+ self.box('rack_corner1', [4.13, 4.73, 2.2], [0.18, 0.025, 0.035], 'brass')
435
+ self.box('rack_corner2', [4.06, 4.73, 2.13], [0.035, 0.025, 0.18], 'brass')
436
+ slots = [(4.42, 4.7, 1.94), (4.98, 4.7, 1.94), (4.42, 4.7, 1.4), (4.98, 4.7, 1.4)]
437
+ slotnodes = []
438
+ for i, c in enumerate(slots):
439
+ p = np.array(c)
440
+ pad = self.box('holder' + str(i), p + [0, 0.035, -0.03], [0.17, 0.025, 0.22], 'paint')
441
+ for dx in [-0.055, 0.055]:
442
+ self.cylinder('holder_pin', [p[0] + dx, p[1] - 0.005, p[2] - 0.05], 0.012, 0.1, 'brass', 'y')
443
+ slotnodes.append(pad)
444
+ self.tube('rack_latch_link', [4.1, 4.75, 1.0], [4.1, 4.75, 0.74], 0.015, 'brass')
445
+ for c, size in [([4.7, 4.9, 0.58], [1.15, 0.08, 0.8]), ([4.13, 4.69, 0.58], [0.07, 0.5, 0.8]), ([5.27, 4.69, 0.58], [0.07, 0.5, 0.8]), ([4.7, 4.69, 0.97], [1.15, 0.5, 0.07]), ([4.7, 4.69, 0.2], [1.15, 0.5, 0.08])]:
446
+ self.box('keycab_body', c, size, 'paint')
447
+ drawer = self.group('key_drawer', [4.7, 4.69, 0.47])
448
+ self.box('drawer_tray', [0, 0, 0], [0.99, 0.43, 0.05], 'wood', drawer)
449
+ self.box('drawer_lining', [0, 0, 0.035], [0.93, 0.37, 0.012], 'drawer_felt', drawer)
450
+ for x in [-0.49, 0.49]:
451
+ self.box('drawer_front_side', [x, -0.24, 0.135], [0.08, 0.05, 0.28], 'paint', drawer)
452
+ self.box('drawer_sidewall', [x, 0, 0.075], [0.03, 0.43, 0.12], 'wood', drawer)
453
+ self.box('drawer_slide', [x * 0.97, 0, -0.035], [0.025, 0.44, 0.035], 'steel', drawer)
454
+ for z in [-0.005, 0.275]:
455
+ self.box('drawer_front_rail', [0, -0.24, z], [1.06, 0.05, 0.05], 'paint', drawer)
456
+ glass = self.plane('drawer_glass', [0, -0.268, 0.135], 0.89, 0.21, [1, 0, 0], [0, 0, 1], None, drawer, material=self.mats['glass'])
457
+ self.box('drawer_handle', [0, -0.3, 0.26], [0.28, 0.055, 0.045], 'brass', drawer)
458
+ label = self.label_image('shift_label', 'SHIFT HANDOVER', 900, 160)
459
+ self.plane('shift_label', [4.7, 4.412, 0.92], 0.63, 0.11, [1, 0, 0], [0, 0, 1], label)
460
+ self.box('keycab_light_strip', [4.7, 4.65, 0.882], [0.32, 0.08, 0.018], 'lamp')
461
+ lamp = self.cylinder('rack_status', [5.18, 4.42, 0.91], 0.025, 0.02, 'brass', 'y')
462
+ for x in [2.4, 3.6]:
463
+ self.box('door_jamb', [x, 0.05, 1.17], [0.12, 0.2, 2.35], 'darkwood')
464
+ door = self.group('exit_door', [2.46, 0.09, 0])
465
+ self.box('door_leaf', [0.54, 0, 1.13], [1.08, 0.1, 2.22], 'wood', door, bevel=0.025)
466
+ for z in [0.27, 1.95]:
467
+ self.box('door_iron_band', [0.54, 0.06, z], [1.02, 0.04, 0.1], 'iron', door)
468
+ self.box('door_lock_plate', [0.93, 0.075, 1.03], [0.13, 0.04, 0.24], 'brass', door)
469
+ self.cylinder('door_knob', [0.93, 0.13, 1.1], 0.045, 0.08, 'steel', 'y', door)
470
+ self.cylinder('keyhole', [0.93, 0.101, 0.99], 0.02, 0.006, 'iron', 'y', door)
471
+ self.box('porch', [3.0, -0.5, -0.025], [1.5, 1.0, 0.05], 'wood')
472
+ book = self.group('album_stand', [2.71, 4.46, 1.12])
473
+ self.transform(book, rpy=[60, 0, 0])
474
+ album = self.group('album_cover', [-0.23, 0, 0.035], parent=book)
475
+ self.box('album_cover_leaf', [0.23, 0, 0.01], [0.46, 0.42, 0.045], 'darkwood', album)
476
+ self.box('album_pages', [0, 0, 0], [0.45, 0.42, 0.035], 'paper', book)
477
+ self.box('album_spine', [-0.25, 0, 0], [0.04, 0.45, 0.06], 'red', book)
478
+ self.box('reading_stand_back', [2.71, 4.59, 1.11], [0.48, 0.06, 0.34], 'darkwood')
479
+ self.box('reading_stand_lip', [2.71, 4.33, 0.957], [0.5, 0.055, 0.04], 'brass')
480
+ placeholder = self.label_image('photo_placeholder', '', 600, 600)
481
+ photo1 = self.plane('photo1', [0, 0, 0.022], 0.41, 0.36, [1, 0, 0], [0, 1, 0], placeholder, book)
482
+ photo2 = self.framed('photo2', [0.105, 2.99, 1.55], 0.42, 0.63, [0, 1, 0], [0, 0, 1], placeholder)
483
+ dust = self.plane('photo_dust', [0.119, 2.99, 1.55], 0.375, 0.565, [0, 1, 0], [0, 0, 1], None, material=self.mats['dust'])
484
+ self.tube('wall_conduit', [0.2, 4.78, 2.42], [5.8, 4.78, 2.42], 0.018, 'steel')
485
+ for x in [1.9, 3.8]:
486
+ self.tube('conduit_drop', [x, 4.78, 2.42], [x, 4.78, 1.2], 0.018, 'steel')
487
+ self.box('side_shelf', [5.75, 3.75, 1.68], [0.4, 0.85, 0.045], 'wood')
488
+ for y in [3.5, 3.75, 4.0]:
489
+ self.cylinder('shelf_can', [5.72, y, 1.78], 0.08, 0.18, 'paint')
490
+ self.cylinder('shelf_can_lid', [5.72, y, 1.88], 0.085, 0.015, 'steel')
491
+ self.box('rug', [3.0, 2.2, 0.006], [2.0, 1.2, 0.012], 'cloth', bevel=0.002)
492
+ self.box('window_back', [0.085, 1.85, 2.06], [0.035, 1.18, 0.85], 'iron')
493
+ self.mat('window_glow', (0.13, 0.22, 0.28), rough=0.5, emission=(0.15, 0.27, 0.35))
494
+ self.box('window_glass', [0.11, 1.85, 2.06], [0.02, 1.08, 0.76], 'window_glow')
495
+ for y in [1.28, 1.85, 2.42]:
496
+ self.box('window_frame', [0.14, y, 2.06], [0.05, 0.05, 0.85], 'darkwood')
497
+ for z in [1.64, 2.48]:
498
+ self.box('window_frame', [0.14, 1.85, z], [0.05, 1.18, 0.05], 'darkwood')
499
+ for x, y in [(2.4, 2.7), (4.7, 4.0)]:
500
+ self.tube('light_cord', [x, y, 2.72], [x, y, 2.52], 0.009, 'iron')
501
+ self.cylinder('ceiling_shade', [x, y, 2.49], 0.23, 0.1, 'paint')
502
+ self.cylinder('ceiling_diffuser', [x, y, 2.43], 0.2, 0.015, 'lamp')
503
+ self.box('entry_light_frame', [3.0, 0.5, 2.58], [1.29, 0.39, 0.055], 'paint')
504
+ self.box('entry_light_diffuser', [3.0, 0.5, 2.555], [1.2, 0.3, 0.012], 'lamp')
505
+ tools = {key: self.tool(key) for key in ['hammer', 'screwdriver', 'brush', 'wrench', 'key']}
506
+ return dict(case=case, locker=locker, crate=crate, nails=nail, hatch=hatch, screw=screw, drawer=drawer, exit=door, album=album, photo1=photo1, photo2=photo2, dust=dust, tools=tools, slots=slots, slotnodes=slotnodes, glass=glass, status=lamp)
runtime/native_runtime/observation1280.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ WIDTH = 640
3
+ HEIGHT = 360
4
+ RENDER_WIDTH = 1280
5
+ RENDER_HEIGHT = 720
6
+ FX = FY = 320.0
7
+ CX = 320.0
8
+ CY = 180.0
9
+ PROFILE = 'new88_native_640x360_v1'
10
+ MODEL_TEMPLATE_ID = 'user_approved_exact_20261027'
11
+ PROMPT_PARENT_SHA256 = '019c4439ee80a1855fc8bfc53470be855a19d0278fd9a46a9028d141e39c6966'
12
+ MODEL_INSTRUCTIONS = 'You are a robot locked in a room. Your goal is to get out of the room.The door is locked. What opens it is not told in this message; you have to find out by searching the room.Papers and notes in the room may give you hints.Things can be hidden inside furniture that opens, and some things are locked themselves.To win, open the exit door.\nEach turn you see what you are holding, your own notes, your last 10 steps and, at the end, a photo of your current view.Each of the last steps is shown with the photo you were looking at when you chose it, the action you took and any available feedback(recalls are listed separately). Older steps are NOT shown; they are kept in your memory, which you can search with recall.\nChoose exactly one action:\n{"action": "walk", "distance": 0.25 | 0.5 | 1.0}\n{"action": "turn", "direction": "left" | "right" | "up" | "down", "degrees": 10-120}\n(left / right turn you in place; up / down tilt your head)\n{"action": "step_back", "distance": 0.1-0.6}\n{"action": "side_step", "direction": "left" | "right", "distance": 0.1-0.5}\n(step back or sideways while keeping your facing direction)\n{"action": "open", "point": [x, y], "target": "<what>", "part": <number>}\n{"action": "close", "point": [x, y], "target": "<what>", "part": <number>}\n{"action": "take", "point": [x, y], "target": "<what>"}\n{"action": "read", "point": [x, y], "target": "<what>"} the item in your hand needs no point\n{"action": "unlock", "point": [x, y], "target": "<what>", "part": <number>, "code": "<digits>"} a locked item in your hand needs no point\n{"action": "use", "point": [x, y], "target": "<what>"} uses/place the item in your hand on the thing you point at,or on another item in your hand (that one needs no point; "target" names it)\n(when you hold several items, add "item": "<a word for the one you mean>" to read / use)\n{"action": "press", "point": [x, y], "target": "<what>"}\n{"action": "recall", "query": "<words to search your memory for>"}\n(recall searches only the steps older than your last 10 steps, by the actions you took and what happened, and shows each step it finds with the photo you were looking at then.)\nRecall has a separate budget and does not use an action. Every recall attempt uses one recall, even if nothing is found. When Recalls left is 0, recall is unavailable.\nFor open / close / unlock on furniture, add "part": <number>: count drawers and doors column by column from the top left, starting at 1. Point at the whole piece of furniture. Room doors and items in your hand need no part.\n"point" says which thing you mean: the position of that thing in the photo of your current view, in pixels: x from 0 (left edge) to 640 (right edge) and y from 0 (top) to 360 (bottom). "target" is one or two words naming the whole thing you point at (cabinet, door, note, ...).\nYou can only act on things in your current view, and you must be close to them. \nWhen you look for something, scan by turning in one direction; do not spin or alternate left and right turns. If you could not move, do not repeat the same walk; turn or step back instead.\nDo not guess codes. Only enter a code that you have actually found written somewhere in the room;trying numbers one after another is not allowed.\nYou can add "note": "<one sentence>" to any action to write down what you think is important; your notes are shown to you every turn (at most 20 notes; "drop_notes": [<note numbers>] removes notes).\nEvery reply must include "thought": one short sentence on why you take this action.\nReply with exactly one JSON object:\n{"thought": "<why you take this action>", "action": "<one of the actions above>", ...its parameters...}\nYou have at most 80 actions.'
13
+
14
+ def rules_for_budget(limit=80):
15
+ return MODEL_INSTRUCTIONS.replace('You have at most 80 actions.', f'You have at most {int(limit)} actions.')
16
+
17
+ def validate_action(action, recalls_left=5):
18
+ from protocol import validate_action as legacy_validate
19
+ original = None
20
+ if isinstance(action, dict) and 'point' in action:
21
+ original = action['point']
22
+ if not isinstance(original, list) or len(original) != 2:
23
+ raise ValueError('point requires [x,y] in640x360 pixels')
24
+ if any((type(v) not in (int, float) or not math.isfinite(v) for v in original)):
25
+ raise ValueError('point must contain finite pixel coordinates')
26
+ if not (0 <= original[0] < WIDTH and 0 <= original[1] < HEIGHT):
27
+ raise ValueError('point out of range: 0<=x<640, 0<=y<360')
28
+ check = dict(action, point=[original[0] * 640 / WIDTH, original[1] * 360 / HEIGHT])
29
+ else:
30
+ check = action
31
+ clean = legacy_validate(check, recalls_left)
32
+ if original is not None:
33
+ clean['point'] = list(original)
34
+ return clean
35
+
36
+ def prepare_observation(rgb, depth):
37
+ import numpy as np
38
+ from PIL import Image
39
+ if rgb.shape[:2] != (RENDER_HEIGHT, RENDER_WIDTH) or depth.shape != (RENDER_HEIGHT, RENDER_WIDTH):
40
+ raise ValueError('Expected1280x720 native RGB/depth before640x360 model conversion')
41
+ rows = np.arange(HEIGHT) * RENDER_HEIGHT // HEIGHT
42
+ cols = np.arange(WIDTH) * RENDER_WIDTH // WIDTH
43
+ model_depth = np.asarray(depth, dtype=np.float32)[rows[:, None], cols[None, :]].copy()
44
+ return (Image.fromarray(rgb[:, :, :3]).copy(), model_depth)
runtime/native_runtime/observation_group.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import copy, math, types
3
+ import numpy as np
4
+ from scipy.spatial.transform import Rotation
5
+ from PIL import Image
6
+
7
+ def _array(value):
8
+ return value.detach().cpu().numpy() if hasattr(value, 'detach') else np.asarray(value)
9
+
10
+ def attach(driver, session):
11
+ if getattr(driver, '_common_photo_transport', None) is not None:
12
+ return
13
+ driver._common_photo_transport = session
14
+ if not hasattr(session, 'driver'):
15
+ session.driver = driver
16
+ session._feedback_photo_registry = {}
17
+ session._feedback_photo_serial = 0
18
+ original = driver.capture_feedback_frame
19
+
20
+ def capture(d):
21
+ original_path = str(original())
22
+ e = session.esc
23
+ C = session.C
24
+ clean = d.clean.copy()
25
+ depth = np.asarray(d.depth, np.float32).copy()
26
+ camera = getattr(d, 'camera', None)
27
+ if camera is not None:
28
+ eye, q = camera.get_position_orientation()
29
+ eye = _array(eye).astype(float)
30
+ q = _array(q).astype(float)
31
+ else:
32
+ eye = np.asarray(e.pos, float)
33
+ q = np.asarray(d.quat, float)
34
+ forward = -Rotation.from_quat(q).as_matrix()[:, 2]
35
+ yaw = math.atan2(forward[1], forward[0])
36
+ pitch = math.degrees(math.atan2(forward[2], math.hypot(forward[0], forward[1])))
37
+ shot = e.c['shot']
38
+ detect = e.c['detect']
39
+ old_pos = e.pos.copy()
40
+ old_z = e.cam_z
41
+ old_flush = getattr(e, '_flush_view', False)
42
+
43
+ def frozen_shot(path, pos, quat):
44
+ clean.save(path)
45
+
46
+ def frozen_detect(path, pos, quat):
47
+ dets, ignored = detect(path, pos, quat)
48
+ return (dets, np.repeat(np.repeat(depth, 2, 0), 2, 1))
49
+ e.c['shot'] = frozen_shot
50
+ e.c['detect'] = frozen_detect
51
+ e.pos = eye.copy()
52
+ e.cam_z = float(eye[2])
53
+ e._flush_view = False
54
+ session._feedback_photo_serial += 1
55
+ try:
56
+ boxed, _ = e.observe('native_feedback_%04d' % session._feedback_photo_serial, yaw, pitch)
57
+ finally:
58
+ e.c['shot'] = shot
59
+ e.c['detect'] = detect
60
+ e.pos = old_pos
61
+ e.cam_z = old_z
62
+ e._flush_view = old_flush
63
+ small = str(C._small(e, boxed))
64
+ with Image.open(small) as image:
65
+ if image.size != (640, 360) or not np.array_equal(np.asarray(image.convert('RGB')), np.asarray(d.small.convert('RGB'))):
66
+ raise RuntimeError('Feedback registration changed the actual delivered pixels')
67
+ registry = {'boxed': str(boxed), 'small': small, 'cam': copy.deepcopy(e._photo_cam[str(boxed)]), 'depth': copy.deepcopy(e._photo_depth[str(boxed)]), 'dets': copy.deepcopy(e._photo_dets[str(boxed)])}
68
+ session._feedback_photo_registry[small] = registry
69
+ d.current_visual_feedback[:] = [small if str(p) == original_path else str(p) for p in d.current_visual_feedback]
70
+ return small
71
+ driver.capture_feedback_frame = types.MethodType(capture, driver)
72
+
73
+ def begin(session):
74
+ session._feedback_photo_registry = {}
75
+
76
+ def finalize(session, images):
77
+ e = session.esc
78
+ C = session.C
79
+ registry = getattr(session, '_feedback_photo_registry', {})
80
+ photos = []
81
+ metadata = []
82
+ for item in images:
83
+ small = str(item)
84
+ record = registry.get(small)
85
+ if record is None:
86
+ p = Path(small)
87
+ if p.stem.endswith('_small'):
88
+ boxed = p.with_name(p.stem[:-6] + '.png')
89
+ else:
90
+ boxed = p
91
+ key = str(boxed)
92
+ registered = key in getattr(e, '_photo_dets', {}) and key in getattr(e, '_photo_cam', {}) and (key in getattr(e, '_photo_depth', {}))
93
+ if not registered:
94
+ expected = session.driver.run / ('000_model.png' if session.driver.step == 0 else 'steps/%03d_model.png' % session.driver.step)
95
+ if Path(small).resolve() != expected.resolve():
96
+ raise RuntimeError('Unregistered image is not this step ordinary observation: ' + small)
97
+ with Image.open(small) as im:
98
+ pixel = np.asarray(im.convert('RGB'))
99
+ matches = []
100
+ for candidate in list(getattr(e, '_claw_photos', []) or []):
101
+ if candidate not in getattr(e, '_photo_depth', {}):
102
+ continue
103
+ current = C._small(e, candidate)
104
+ with Image.open(current) as im:
105
+ if np.array_equal(pixel, np.asarray(im.convert('RGB'))):
106
+ matches.append(str(candidate))
107
+ if not matches:
108
+ raise RuntimeError('Current ordinary frame differs from actual registered observation')
109
+ key = matches[-1]
110
+ elif str(C._small(e, key)) != small:
111
+ raise RuntimeError('Delivered image is not the canonical small photo')
112
+ record = {'boxed': key, 'small': small, 'cam': copy.deepcopy(e._photo_cam[key]), 'depth': copy.deepcopy(e._photo_depth[key]), 'dets': copy.deepcopy(e._photo_dets[key])}
113
+ with Image.open(small) as im:
114
+ if im.size != (640, 360):
115
+ raise RuntimeError('Delivered group contains a non640x360 photo')
116
+ photos.append(record['boxed'])
117
+ metadata.append(record)
118
+ if not photos:
119
+ raise RuntimeError('Current observation group is empty')
120
+ e._claw_photos = list(photos)
121
+ e._photo_cam = {r['boxed']: r['cam'] for r in metadata}
122
+ e._photo_depth = {r['boxed']: r['depth'] for r in metadata}
123
+ e._photo_dets = {r['boxed']: r['dets'] for r in metadata}
124
+ session._current_observation_group = {'images': [str(x) for x in images], 'photos': list(photos), 'metadata': metadata}
125
+ session.driver.save('CURRENT_OBSERVATION_GROUP.json', {'images': [str(x) for x in images], 'photos': list(photos), 'photo_count': len(photos), 'native_metadata_complete': True, 'history_or_third_person_admitted': False, 'model_calls': 0})
126
+ return list(photos)
127
+
128
+ def checkpoint(session):
129
+ if getattr(session, '_current_observation_group', None) is None:
130
+ images = list(getattr(session.driver, 'current_observation_images', []) or [])
131
+ if images:
132
+ finalize(session, images)
133
+ return copy.deepcopy(getattr(session, '_current_observation_group', None))
134
+
135
+ def restore(session, value):
136
+ if value is None:
137
+ return
138
+ e = session.esc
139
+ for path in value['images']:
140
+ if not Path(path).is_file():
141
+ raise RuntimeError('Checkpoint observation image missing: ' + path)
142
+ metadata = value['metadata']
143
+ e._claw_photos = list(value['photos'])
144
+ e._photo_cam = {r['boxed']: r['cam'] for r in metadata}
145
+ e._photo_depth = {r['boxed']: r['depth'] for r in metadata}
146
+ e._photo_dets = {r['boxed']: r['dets'] for r in metadata}
147
+ session._current_observation_group = copy.deepcopy(value)