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

import os
import json
import argparse
import subprocess
import sys
import tempfile
import shutil
from pathlib import Path
from typing import List, Dict, Any, Optional

# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))


# Keywords to identify tables and sofas
TABLE_KEYWORDS = ['table', 'desk', 'dining', 'coffee_table', 'end_table', 'side_table', 'console']
SOFA_KEYWORDS = ['sofa', 'couch', 'loveseat', 'settee', 'sectional', 'armchair', 'chair']


def is_table(asset: Dict) -> bool:
    """Check if asset is a table."""
    semantic = asset.get('semantic', '').lower()
    category = asset.get('category', '').lower()
    uid = asset.get('uid', '').lower()
    
    text = f"{semantic} {category} {uid}"
    return any(kw in text for kw in TABLE_KEYWORDS)


def is_sofa(asset: Dict) -> bool:
    """Check if asset is a sofa/seating."""
    semantic = asset.get('semantic', '').lower()
    category = asset.get('category', '').lower()
    uid = asset.get('uid', '').lower()
    
    text = f"{semantic} {category} {uid}"
    return any(kw in text for kw in SOFA_KEYWORDS)


def find_tables_and_sofas(layout: Dict) -> Dict[str, List[Dict]]:
    """Find all tables and sofas in the layout."""
    assets = layout.get('assets', [])
    
    tables = []
    sofas = []
    
    for asset in assets:
        if is_table(asset):
            tables.append(asset)
        elif is_sofa(asset):
            sofas.append(asset)
    
    return {
        'tables': tables,
        'sofas': sofas
    }


def compose_assets_scene(assets: List[Dict], output_path: str):
    """
    Compose a scene with only the specified assets.
    """
    from tools.data_gen.compose_generated import compose_scene
    
    # Create a minimal layout with just these assets
    layout = {
        "meta": {"scene_type": "asset_vis"},
        "architecture": {"boundary_polygon": []},
        "assets": assets
    }
    
    compose_scene(
        layout=layout,
        output_path=output_path,
        add_floor=False,
        add_walls=False,
        add_ceiling=False,
    )
    print(f"  Composed scene: {output_path}")


def run_command(cmd, env=None, quiet=False):
    """Run a shell command."""
    print(f"  Running: {cmd[:100]}...")
    try:
        if quiet:
            subprocess.check_call(cmd, shell=True, env=env,
                                  stdout=subprocess.DEVNULL,
                                  stderr=subprocess.DEVNULL)
        else:
            subprocess.check_call(cmd, shell=True, env=env)
        return True
    except subprocess.CalledProcessError as e:
        print(f"  Command failed: {e}")
        return False


def render_scene(glb_path: str, output_path: str, view_mode: str = "diagonal",
                 width: int = 1200, height: int = 900):
    """Render a GLB scene using Blender."""
    current_env = os.environ.copy()
    
    cmd = (
        f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
        f"--input '{glb_path}' "
        f"--output '{output_path}' "
        f"--width {width} --height {height} "
        f"--engine BLENDER_EEVEE --samples 64 "
        f"--view-mode {view_mode} --auto-crop "
        f"--floor-material solid "
        f"--diagonal-distance 2.5 "
        f"--camera-factor 1.8 "
    )
    
    run_command(cmd, env=current_env, quiet=True)


def render_table_sofa(
    layout_path: str,
    output_dir: str,
    render_views: List[str] = None,
):
    """
    Main function to render tables and sofas from a layout.
    """
    if render_views is None:
        render_views = ["diagonal", "diagonal2"]
    
    print(f"\n{'='*60}")
    print(f"Table & Sofa Rendering")
    print(f"{'='*60}")
    print(f"Input: {layout_path}")
    print(f"Output: {output_dir}")
    print(f"{'='*60}\n")
    
    # Load layout
    with open(layout_path, 'r') as f:
        layout = json.load(f)
    
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Find tables and sofas
    print("Finding tables and sofas...")
    found = find_tables_and_sofas(layout)
    
    tables = found['tables']
    sofas = found['sofas']
    
    print(f"Found {len(tables)} table(s):")
    for t in tables:
        print(f"  - {t.get('semantic', 'unknown')} ({t.get('uid', 'no-uid')[:30]})")
    
    print(f"Found {len(sofas)} sofa(s):")
    for s in sofas:
        print(f"  - {s.get('semantic', 'unknown')} ({s.get('uid', 'no-uid')[:30]})")
    
    if not tables and not sofas:
        print("No tables or sofas found in this layout!")
        return
    
    # Combine all found assets
    assets_to_render = tables + sofas
    
    print(f"\nRendering {len(assets_to_render)} asset(s) together...")
    
    # Create temporary directory for intermediate files
    with tempfile.TemporaryDirectory() as tmpdir:
        # Compose scene with tables and sofas
        scene_glb = os.path.join(tmpdir, "table_sofa_scene.glb")
        compose_assets_scene(assets_to_render, scene_glb)
        
        # Render from different views
        for view in render_views:
            print(f"\nRendering {view} view...")
            output_img = os.path.join(output_dir, f"table_sofa_{view}.png")
            render_scene(scene_glb, output_img, view_mode=view)
            
            if os.path.exists(output_img):
                print(f"  Saved: {output_img}")
    
    # Save asset info
    info_path = os.path.join(output_dir, "asset_info.json")
    info = {
        'tables': [{'semantic': t.get('semantic'), 'uid': t.get('uid')} for t in tables],
        'sofas': [{'semantic': s.get('semantic'), 'uid': s.get('uid')} for s in sofas],
    }
    with open(info_path, 'w') as f:
        json.dump(info, f, indent=2)
    
    print(f"\n{'='*60}")
    print(f"Done! Outputs saved to {output_dir}")
    print(f"{'='*60}\n")


def main():
    parser = argparse.ArgumentParser(description='Render tables and sofas from a scene layout')
    parser.add_argument('--input', required=True, help='Path to layout JSON file')
    parser.add_argument('--output', default='table_sofa_output', help='Output directory')
    parser.add_argument('--all-views', action='store_true', help='Render from all standard views')
    
    args = parser.parse_args()
    
    views = ["diagonal", "diagonal2"]
    if args.all_views:
        views = ["diagonal", "diagonal2", "top", "front"]
    
    render_table_sofa(
        layout_path=args.input,
        output_dir=args.output,
        render_views=views,
    )


if __name__ == "__main__":
    main()