RoboHome / code /robohome /src /bathroom_mode_revision.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
19.1 kB
"""Measured bathroom mode advice plus a scoped north-entry scene revision.
select_mode is a bounded planning preference, not a universal partition solver.
apply supports this reviewed rectangular north-entry bathroom with west basin
and east toilet/shower. It preserves native furniture dimensions and materials.
"""
import rhg_paths
import copy
import hashlib
import json
import math
from collections import deque
from pathlib import Path
import sys
def select_mode(net_width, net_depth, entry_width, fixture_dimensions, preferred='auto'):
"""Choose compact centralized or entry-dry separated mode, without retries.
Dimensions are native [width, depth, height]. This proposal assumes the
basin uses one side wall and toilet/shower share the opposite wet wall.
Existing obstacle geometry and door motion still need scene-level checks.
"""
if preferred not in {'auto','centralized','separated'}:raise ValueError('Unknown bathroom mode preference')
if any(not math.isfinite(v) or v<=0 for v in (net_width,net_depth,entry_width)):
raise ValueError('Bathroom dimensions must be positive finite metres')
out=dict(schema='rhg.bathroom-mode-selector.v1',mode='centralized',fallback=False,rescaled_assets=False,
candidates_evaluated=0,scope='rectangular single-entry side-wall fixture arrangement feasibility only',
centralized_layout_validated=False,physical_qualification_claimed=False,reasons=[])
if preferred=='centralized':return dict(out,reasons=['explicit_centralized_preference'])
if not all(k in fixture_dimensions for k in ('sink','toilet','shower')):
return dict(out,fallback=True,reasons=['missing_native_fixture_dimensions'])
s,t,h=[fixture_dimensions[k] for k in ('sink','toilet','shower')]
if any(len(d)!=3 or any(not math.isfinite(v) or v<=0 for v in d) for d in (s,t,h)):
raise ValueError('Native fixture dimensions must be three positive finite values')
required_width=max(s[1]+.60,t[1]+.60,h[1]+.60)
wet_depth=h[0]+t[0]+.40+.20
# A finite set of modest dry zones. No source geometry is scaled and no
# stricter rejection of the centralized generator occurs on failure.
for dry in sorted(set(round(max(v,s[0]+.23),4) for v in (.80,.90,1.00))):
out['candidates_evaluated']+=1
if net_width>=required_width and net_depth>=dry+.08+wet_depth and entry_width>=.70:
return dict(out,mode='separated',dry_zone_depth_m=dry,wet_zone_min_depth_m=wet_depth,
required_net_width_m=required_width,reasons=['native_fixtures_and_entry_fit_separated_candidate'])
return dict(out,fallback=True,reasons=['separated_geometry_insufficient_use_centralized_layout'],
required_net_width_m=required_width,wet_zone_min_depth_m=wet_depth)
def _route(inner, boxes, start, goal, radius=.30, step=.025):
"""Finite four-neighbor clearance search; boxes include the opened door."""
x0,y0,x1,y1=inner;nx=int((x1-x0-2*radius)/step)+1;ny=int((y1-y0-2*radius)/step)+1
def point(n):return [x0+radius+n[0]*step,y0+radius+n[1]*step]
def valid(n):
if not (0<=n[0]<nx and 0<=n[1]<ny):return False
x,y=point(n)
return not any(b[0]-radius+1e-8<x<b[2]+radius-1e-8 and b[1]-radius+1e-8<y<b[3]+radius-1e-8 for b in boxes)
def nearest(p):
options=[(i,j) for i in range(nx) for j in range(ny) if valid((i,j))]
n=min(options,key=lambda n:math.dist(point(n),p)) if options else None
return n if n is not None and math.dist(point(n),p)<=step*1.5 else None
a,b=nearest(start),nearest(goal)
if a is None or b is None:return dict(passed=False,clearance_diameter_m=2*radius,nodes=0)
q=deque([a]);previous={a:None}
while q:
n=q.popleft()
if n==b:break
for d in ((1,0),(-1,0),(0,1),(0,-1)):
v=(n[0]+d[0],n[1]+d[1])
if v not in previous and valid(v):previous[v]=n;q.append(v)
path=[];n=b
if b in previous:
while n is not None:path.append(point(n));n=previous[n]
path.reverse()
return dict(passed=bool(path),clearance_diameter_m=2*radius,grid_step_m=step,nodes=len(previous),path_xy_m=path,
scope='conservative axis-aligned fixture/partition/door boxes at saved open pose')
def plan_revision(manifest):
fp=manifest['floor_plan'];room=next(r for r in fp['rooms'] if r['room_id']=='bath')
if room['bounds_m']!=[5.93,3.66,7.93,7.06]:raise ValueError('Scene revision supports the reviewed north-entry bathroom only')
rows={e['entity_id']:e for e in manifest['entities'] if e.get('room_id')=='bath'}
sink,toilet,shower=[rows[k] for k in ('bathroom_sink','toilet','shower')]
advice=select_mode(1.79,3.19,1.,{k:e['dimensions_m'] for k,e in [('sink',sink),('toilet',toilet),('shower',shower)]},preferred='separated')
if advice['mode']!='separated':return dict(mode='centralized',selector=advice,changed=False)
inner=[6.035,3.765,7.825,6.955];partition=6.08
low,high=copy.deepcopy(sink['world_bbox_m']);dy=6.88-high[1];low[1]+=dy;high[1]+=dy
if low[1]<partition+.04+.10:raise ValueError('Native basin does not fit the proposed dry area')
sinkbb=[low,high];door=[6.30,7.20];hinge=[6.33,partition];leaf=.84;thickness=.036
checks=[]
for e in (toilet,shower):
a,b=e['world_bbox_m'];dx=max(a[0]-hinge[0],0,hinge[0]-b[0]);dy0=max(a[1]-hinge[1],0,hinge[1]-b[1])
distance=math.hypot(dx,dy0)
checks.append(dict(entity_id=e['entity_id'],minimum_hinge_to_fixture_m=distance,swept_radius_m=leaf+thickness/2,passed=distance>leaf+thickness/2+.01))
checks.append(dict(entity_id='bathroom_sink',dry_side_gap_m=low[1]-(partition+thickness/2),passed=low[1]>partition+thickness/2+.01))
boxes=[[low[0],low[1],high[0],high[1]]]+[[e['world_bbox_m'][0][0],e['world_bbox_m'][0][1],e['world_bbox_m'][1][0],e['world_bbox_m'][1][1]] for e in (toilet,shower)]
boxes.extend([[6.035,partition-.04,6.325,partition+.04],[7.175,partition-.04,7.825,partition+.04],[hinge[0]-.018,partition-leaf,hinge[0]+.018,partition]])
route=_route([6.035,3.765,7.825,7.50],boxes,[6.93,7.18],[6.55,4.55])
if not route['passed'] or not all(c['passed'] for c in checks):
return dict(mode='centralized',selector=advice,changed=False,reason='actual_partition_route_or_swing_failed_soft_fallback',route=route,door_sweep_checks=checks)
return dict(schema='rhg.bathroom-mode-revision.v1',mode='separated',selector=advice,room_id='bath',
partition_y_m=partition,partition_thickness_m=.08,dry_bounds_m=[6.035,partition+.04,7.825,7.06],
wet_bounds_m=[6.035,3.765,7.825,partition-.04],door_interval_m=door,door_clear_width_m=.85,
hinge_xy_m=hinge,leaf_width_m=leaf,leaf_thickness_m=thickness,door_height_m=2.1,door_open_angle_deg=-90.,
sink_translation_m=[0.,dy,0.],sink_world_bbox_m=sinkbb,mirror_base_z_m=max(1.15,high[2]+.11),
moved_entity_ids=['bathroom_sink'],route=route,door_sweep_checks=checks,physical_qualification_claimed=False,
scope='current north-entry bathroom only; selector proposes modes for rectangular single-entry rooms, without automatic structural assembly elsewhere')
OLD_DOOR='door__hallway__bath'
INNER_DOOR='bath__dry_wet_glass_door'
NORTH_PIERS=('wall__interior__hallway__bath__west','wall__interior__hallway__bath__east')
def update_plan(manifest, revision):
fp=manifest['floor_plan'];fp['doors']=[d for d in fp.get('doors',[]) if d.get('door_id')!=OLD_DOOR]
a=next(a for a in fp['topology_adjacencies'] if set(a['room_ids'])=={'hallway','bath'})
for k in ('door_id','door_interval_m','door_width_m','door_height_m'):a.pop(k,None)
a.update(open_connection=True,open_interval_m=[6.03,7.83],clear_width_m=1.80,
opening_height_m=3.,head_height_m=3.,sill_height_m=0.,connection_kind='open_entry_to_bathroom_dry_zone')
zones=[dict(zone_id='bath__entry_dry',parent_room_id='bath',kind='dry_handwashing',bounds_m=revision['dry_bounds_m'],entity_ids=['bathroom_sink','bathroom_mirror']),
dict(zone_id='bath__inner_wet',parent_room_id='bath',kind='toilet_and_shower',bounds_m=revision['wet_bounds_m'],entity_ids=['toilet','shower'])]
door=dict(door_id=INNER_DOOR,parent_room_id='bath',wall_orientation='H',wall_line_m=revision['partition_y_m'],
door_interval_m=revision['door_interval_m'],clear_width_m=revision['door_clear_width_m'],opening_height_m=2.1,
head_height_m=2.1,sill_height_m=0.,motion_type='hinged',hinge_xy_m=revision['hinge_xy_m'],
open_angle_deg=-90.,swing_zone_id='bath__inner_wet',independent_geometry_validation=True,
wholehouse_door_contract_qualification=False)
fp.setdefault('interior_partitions',[]).append(dict(partition_id='bath__dry_wet_partition',parent_room_id='bath',
wall_orientation='H',wall_line_m=revision['partition_y_m'],span_m=[6.035,7.825],thickness_m=.08,height_m=3.,door=door))
room=next(r for r in fp['rooms'] if r['room_id']=='bath');room['bathroom_mode']='separated';room['functional_zones']=zones
manifest['bathroom_mode_revision']=copy.deepcopy(revision);manifest['bathroom_mode_revision']['zones']=zones
manifest['bathroom_mode_revision']['interior_door']=door
def apply(bpy, manifest, tree):
if manifest.get('bathroom_mode_revision',{}).get('mode')=='separated':
return dict(changed=False,mode='separated',schema='rhg.bathroom-mode-revision.v1')
r=plan_revision(manifest)
if r['mode']!='separated':return dict(r,changed=False,moved_existing_entities=[],removed_objects=[],created_objects=[])
from mathutils import Matrix,Vector
tree=Path(tree);code=tree/'engine/source/scripts/internal/scene_generation/real_assets'
sys.path[:0]=[str(tree),str(code),str(code.parent),str(code.parent/'base'),str(tree/'engine')]
from asset_import import load_module,mesh_bounds
source=rhg_paths.resolve(json.loads((Path(__file__).parent/'bathroom_mirror_asset.json').read_text()))
for key,sha in [('canonical_path','asset_sha256'),('runtime_path','runtime_sha256')]:
if hashlib.sha256(Path(source[key]).read_bytes()).hexdigest()!=source[sha]:raise ValueError('Mirror source bytes changed')
oldwalls=[bpy.data.objects.get(n) for n in NORTH_PIERS]
if any(o is None for o in oldwalls):raise ValueError('Expected bathroom entrance piers missing')
walls=[o for o in bpy.context.scene.objects if o.type=='MESH' and o.name.startswith('wall__')]
material=oldwalls[0].data.materials[0];collection=oldwalls[0].users_collection[0]
sink=next(e for e in manifest['entities'] if e['entity_id']=='bathroom_sink')
sink_objects=[o for o in bpy.context.scene.objects if o.get('entity_id')=='bathroom_sink']
if not sink_objects or any(o.parent for o in sink_objects):raise ValueError('Unexpected basin geometry/hierarchy')
removed=[o.name for o in bpy.context.scene.objects if o.name in NORTH_PIERS or OLD_DOOR in o.name or o.get('portal_id')==OLD_DOOR]
# All source doorway parts belong to this portal; adjacent hallway walls stay.
for name in removed:
o=bpy.data.objects.get(name)
if o:bpy.data.objects.remove(o,do_unlink=True)
created=[]
def new_material(name,color,metallic=0.,rough=.3,transmission=0.):
m=bpy.data.materials.get(name) or bpy.data.materials.new(name);m.use_nodes=True
bs=m.node_tree.nodes.get('Principled BSDF');bs.inputs['Base Color'].default_value=(*color,1.)
bs.inputs['Metallic'].default_value=metallic;bs.inputs['Roughness'].default_value=rough
bs.inputs['Transmission Weight'].default_value=transmission;bs.inputs['IOR'].default_value=1.45
return m
aluminum=new_material('RHG_Bathroom_Brushed_Aluminum',(.32,.36,.38),.7,.25)
glass=new_material('RHG_Bathroom_Frosted_Glass',(.94,.98,.98),0.,.28,1.)
mirror_material=new_material('RHG_Bathroom_Native_Mirror_Front',(.94,.94,.94),1.,.025)
def box(name,lo,hi,mat,kind='wall',parent=None):
x0,y0,z0=lo;x1,y1,z1=hi
mesh=bpy.data.meshes.new(name+'__mesh');mesh.from_pydata([(x0,y0,z0),(x1,y0,z0),(x1,y1,z0),(x0,y1,z0),(x0,y0,z1),(x1,y0,z1),(x1,y1,z1),(x0,y1,z1)],[],[(0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7)]);mesh.update()
o=bpy.data.objects.new(name,mesh);collection.objects.link(o);mesh.materials.append(mat)
o['structural_object_id']=name;o['revision']='bathroom_mode_revision_20261113';o['component_kind']=kind
if kind=='wall':o['wall_orient']='H'
else:o['portal_id']=INNER_DOOR;o['door_motion_type']='hinged'
if parent:
bpy.context.view_layer.update();matrix=o.matrix_world.copy();o.parent=parent;o.matrix_parent_inverse=parent.matrix_world.inverted();o.matrix_world=matrix
created.append(dict(name=o.name,bounds_m=[list(lo),list(hi)],material_name=mat.name,component_kind=kind))
return o
y=r['partition_y_m']
box('wall__bath__dry_wet__west',[6.035,y-.04,0],[6.30,y+.04,3],material)
box('wall__bath__dry_wet__east',[7.20,y-.04,0],[7.825,y+.04,3],material)
box('wall__bath__dry_wet__lintel',[6.30,y-.04,2.1],[7.20,y+.04,3],material)
box(INNER_DOOR+'__jamb_west',[6.30,y-.045,0],[6.325,y+.045,2.1],aluminum,'frame')
box(INNER_DOOR+'__jamb_east',[7.175,y-.045,0],[7.20,y+.045,2.1],aluminum,'frame')
box(INNER_DOOR+'__head',[6.325,y-.045,2.075],[7.175,y+.045,2.1],aluminum,'frame')
hinge=bpy.data.objects.new(INNER_DOOR+'__hinge',None);collection.objects.link(hinge);hinge.location=(*r['hinge_xy_m'],0)
hinge['portal_id']=INNER_DOOR;hinge['joint_type']='revolute';hinge['hinge_axis']=[0.,0.,1.];hinge['closed_yaw_deg']=0.;hinge['open_yaw_deg']=-90.
limit=hinge.constraints.new('LIMIT_ROTATION');limit.owner_space='LOCAL';limit.use_limit_x=limit.use_limit_y=limit.use_limit_z=True;limit.min_x=limit.max_x=limit.min_y=limit.max_y=0.;limit.min_z=-math.pi/2;limit.max_z=0.
x=6.33;w=.027;h=2.065;z=.015;depth=.018
for label,a,b in [('hinge',x,x+w),('latch',x+.84-w,x+.84)]:box(INNER_DOOR+'__'+label,[a,y-depth,z],[b,y+depth,h],aluminum,'leaf_frame',hinge)
box(INNER_DOOR+'__bottom',[x+w,y-depth,z],[x+.84-w,y+depth,z+w],aluminum,'leaf_frame',hinge)
box(INNER_DOOR+'__top',[x+w,y-depth,h-w],[x+.84-w,y+depth,h],aluminum,'leaf_frame',hinge)
box(INNER_DOOR+'__glass',[x+w,y-.004,z+w],[x+.84-w,y+.004,h-w],glass,'frosted_glass',hinge)
box(INNER_DOOR+'__pull',[x+.75,y+.019,.98],[x+.77,y+.036,1.15],aluminum,'handle',hinge)
bpy.context.view_layer.update();hinge.rotation_euler.z=-math.pi/2;bpy.context.view_layer.update()
delta=r['sink_translation_m']
for o in sink_objects:o.matrix_world=Matrix.Translation(delta)@o.matrix_world
for key in ('center_xy_m','actual_center_xy_m'):
if sink.get(key):sink[key]=[sink[key][i]+delta[i] for i in (0,1)]
if sink.get('visual_footprint_polygon_xy_m'):sink['visual_footprint_polygon_xy_m']=[[p[i]+delta[i] for i in (0,1)] for p in sink['visual_footprint_polygon_xy_m']]
sink['world_bbox_m']=copy.deepcopy(r['sink_world_bbox_m']);sink['layout_authority']='bathroom_entry_dry_zone';sink['functional_zone_id']='bath__entry_dry'
# Discard old pose evidence without changing source asset evidence.
stale={k:sink.pop(k) for k in ('operation_space_xy_m','front_clearance_box_xy_m','real_dimension_layout','functional_fit_corrections','measured_wall_mount','floor_body_geometry_evidence','_adaptive_relations') if k in sink}
md=source['dimensions_m'];sink_y=sum(v[1] for v in sink['world_bbox_m'])/2
mitem=dict(entity_id='bathroom_mirror',room_id='bath',functional_zone_id='bath__entry_dry',category='mirror',role='mirror',binding_semantic_key='mirror',
display_name=source['source_name'],yaw_deg=-90.,canonical_front_axis='+Y',center_xy_m=[6.035+md[1]/2,sink_y],
base_z_m=r['mirror_base_z_m'],dimensions_m=md,source_dimensions_m=md,uniform_scale=1.,world_front_vector_xy=[1.,0.],
wall_anchor='W',placement_side='W',reviewed_installation='wall',layout_relation='wall_mounted_above_basin',layout_authority='reviewed_bathroom_mirror',
source_semantic_evidence=dict(authored_source=dict(source_name=source['source_name'],wordnet_synset='mirror.n.01')),suffix='.glb',units='m',up_axis='Z')
for k in ('asset_id','asset_sha256','runtime_path','runtime_sha256','canonical_path','canonical_transform'):mitem[k]=source[k]
compositor=load_module('bathroom_mirror_compositor',code.parent/'base/blender_compose_asset_first_scene.py')
before=set(bpy.data.objects);record=compositor._import_entity(mitem);objects=[bpy.data.objects[n] for n in record['mesh_object_names']]
for o in list(bpy.data.objects):
if o not in before and o.type!='MESH':
for child in list(o.children):matrix=child.matrix_world.copy();child.parent=None;child.matrix_world=matrix
bpy.data.objects.remove(o,do_unlink=True)
lo,hi=mesh_bounds(objects);target=[6.035,sink_y-md[0]/2,r['mirror_base_z_m']];offset=[target[i]-lo[i] for i in range(3)]
for o in objects:o.matrix_world=Matrix.Translation(offset)@o.matrix_world
bpy.context.view_layer.update();lo,hi=mesh_bounds(objects);front_polygons=0
# Source mirror geometry is retained; only its authored front plane is
# assigned a reflective shader because the GLB's generic grey is not one.
for o in objects:
o.data.materials.append(mirror_material);index=len(o.data.materials)-1
for poly in o.data.polygons:
vertices=[o.matrix_world@o.data.vertices[i].co for i in poly.vertices]
if all(abs(v.x-hi[0])<.0015 for v in vertices):poly.material_index=index;front_polygons+=1
if front_polygons==0:raise ValueError('Native mirror front plane not found')
mitem.update(world_bbox_m=[list(lo),list(hi)],center_xy_m=[record['center_xy_m'][i]+offset[i] for i in (0,1)],
visual_footprint_polygon_xy_m=[[p[i]+offset[i] for i in (0,1)] for p in record['visual_footprint_polygon_xy_m']],
applied_world_front_vector_xy=[1.,0.],mesh_object_names=record['mesh_object_names'],mirror_front_material_correction=dict(front_polygons=front_polygons,material_name=mirror_material.name,source_materials_elsewhere_preserved=True))
mitem['actual_center_xy_m']=list(mitem['center_xy_m']);manifest['entities'].append(mitem)
update_plan(manifest,r);bpy.context.scene['rhg_bathroom_mode_revision_json']=json.dumps(manifest['bathroom_mode_revision'],sort_keys=True)
for row in created:
obj=bpy.data.objects[row['name']];row['bounds_m']=[list(v) for v in mesh_bounds([obj])]
return dict(schema=r['schema'],changed=True,mode='separated',plan=r,moved_existing_entities=['bathroom_sink'],
added_entities=['bathroom_mirror'],removed_objects=removed,created_objects=created,mirror_import=record,
wall_assignment_template_object=NORTH_PIERS[0],wall_material_source=material.name,previous_sink_pose_evidence=stale,
native_fixture_scales_preserved=True,mirror_front_material_correction=mitem['mirror_front_material_correction'],
floor_geometry_unchanged=True,physical_qualification_claimed=False)