#!/usr/bin/env python3 """Prepare and optionally build a fresh v25 native residential shell in v26. This deliberately stops before furniture selection, joint layout and robot work. The source generator owns topology and Blender owns the saved structural mesh. """ from __future__ import annotations import rhg_paths import argparse import copy import hashlib import importlib import json import os from pathlib import Path import signal import subprocess import sys import time from scene_input import select_rplan DEFAULT_ENGINE = Path(__file__).resolve().parent / 'engine' DEFAULT_BLENDER = Path(os.environ.get('RHG_BLENDER', 'blender')) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def save(path, value): Path(path).write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + '\n', encoding='utf-8') def validate_plan(plan): rooms = plan['rooms'] ids = [r['room_id'] for r in rooms] if len(set(ids)) != len(ids): raise ValueError('Duplicate room identifiers') beds = [r for r in rooms if 'bedroom' in r['room_type']] if not beds: raise ValueError('Selected floorplan has no bedroom') if not any(r['room_id'] == 'living' or r['room_type'] == 'living_room' for r in rooms): raise ValueError('Selected floorplan has no living room') overlap_warnings = [] for i, room in enumerate(rooms): x0, y0, x1, y1 = room['bounds_m'] if x1 <= x0 or y1 <= y0: raise ValueError('Nonpositive room area: ' + room['room_id']) for other in rooms[i + 1:]: a, b, c, d = other['bounds_m'] overlap_x = min(x1, c) - max(x0, a) overlap_y = min(y1, d) - max(y0, b) if overlap_x > 0.10 and overlap_y > 0.10: raise ValueError('Room interiors overlap') if overlap_x > 0 and overlap_y > 0: overlap_warnings.append({ 'room_ids': [room['room_id'], other['room_id']], 'overlap_xy_m': [round(overlap_x, 3), round(overlap_y, 3)], 'accepted_axis_tolerance_m': 0.10, }) if overlap_warnings: plan['room_bbox_overlap_warnings'] = overlap_warnings return [r['room_id'] for r in beds] def validate_connectivity(plan, contract): rooms = {r['room_id'] for r in plan['rooms']} graph = {rid: set() for rid in rooms} narrow_portals = [] for portal in contract['portals']: owners = portal['room_ids'] if len(owners) == 2: a, b = owners if portal['clear_width_m'] <= 0: raise ValueError('Native internal portal has no usable width') if portal['clear_width_m'] < 1.0 - 1.e-6: narrow_portals.append(portal['portal_id']) graph[a].add(b) graph[b].add(a) living = next((r['room_id'] for r in plan['rooms'] if r['room_id'] == 'living' or r['room_type'] == 'living_room'), None) if living is None: raise ValueError('Selected floorplan has no living room') reached, pending = set(), [living] while pending: rid = pending.pop() if rid not in reached: reached.add(rid) pending.extend(graph[rid] - reached) if reached != rooms: raise ValueError('Disconnected native rooms: ' + ','.join(sorted(rooms - reached))) return dict(connected_room_ids=sorted(reached), adjacency={k: sorted(v) for k, v in graph.items()}, narrow_portal_ids=sorted(narrow_portals), scope='authored_portal_graph_not_robot_navigation_or_saved_mesh') def run_logged(command, log_path, environment, timeout_s): started = time.monotonic() with Path(log_path).open('w', encoding='utf-8') as log: log.write(json.dumps(command, ensure_ascii=False) + '\n') log.flush() process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=environment, start_new_session=True) timed_out = False try: code = process.wait(timeout=timeout_s) except subprocess.TimeoutExpired: timed_out = True os.killpg(process.pid, signal.SIGTERM) try: code = process.wait(timeout=10) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) code = process.wait() return dict(command=command, returncode=code, timed_out=timed_out, elapsed_s=round(time.monotonic() - started, 3), log=str(log_path), passed=code == 0 and not timed_out) def prepare(args): engine = args.engine.resolve() if engine != DEFAULT_ENGINE.resolve(): raise ValueError('Use the engine belonging to this separate adapter workspace') case = (args.case or engine / 'runs/threebed_cup_01').resolve() if engine not in case.parents: raise ValueError('Case must be inside this adapter engine') case.mkdir(parents=True, exist_ok=True) layout = case / 'layout' scene = layout / 'fullhome_asset_v16_000' result_path = case / 'native_shell_result.json' result = dict(schema='rhg.v26.native-shell-result.v1', passed=False, status='preparing', scene=str(scene), furniture_executed=False, physics_executed=False, robot_task_executed=False, whole_task_acceptance=False) try: helpers = engine / 'source/scripts/internal/scene_generation' source_environment = dict(os.environ) input_text = (args.prompt_file.read_text(encoding='utf-8') if args.prompt_file else args.description or '') image_report = None if args.floorplan_image: from floorplan_image import ( FloorplanScaleConfirmationRequired, extract_floorplan_from_jpg, resolve_native_window_candidates, ) model_path = args.vlm_model or source_environment.get('RHG_FLOORPLAN_VLM_MODEL') if not model_path: raise ValueError( 'JPG/PNG parsing requires a local Qwen3-VL model; set ' 'RHG_FLOORPLAN_VLM_MODEL or pass --vlm-model' ) try: plan, image_report = extract_floorplan_from_jpg( args.floorplan_image, model_path=model_path, scale_m_per_pixel=args.floorplan_scale_m_per_pixel, gpu=args.gpu, artifact_dir=case) except FloorplanScaleConfirmationRequired as error: save(case / 'floorplan_draft.json', error.draft) raise from scene_input import parse_text_requirements, plan_matches_requirements requirements = parse_text_requirements(input_text) if not plan_matches_requirements(plan, requirements): raise ValueError( 'The parsed image floorplan does not satisfy the explicit room ' 'requirements in the description.' ) selection = { 'schema': 'robohousegen.input_selection.v1', 'input_kind': 'png' if args.floorplan_image.suffix.casefold() == '.png' else 'jpg', 'seed': args.seed, 'selected_plan_id': plan.get('plan_id'), 'requirements': requirements, 'floorplan_image_report': image_report, } else: corpus_path = Path(source_environment.get( 'RHG_RPLAN_SEEDS', str(engine / 'source/configs/floorplans/rplan_production_16.json'))) plan, selection = select_rplan(corpus_path, input_text, seed=args.seed) # Failed image parsing must not leave an empty scene that blocks retry. scene.mkdir(parents=True, exist_ok=False) plan = copy.deepcopy(plan) bedrooms = validate_plan(plan) text = input_text or ( '根据参考户型图生成住宅场景。' if args.floorplan_image else '从 RPLAN 随机选择户型并生成住宅场景。') configured_rootfs = args.rootfs or ( Path(source_environment['RHG_ROOTFS']) if source_environment.get('RHG_ROOTFS') else None) rootfs = configured_rootfs.resolve() if configured_rootfs else None library = source_environment.get('RHG_LIBRARY_ROOT') or ( str(rootfs / 'assets/library') if rootfs else '') environment = dict(source_environment) for key in list(environment): if key not in rhg_paths.ENVIRONMENT_KEYS and key not in ('RHG_DIGEST_CACHE', 'RHG_ROOM_SEARCH_BUDGETS', 'RHG_FLOOR_COVER_COLLISION_OMISSION', 'RHG_RECOVERY_MAX_ATTEMPTS', 'RHG_PENETRATION_TOLERANCE_M', 'RHG_COMPACT_KITCHEN') and key.startswith(('RHG_', 'OPENAI_', 'ASTRA_')): environment.pop(key) environment.update( PYTHONDONTWRITEBYTECODE='1', CUDA_VISIBLE_DEVICES='', OMP_NUM_THREADS='4', RHG_OUT_ROOT=str(case / 'bootstrap'), RHG_RUNTIME_ROOT=str(case / 'runtime'), RHG_LIBRARY_ROOT=str(library), RHG_ASSET_LIBRARY_ROOT=str(library), RHG_RPLAN_SEEDS=source_environment.get( 'RHG_RPLAN_SEEDS', str(engine / 'source/configs/floorplans/rplan_production_16.json')), RHG_BASE_SCRIPT=str(helpers / 'base/rhg_fullhome_test_generate_v2.py'), RHG_BASE_BLENDER_SCRIPT=str(helpers / 'base/rhg_fullhome_test_blender_v2.py'), RHG_USE_ASTRA_TASK_PLAN='0', RHG_USE_ASTRA_LAYOUT_BRIEF='0', RHG_ENABLE_VLM_REVIEW='0', RHG_REQUIRE_VLM_REVIEW='0', RHG_BUILD_LAYOUT_SHELL='1', RHG_SKIP_RENDER='1', RHG_ASSET_SELECTION_POLICY='content_diverse_v1', RHG_DOOR_WIDTH_M='1.0', RHG_DOOR_HEIGHT_M='2.4', RHG_WALL_HEIGHT_M='3.0', RHG_TEST_SEED=str(args.seed), RHG_TEST_SCENE_COUNT='1') for key, folder in dict(TMPDIR='tmp', XDG_CACHE_HOME='cache', BLENDER_USER_CONFIG='blender/config', BLENDER_USER_SCRIPTS='blender/scripts', BLENDER_USER_DATAFILES='blender/datafiles').items(): directory = case / 'shell_runtime' / folder directory.mkdir(parents=True, exist_ok=True) environment[key] = str(directory) environment['PYTHONPATH'] = os.pathsep.join( [str(helpers), str(engine / 'source'), str(engine / 'supervisor_site'), str(engine / 'runtime_site')]) os.environ.clear() os.environ.update(environment) sys.path[:0] = [str(helpers), str(engine / 'source'), str(engine / 'supervisor_site')] native = importlib.import_module('rhg_task_contract_generate_v16_1p_procedural_pure') # Avoid the legacy normalizer: preserve approved room names and bounds. image_window_candidates = copy.deepcopy(plan.get('window_input_candidates', [])) authored_openings = {k:copy.deepcopy(plan.get(k,[])) for k in ('doors','windows')} preserve_input_openings = image_report is not None or any(plan.get(k) for k in ('doors','windows','window_input_candidates')) plan = native.add_plan_topology(plan, include_windows=True) residential_profile = getattr(args,'residential_profile',None) if residential_profile: from residential_profile import load_profile config = load_profile(residential_profile).get('group_layout') or {} adaptive = config.get('enabled',True) and config.get('adaptive_relations',False) if adaptive and not preserve_input_openings: from adaptive_shell import adapt_generated_shell plan = adapt_generated_shell(plan) if image_report is not None: image_report['window_candidate_resolution'] = resolve_native_window_candidates( image_window_candidates, plan.get('windows', [])) plan = native.apply_scene_envelope_contract_v16_21p(plan) native_plan = plan # restore_authored_openings returns an independent copy. authored_doors_rejected = None if any(authored_openings.values()): # Reapply AFTER native defaults, which normalize all verticals. from adaptive_shell import restore_authored_openings plan = restore_authored_openings(plan, authored_openings) from engine.source.scripts.internal.scene_generation import window_rules window_rules.annotate_plan(plan) from adaptive_shell import ensure_door_jambs plan = ensure_door_jambs(plan) metric = native.build_metric_layout_contract_v14(plan) try: connectivity = validate_connectivity(plan, metric) except ValueError as error: if not any(d.get('source') == 'rplan_png_interior_door' for d in authored_openings['doors']): raise # Reject the entire real-door batch. Other authored openings retain # their established behavior, including entry doors and windows. authored_doors_rejected = str(error) plan = native_plan remaining = dict(authored_openings, doors=[d for d in authored_openings['doors'] if d.get('source') != 'rplan_png_interior_door']) if any(remaining.values()): plan = restore_authored_openings(plan, remaining) window_rules.annotate_plan(plan) plan = ensure_door_jambs(plan) metric = native.build_metric_layout_contract_v14(plan) connectivity = validate_connectivity(plan, metric) task = dict(task_kind='scene_generation', natural_language_task=text, goal='Build a new RPLAN structural shell for subsequent furnishing.', actions=[], success_conditions=[], physical_execution='not_requested_not_run', scope='structural_shell_only', robot_task_status='pending_parent_task_adapter') composition = dict(schema='robohousegen.task_contract_scene.v16', scene_id=scene.name, seed=args.seed, chain_version=native.CHAIN_VERSION, natural_language_task=text, source='v26.rplan.native_shell_adapter', floor_plan=plan, metric_layout_contract=metric, entities=[], furniture_layout_slots=[], task_contract_v16=dict(schema='rhg.explicit_scene_task.v1', TaskSpec=task, SpatialPlan=plan, AssetRequirements=[]), room_completeness=None, layout_validation=None, structured_contract_validation_v16=None) scene_manifest = native.build_scene_manifest_v16(composition) episode = dict(schema='robohousegen.BenchmarkEpisode.v16', scene_id=scene.name, episode_id=scene.name + '__structural_shell', task_spec=task, bindings={}, route_room_sequence=[], success_conditions=[], physical_execution='not_run') save(case / 'scene_input.json', dict( description=input_text, selection=selection, source=(selection['input_kind'] if args.floorplan_image else 'text' if input_text.strip() else 'random'), floorplan_image=str(Path(args.floorplan_image).resolve()) if args.floorplan_image else None)) for name, value in [('composition_manifest.runtime.json', composition), ('SceneManifest.v16.json', scene_manifest), ('BenchmarkEpisode.v16.json', episode), ('task_contract_v16.json', composition['task_contract_v16'])]: save(scene / name, value) provenance = dict(schema='rhg.v26.native-shell-preparation.v1', plan_selection=selection, adapter_sha256=digest(__file__), bedroom_ids=bedrooms, connectivity=connectivity, source_sha256={str(p): digest(p) for p in [Path(native.__file__), helpers / 'build_native_shell_blender_v16_1g.py']}, original_scene_reused=False, original_floorplan_reused=False, layout_inputs={str(p): digest(p) for p in scene.glob('*.json')}) if authored_doors_rejected is not None: provenance['authored_doors_rejected'] = authored_doors_rejected save(case / 'native_shell_preparation.json', provenance) result.update(status='prepared', prepared=True, bedroom_ids=bedrooms, baseline_root=str(layout), connectivity=connectivity) save(result_path, result) if not args.execute: return result command = [str(args.blender), '--background', '--threads', '4', '--python-exit-code', '1', '--python', str(helpers / 'build_native_shell_blender_v16_1g.py'), '--', str(layout)] result['build'] = run_logged(command, case / 'native_shell_build.log', environment, args.timeout_s) save(result_path, result) if not result['build']['passed']: raise RuntimeError('Native shell build failed; see native_shell_build.log') report = json.loads((scene / 'blender_report.json').read_text()) blend = scene / (scene.name + '.blend') if (report.get('passed') is not True or report.get('baseline_mode') != 'layout_shell_v1' or report.get('room_count') != len(plan['rooms']) or report.get('imported_count') != 0 or not blend.is_file()): raise ValueError('Native shell report or saved blend is incomplete') # Reopen the actual saved blend in a separate native process. readback_path = case / 'native_shell_readback.json' code = '''import bpy,json,sys from pathlib import Path sys.path.insert(0,HELPERS) from floor_slab import audit_floor_slab scene=Path(SCENE) manifest=json.loads((scene/'composition_manifest.runtime.json').read_text()) bpy.ops.wm.open_mainfile(filepath=str(scene/(scene.name+'.blend'))) floor_audit=audit_floor_slab(bpy,manifest['floor_plan']) if bpy.context.scene.get('rhg_baseline_mode')!='layout_shell_v1': raise ValueError('Saved shell marker differs') if any(o.get('entity_id') for o in bpy.context.scene.objects): raise ValueError('Unexpected furniture in shell') measurements=[dict(room_id=room,top_face_area_m2=area) for room,area in floor_audit['room_top_face_area_m2'].items()] Path(OUTPUT).write_text(json.dumps(dict(passed=True,room_count=len(measurements),room_floor_measurements=measurements, floor_slab_audit=floor_audit,scope='saved_empty_shell_floor_readback_not_full_collision_or_robot_acceptance'),indent=2)+'\\n') ''' code = 'SCENE=' + repr(str(scene)) + '\nOUTPUT=' + repr(str(readback_path)) + '\nHELPERS=' + repr(str(helpers)) + '\n' + code result['readback'] = run_logged([str(args.blender), '--background', '--threads', '4', '--python-exit-code', '1', '--python-expr', code], case / 'native_shell_readback.log', environment, args.timeout_s) if not result['readback']['passed'] or not readback_path.is_file(): raise RuntimeError('Saved native shell readback failed; see native_shell_readback.log') result.update(passed=True, status='native_shell_saved_and_reopened', blend=str(blend), blend_sha256=digest(blend), blender_report_sha256=digest(scene / 'blender_report.json'), readback_path=str(readback_path), geometry_qualified=False, runtime_recommendation=dict(baseline_root=str(layout), scene_count=1, render_profile='none', candidate_selection_policy='declared', joint_request='PARENT_TO_SUPPLY_COMPLETE_THREE_BEDROOM_REQUEST')) except Exception as error: result.update(passed=False, status='failed', error=type(error).__name__ + ': ' + str(error)) if isinstance(getattr(error, 'diagnostic', None), dict): result['diagnostic'] = copy.deepcopy(error.diagnostic) save(result_path, result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--engine', type=Path, default=DEFAULT_ENGINE) parser.add_argument('--case', type=Path) parser.add_argument('--rootfs', type=Path) parser.add_argument('--blender', type=Path, default=DEFAULT_BLENDER) parser.add_argument('--prompt-file', type=Path) parser.add_argument('--description', help='Optional natural-language room/task requirements used to filter RPLAN') parser.add_argument('--residential-profile', choices=['balanced_visual_v1'], help='Apply adaptive preferences only to newly generated openings') parser.add_argument('--floorplan-image', type=Path, help='JPG/JPEG/PNG reference plan parsed locally with Qwen3-VL and OpenCV') parser.add_argument('--floorplan-scale-m-per-pixel', type=float, help='User scale override; otherwise use consistent printed dimensions/areas') parser.add_argument('--vlm-model', type=Path, help='Local Qwen3-VL model folder; defaults to RHG_FLOORPLAN_VLM_MODEL') parser.add_argument('--gpu', default='0', help='CUDA device index for local Qwen3-VL inference') parser.add_argument('--seed', type=int, default=2026102801) parser.add_argument('--timeout-s', type=float, default=240) parser.add_argument('--execute', action='store_true') args = parser.parse_args() if args.prompt_file and args.description is not None: parser.error('Use either --prompt-file or --description, not both') if args.floorplan_scale_m_per_pixel is not None and not args.floorplan_image: parser.error('--floorplan-scale-m-per-pixel requires --floorplan-image') result = prepare(args) print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if result.get('passed') or result.get('status') == 'prepared' else 1 if __name__ == '__main__': raise SystemExit(main())