-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrellis_for_blender.py
2200 lines (1867 loc) · 89.5 KB
/
trellis_for_blender.py
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
bl_info = {
"name": "TRELLIS 3D Generation",
"author": "FishWoWater",
"version": (0, 2),
"blender": (3, 6, 0),
"location": "View3D > Sidebar > TRELLIS",
"description": "3D Mesh Generation with TRELLIS (Image-to-3D and Text-to-3D)",
"category": "3D View",
}
import bpy
import os
import requests
import tempfile
import base64
import socket
import json
import traceback
from bpy.props import StringProperty, BoolProperty, EnumProperty, FloatProperty, IntProperty
from bpy.types import Operator, Panel, PropertyGroup
from bpy.utils import register_class, unregister_class
import time
# Configuration
CACHE_DIR = os.path.join(tempfile.gettempdir(), "trellis_cache")
os.makedirs(CACHE_DIR, exist_ok=True)
def get_cache_path(file_url):
"""Get local cache path for a file URL"""
return os.path.join(CACHE_DIR, file_url.split('/')[-2] + '_' + file_url.split('/')[-1])
def is_cached(file_url):
"""Check if file is already in cache"""
cache_path = get_cache_path(file_url)
return os.path.exists(cache_path)
def download_file(file_url):
"""Download file if not in cache"""
cache_path = get_cache_path(file_url)
if not is_cached(file_url):
response = requests.get(file_url, timeout=2)
response.raise_for_status()
with open(cache_path, 'wb') as f:
f.write(response.content)
return cache_path
class TrellisProperties(PropertyGroup):
api_url: StringProperty(name="Endpoint Url",
description="TRELLIS API URL",
default="http://localhost:6006",
maxlen=1024)
server_status: StringProperty(name="Server Status", default="unknown")
# Image-to-3D properties
image_path: StringProperty(name="input image path",
description="Path to the image file",
default="",
subtype='FILE_PATH')
# Text-to-3D properties
prompt_text: StringProperty(name="Text Prompt",
description="Text description for 3D generation",
default="",
maxlen=128)
negative_prompt_text: StringProperty(name="Negative Text Prompt",
description="Negative Text description for 3D generation",
default="",
maxlen=128)
# Common properties for both modes
sparse_structure_sample_steps: IntProperty(name="1st stage sample steps",
description="Number of sampling steps for the (SparseStructure)coarse geoemtry generation",
default=12,
min=1)
sparse_structure_cfg_strength: FloatProperty(name="1st stage cfg strength",
description="CFG strength for (SparseStructure)coarse geometry generation",
default=7.5,
min=0.0)
slat_sample_steps: IntProperty(name="2nd stage sample steps",
description="Number of sampling steps for (SLAT)final geometry and texture generation",
default=12,
min=1)
slat_cfg_strength: FloatProperty(name="2nd stage cfg strength",
description="CFG strength for (SLAT)final geometry and texture generation",
default=3.5,
min=0.0)
simplify_ratio: FloatProperty(name="simplify ratio",
description="Ratio of triangles to remove in simplification",
default=0.95,
min=0.0,
max=1.0)
texture_size: IntProperty(name="texture size", description="Size of the texture used for GLB", default=1024, min=64)
texture_bake_mode: EnumProperty(name="Tex Bake",
description="Mode for texture baking",
items=[('opt', "optimized", "Optimized texture baking"),
('fast', "fast", "Fast texture baking")],
default='fast')
auto_refresh: BoolProperty(
name="Auto Refresh",
description="Automatically refresh request status",
default=True,
update=lambda self, context: start_auto_refresh() if self.auto_refresh else stop_auto_refresh()
)
task_id: StringProperty(name="Task ID", description="Current task ID for tracking conversion progress", default="")
show_parameters: BoolProperty(name="Show Parameters", description="Show/hide generation parameters", default=False)
show_history: BoolProperty(name="Show History", description="Show/hide history section", default=False)
active_tab: EnumProperty(
name="Active Tab",
description="Active generation tab",
items=[
('IMAGE_TO_3D', "Image to 3D", "Generate 3D models from images"),
('TEXT_TO_3D', "Text to 3D", "Generate 3D models from text descriptions")
],
default='IMAGE_TO_3D'
)
class TRELLIS_OT_convert_image(Operator):
bl_idname = "trellis.convert_image"
bl_label = "Generation"
bl_description = "Convert image to 3D model using TRELLIS"
def execute(self, context):
props = context.scene.trellis_props
if not props.image_path:
self.report({'ERROR'}, "Please select an image file")
return {'CANCELLED'}
try:
with open(props.image_path, 'rb') as f:
# Read and encode the image file as base64
image_data = base64.b64encode(f.read()).decode('utf-8')
data = {
'image_data': image_data,
'image_name': os.path.splitext(os.path.basename(props.image_path))[0],
'sparse_structure_sample_steps': props.sparse_structure_sample_steps,
'sparse_structure_cfg_strength': props.sparse_structure_cfg_strength,
'slat_sample_steps': props.slat_sample_steps,
'slat_cfg_strength': props.slat_cfg_strength,
'simplify_ratio': props.simplify_ratio,
'texture_size': props.texture_size,
'texture_bake_mode': props.texture_bake_mode
}
headers = {'Content-Type': 'application/json'}
response = requests.post(f"{props.api_url}/image_to_3d", json=data, headers=headers, timeout=2)
response.raise_for_status()
result = response.json()
if result['status'] == 'queued':
self.report({'INFO'}, f"Request queued with ID: {result['request_id']}")
# Force an immediate refresh and update the UI
bpy.ops.trellis.refresh_status()
# TODO: CHECK THIS
# Force the panel to redraw
for area in context.screen.areas:
if area.type == 'VIEW_3D':
area.tag_redraw()
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error: {str(e)}")
return {'CANCELLED'}
return {'FINISHED'}
class TRELLIS_OT_import_result(Operator):
bl_idname = "trellis.import_result"
bl_label = "Import Result"
bl_description = "Import the selected result into Blender"
file_url: StringProperty()
def execute(self, context):
try:
# Download and import the file
file_path = download_file(self.file_url)
bpy.ops.import_scene.gltf(filepath=file_path)
self.report({'INFO'}, "Model imported successfully")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error importing model: {str(e)}")
return {'CANCELLED'}
class TRELLIS_OT_refresh_status(Operator):
bl_idname = "trellis.refresh_status"
bl_label = "Refresh Status"
bl_description = "Refresh the status of recent requests"
def execute(self, context):
try:
# Get recent requests
response = requests.get(f"{context.scene.trellis_props.api_url}/my_requests", timeout=1)
response.raise_for_status()
# Format the finish_time for each request if available
result = response.json()
for req in result.get('requests', []):
if 'finish_time' in req and req['finish_time']:
# Convert ISO format to more readable format
try:
from datetime import datetime
# Handle ISO format without Z suffix
finish_time = datetime.fromisoformat(req['finish_time'])
# Format with date and time, showing only hours and minutes
req['display_time'] = finish_time.strftime('%Y-%m-%d %H:%M')
except Exception as e:
print(f"Error parsing time: {e}")
# Keep original if parsing fails
req['display_time'] = req['finish_time']
context.scene['trellis_requests'] = result
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error refreshing status: {str(e)}")
return {'CANCELLED'}
class TRELLIS_OT_convert_text(Operator):
bl_idname = "trellis.convert_text"
bl_label = "Text to 3D Generation"
bl_description = "Convert text prompt to 3D model using TRELLIS"
def execute(self, context):
props = context.scene.trellis_props
if not props.prompt_text.strip():
self.report({'ERROR'}, "Please enter a text prompt")
return {'CANCELLED'}
try:
data = {
'text': props.prompt_text,
'negative_text': props.negative_prompt_text,
'ss_sample_steps': props.sparse_structure_sample_steps,
'ss_cfg_strength': props.sparse_structure_cfg_strength,
'slat_sample_steps': props.slat_sample_steps,
'slat_cfg_strength': props.slat_cfg_strength,
'simplify_ratio': props.simplify_ratio,
'texture_size': props.texture_size,
'texture_bake_mode': props.texture_bake_mode
}
headers = {'Content-Type': 'application/json'}
response = requests.post(f"{props.api_url}/text_to_3d", json=data, headers=headers)
response.raise_for_status()
result = response.json()
if result['status'] == 'queued':
self.report({'INFO'}, f"Request queued with ID: {result['request_id']}")
# Force an immediate refresh and update the UI
bpy.ops.trellis.refresh_status()
# Force the panel to redraw
for area in context.screen.areas:
if area.type == 'VIEW_3D':
area.tag_redraw()
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error: {str(e)}")
return {'CANCELLED'}
return {'FINISHED'}
class TRELLIS_OT_show_preview(Operator):
bl_idname = "trellis.show_preview"
bl_label = "Preview Image"
bl_description = "Show preview of selected image"
def execute(self, context):
props = context.scene.trellis_props
if not props.image_path or not os.path.exists(props.image_path):
self.report({'ERROR'}, "Please select a valid image file")
return {'CANCELLED'}
# Load image into Blender
image_name = os.path.basename(props.image_path)
if image_name in bpy.data.images:
bpy.data.images.remove(bpy.data.images[image_name])
img = bpy.data.images.load(props.image_path)
# Try to find an existing image editor
image_editor = None
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type == 'IMAGE_EDITOR':
image_editor = area
break
if image_editor:
break
if not image_editor:
# If no image editor exists, create one by splitting the 3D view
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type == 'VIEW_3D':
# Store current context
temp_override = context.copy()
temp_override['window'] = window
temp_override['screen'] = window.screen
temp_override['area'] = area
temp_override['region'] = area.regions[-1]
# Split the area
with context.temp_override(**temp_override):
bpy.ops.screen.area_split(direction='VERTICAL', factor=0.3)
# The new area is the last one in the areas list
new_area = window.screen.areas[-1]
new_area.type = 'IMAGE_EDITOR'
image_editor = new_area
break
if image_editor:
break
# Set the image in the editor
if image_editor:
image_editor.spaces.active.image = img
else:
self.report({'WARNING'}, "Could not create image editor, but image was loaded")
return {'FINISHED'}
class TRELLIS_OT_convert_mesh(Operator):
bl_idname = "trellis.convert_mesh"
bl_label = "Convert Selected to GLB"
bl_description = "Convert selected object to GLB and process with TRELLIS using image conditioning"
def execute(self, context):
props = context.scene.trellis_props
# Check requirements
if not context.active_object:
self.report({'ERROR'}, "Please select an object to convert")
return {'CANCELLED'}
if not props.image_path:
self.report({'ERROR'}, "Please select an input image")
return {'CANCELLED'}
# Create a temporary directory for the GLB
temp_dir = tempfile.mkdtemp()
temp_glb = os.path.join(temp_dir, "temp.glb")
try:
# Export selected object to GLB
bpy.ops.export_scene.gltf(
filepath=temp_glb,
use_selection=True,
export_format='GLB',
export_yup=False # This ensures Z-up orientation
)
# Read and encode both GLB and image files as base64
with open(temp_glb, 'rb') as glb_file, open(props.image_path, 'rb') as img_file:
glb_data = base64.b64encode(glb_file.read()).decode('utf-8')
img_data = base64.b64encode(img_file.read()).decode('utf-8')
data = {
'mesh_data': glb_data,
'image_data': img_data,
'image_name': os.path.splitext(os.path.basename(props.image_path))[0],
'sparse_structure_sample_steps': props.sparse_structure_sample_steps,
'sparse_structure_cfg_strength': props.sparse_structure_cfg_strength,
'slat_sample_steps': props.slat_sample_steps,
'slat_cfg_strength': props.slat_cfg_strength,
'simplify_ratio': props.simplify_ratio,
'texture_size': props.texture_size,
'texture_bake_mode': props.texture_bake_mode,
'is_dv_mode': True
}
headers = {'Content-Type': 'application/json'}
response = requests.post(f"{props.api_url}/image_to_3d", json=data, headers=headers)
response.raise_for_status()
result = response.json()
if result['status'] == 'queued':
# Refresh status immediately to show the new request
bpy.ops.trellis.refresh_status()
self.report({'INFO'}, f"Request queued with ID: {result.get('request_id', '')}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error: {str(e)}")
return {'CANCELLED'}
finally:
# Clean up temporary files
if os.path.exists(temp_glb):
os.remove(temp_glb)
if os.path.exists(temp_dir):
os.rmdir(temp_dir)
return {'FINISHED'}
class TRELLIS_OT_convert_text_mesh(Operator):
bl_idname = "trellis.convert_text_mesh"
bl_label = "Convert Selected to GLB with Text"
bl_description = "Convert selected object to GLB and process with TRELLIS using text conditioning"
def execute(self, context):
props = context.scene.trellis_props
# Check requirements
if not context.active_object:
self.report({'ERROR'}, "Please select an object to convert")
return {'CANCELLED'}
if not props.prompt_text.strip():
self.report({'ERROR'}, "Please enter a text prompt")
return {'CANCELLED'}
# Create a temporary directory for the GLB
temp_dir = tempfile.mkdtemp()
temp_glb = os.path.join(temp_dir, "temp.glb")
try:
# Export selected object to GLB
bpy.ops.export_scene.gltf(
filepath=temp_glb,
use_selection=True,
export_format='GLB',
export_yup=False # This ensures Z-up orientation
)
# Read and encode GLB file as base64
with open(temp_glb, 'rb') as glb_file:
glb_data = base64.b64encode(glb_file.read()).decode('utf-8')
data = {
'mesh_data': glb_data,
'text': props.prompt_text,
'negative_text': props.negative_prompt_text,
'ss_sample_steps': props.sparse_structure_sample_steps,
'ss_cfg_strength': props.sparse_structure_cfg_strength,
'slat_sample_steps': props.slat_sample_steps,
'slat_cfg_strength': props.slat_cfg_strength,
'simplify_ratio': props.simplify_ratio,
'texture_size': props.texture_size,
'texture_bake_mode': props.texture_bake_mode,
'is_dv_mode': True
}
headers = {'Content-Type': 'application/json'}
response = requests.post(f"{props.api_url}/text_to_3d", json=data, headers=headers)
response.raise_for_status()
result = response.json()
if result['status'] == 'queued':
# Refresh status immediately to show the new request
bpy.ops.trellis.refresh_status()
self.report({'INFO'}, f"Request queued with ID: {result.get('request_id', '')}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error: {str(e)}")
return {'CANCELLED'}
finally:
# Clean up temporary files
if os.path.exists(temp_glb):
os.remove(temp_glb)
if os.path.exists(temp_dir):
os.rmdir(temp_dir)
return {'FINISHED'}
class TRELLIS_OT_check_server(Operator):
bl_idname = "trellis.check_server"
bl_label = "Check Server"
bl_description = "Check if the TRELLIS server is running"
def execute(self, context):
props = context.scene.trellis_props
try:
response = requests.get(f"{props.api_url}/status", timeout=2)
if response.status_code == 200 and response.json().get('status') == 'ok':
props.server_status = "online"
self.report({'INFO'}, "TRELLIS server is online")
else:
props.server_status = "offline"
self.report({'ERROR'}, "TRELLIS server is not responding correctly")
except Exception as e:
props.server_status = "offline"
self.report({'ERROR'}, f"Error connecting to server: {str(e)}")
# Force redraw of the UI
for area in context.screen.areas:
if area.type == 'VIEW_3D':
area.tag_redraw()
return {'FINISHED'}
class TRELLIS_PT_main_panel(Panel):
bl_label = "TRELLIS 3D Generation"
bl_idname = "TRELLIS_PT_main_panel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'TRELLIS'
bl_options = {'DEFAULT_CLOSED'}
def draw(self, context):
layout = self.layout
props = context.scene.trellis_props
scene = context.scene
# API Configuration
box = layout.box()
box.label(text="API Configuration")
row = box.row()
row.prop(props, "api_url")
row = box.row()
row.operator("trellis.check_server", text="Check Connection", icon='FILE_REFRESH')
# MCP Server section
mcp_box = layout.box()
row = mcp_box.row(align=True)
row.alignment = "CENTER"
row.label(text="MCP Connections")
row = mcp_box.row()
row.prop(scene, "trellis_mcp_port")
row = mcp_box.row()
row.prop(scene, "blendermcp_use_polyhaven", text="Use assets from Poly Haven")
row = mcp_box.row()
row.enabled = True
row.prop(scene, "MCP_use_trellis", text="Use Trellis as assets generator")
if not scene.trellis_mcp_server_running:
mcp_box.operator("trellis.start_mcp_server", text="Start MCP Server")
else:
mcp_box.operator("trellis.stop_mcp_server", text="Stop MCP Server")
mcp_box.label(text=f"Running on port {scene.trellis_mcp_port}")
# Show server status
if props.server_status == "online":
box.label(text="Server Status: Online", icon='CHECKMARK')
# Only show the rest of the UI if the server is online
# Tab selector
row = layout.row()
row.prop(props, "active_tab", expand=True)
# Draw the appropriate panel based on active tab
if props.active_tab == 'IMAGE_TO_3D':
self.draw_image_to_3d(context, layout)
else: # TEXT_TO_3D
self.draw_text_to_3d(context, layout)
# History section (common for both tabs)
self.draw_history(context, layout)
elif props.server_status == "offline":
box.label(text="Server Status: Offline", icon='CANCEL')
layout.label(text="Please check the server connection", icon='ERROR')
else:
box.label(text="Server Status: Unknown", icon='QUESTION')
layout.label(text="Please check the server connection", icon='INFO')
def draw_image_to_3d(self, context, layout):
props = context.scene.trellis_props
# Image selection
box = layout.box()
box.label(text="Image Input")
row = box.row()
row.prop(props, "image_path")
# Preview button
if props.image_path and os.path.exists(props.image_path):
row = box.row()
row.operator("trellis.show_preview", text="Preview Image", icon='IMAGE_DATA')
# Parameters with collapse button
self.draw_parameters(context, layout)
# Convert buttons
layout.operator("trellis.convert_image", text="Image to 3D", icon='MESH_CUBE')
layout.operator("trellis.convert_mesh", text="Image-Conditioned Detail Variation", icon='MESH_CUBE')
def draw_text_to_3d(self, context, layout):
props = context.scene.trellis_props
# Text input
box = layout.box()
box.label(text="Text Prompt")
col = box.column()
col.prop(props, "prompt_text", text="")
# Negative prompt
neg_box = layout.box()
neg_box.label(text="Negative Text Prompt")
neg_col = neg_box.column()
neg_col.prop(props, "negative_prompt_text", text="")
# Parameters with collapse button
self.draw_parameters(context, layout)
# Convert buttons
layout.operator("trellis.convert_text", text="Text to 3D", icon='MESH_CUBE')
layout.operator("trellis.convert_text_mesh", text="Text-Conditioned Detail Variation", icon='MESH_CUBE')
def draw_parameters(self, context, layout):
props = context.scene.trellis_props
params_box = layout.box()
row = params_box.row()
row.prop(props,
"show_parameters",
text="Parameters",
icon='TRIA_DOWN' if props.show_parameters else 'TRIA_RIGHT',
emboss=False)
if props.show_parameters:
col = params_box.column(align=True)
col.prop(props, "sparse_structure_sample_steps")
col.prop(props, "sparse_structure_cfg_strength")
col.prop(props, "slat_sample_steps")
col.prop(props, "slat_cfg_strength")
col.prop(props, "simplify_ratio")
col.prop(props, "texture_size")
col.prop(props, "texture_bake_mode")
def draw_history(self, context, layout):
props = context.scene.trellis_props
# History section in a single box
history_box = layout.box()
row = history_box.row()
row.prop(props,
"show_history",
text="History",
icon='TRIA_DOWN' if props.show_history else 'TRIA_RIGHT',
emboss=False)
row.operator("trellis.refresh_status", text="", icon='FILE_REFRESH')
if props.show_history:
row = history_box.row()
row.prop(props, "auto_refresh")
if 'trellis_requests' in context.scene:
requests = context.scene['trellis_requests'].get('requests', [])
for req in requests:
row = history_box.row(align=True)
# Show request type and ID
task_type = "TextTo3D" if req.get('task_type', '') == 'text_to_3d' else "ImageTo3D"
instance_name = req.get('image_name', '') if task_type == "ImageTo3D" else req.get('text', '')
display_name = f"{task_type}: {instance_name[:8]}(ID-{req['request_id'][:8]})"
row.label(text=display_name)
if 'display_time' in req:
row.label(text=req['display_time'])
row.label(text=req['status'])
# Show finish time if available
# if 'display_time' in req:
# time_row = history_box.row()
# time_row.label(text=f" Finished: {req['display_time']}")
if req['status'] == 'complete' and req.get('output_files'):
for file_url in req['output_files']:
if file_url.endswith('.glb'):
op = row.operator("trellis.import_result", text="", icon='IMPORT')
op.file_url = file_url
def auto_refresh_callback():
# Get or initialize the attempt count and last success time
if not hasattr(auto_refresh_callback, 'attempt_count'):
auto_refresh_callback.attempt_count = 0
if not hasattr(auto_refresh_callback, 'last_success'):
auto_refresh_callback.last_success = 0
try:
if not bpy.context or not hasattr(bpy.context.scene, 'trellis_props'):
return None # Stop timer if context is invalid
if bpy.context.scene.trellis_props.auto_refresh:
try:
bpy.ops.trellis.refresh_status()
# Reset attempt count on success
auto_refresh_callback.attempt_count = 0
auto_refresh_callback.last_success = time.time()
return 3.0 # Normal interval on success
except Exception as e:
print(f"Error in auto refresh: {str(e)}")
# Increment attempt count on failure
auto_refresh_callback.attempt_count += 1
# If we haven't had success for over 5 minutes, stop retrying
if time.time() - auto_refresh_callback.last_success > 300: # 5 minutes
print("Auto-refresh stopped: Server unavailable for 5 minutes")
return None
# Exponential backoff: 3s, 6s, 12s, 24s
next_interval = min(3.0 * (2 ** (auto_refresh_callback.attempt_count - 1)), 24.0)
return next_interval
return None # Stop timer if auto_refresh is disabled
except Exception:
return None # Stop timer if any error occurs
def start_auto_refresh():
if not bpy.app.timers.is_registered(auto_refresh_callback):
bpy.app.timers.register(auto_refresh_callback, persistent=True)
def stop_auto_refresh():
if bpy.app.timers.is_registered(auto_refresh_callback):
bpy.app.timers.unregister(auto_refresh_callback)
# MCP Server implementation
class BlenderMCPServer:
def __init__(self, host="localhost", port=9876):
self.host = host
self.port = port
self.running = False
self.socket = None
self.client = None
self.command_queue = []
self.buffer = b"" # Buffer for incomplete data
def start(self):
self.running = True
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.socket.bind((self.host, self.port))
self.socket.listen(1)
self.socket.setblocking(False)
# Register the timer
bpy.app.timers.register(self._process_server, persistent=True)
print(f"BlenderMCP server started on {self.host}:{self.port}")
except Exception as e:
print(f"Failed to start server: {str(e)}")
self.stop()
def stop(self):
self.running = False
if hasattr(bpy.app.timers, "unregister"):
if bpy.app.timers.is_registered(self._process_server):
bpy.app.timers.unregister(self._process_server)
if self.socket:
self.socket.close()
if self.client:
self.client.close()
self.socket = None
self.client = None
print("BlenderMCP server stopped")
def _process_server(self):
"""Timer callback to process server operations"""
if not self.running:
return None # Unregister timer
try:
# Accept new connections
if not self.client and self.socket:
try:
self.client, address = self.socket.accept()
self.client.setblocking(False)
print(f"Connected to client: {address}")
except BlockingIOError:
pass # No connection waiting
except Exception as e:
print(f"Error accepting connection: {str(e)}")
# Process existing connection
if self.client:
try:
# Try to receive data
try:
data = self.client.recv(8192)
if data:
self.buffer += data
# Try to process complete messages
try:
# Attempt to parse the buffer as JSON
command = json.loads(self.buffer.decode("utf-8"))
# If successful, clear the buffer and process command
self.buffer = b""
response = self.execute_command(command)
response_json = json.dumps(response)
self.client.sendall(response_json.encode("utf-8"))
except json.JSONDecodeError:
# Incomplete data, keep in buffer
pass
else:
# Connection closed by client
print("Client disconnected")
self.client.close()
self.client = None
self.buffer = b""
except BlockingIOError:
pass # No data available
except Exception as e:
print(f"Error receiving data: {str(e)}")
self.client.close()
self.client = None
self.buffer = b""
except Exception as e:
print(f"Error with client: {str(e)}")
if self.client:
self.client.close()
self.client = None
self.buffer = b""
except Exception as e:
print(f"Server error: {str(e)}")
return 0.1 # Check again in 0.1 seconds
def execute_command(self, command):
"""Execute a command in the main Blender thread"""
try:
cmd_type = command.get("type")
params = command.get("params", {})
# Ensure we're in the right context
if cmd_type in ["create_object", "modify_object", "delete_object"]:
override = bpy.context.copy()
override["area"] = [
area for area in bpy.context.screen.areas if area.type == "VIEW_3D"
][0]
with bpy.context.temp_override(**override):
return self._execute_command_internal(command)
else:
return self._execute_command_internal(command)
except Exception as e:
print(f"Error executing command: {str(e)}")
traceback.print_exc()
return {"status": "error", "message": str(e)}
def _execute_command_internal(self, command):
"""Internal command execution with proper context"""
cmd_type = command.get("type")
params = command.get("params", {})
# Add a handler for checking PolyHaven status
if cmd_type == "get_polyhaven_status":
return {"status": "success", "result": self.get_polyhaven_status()}
# Base handlers that are always available
handlers = {
"get_scene_info": self.get_scene_info,
"create_object": self.create_object,
"modify_object": self.modify_object,
"delete_object": self.delete_object,
"get_object_info": self.get_object_info,
"execute_code": self.execute_code,
"set_material": self.set_material,
"get_polyhaven_status": self.get_polyhaven_status,
"import_trellis_glb_model": self.import_trellis_glb_model,
}
# Add Polyhaven handlers only if enabled
if bpy.context.scene.blendermcp_use_polyhaven:
polyhaven_handlers = {
"get_polyhaven_categories": self.get_polyhaven_categories,
"search_polyhaven_assets": self.search_polyhaven_assets,
"download_polyhaven_asset": self.download_polyhaven_asset,
"set_texture": self.set_texture,
}
handlers.update(polyhaven_handlers)
handler = handlers.get(cmd_type)
if handler:
try:
print(f"Executing handler for {cmd_type}")
result = handler(**params)
print(f"Handler execution complete")
return {"status": "success", "result": result}
except Exception as e:
print(f"Error in handler: {str(e)}")
traceback.print_exc()
return {"status": "error", "message": str(e)}
else:
return {"status": "error", "message": f"Unknown command type: {cmd_type}"}
def import_trellis_glb_model(self, url):
response = requests.get(url, timeout=1)
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".glb")
temp_file.write(response.content)
temp_file.close()
bpy.ops.object.select_all(action="DESELECT")
bpy.ops.import_scene.gltf(filepath=temp_file.name)
imported_objects = bpy.context.selected_objects
model_info = []
for obj in imported_objects:
# calculate the bounding box
bbox_dimensions = [
dim * scale for dim, scale in zip(obj.dimensions, obj.scale)
]
model_info.append(
{
"name": obj.name,
"dimensions": {
"x": round(bbox_dimensions[0], 4),
"y": round(bbox_dimensions[1], 4),
"z": round(bbox_dimensions[2], 4),
},
}
)
os.unlink(temp_file.name)
return {
"status": "success",
"message": "Model imported successfully",
"models": model_info,
}
def get_simple_info(self):
"""Get basic Blender information"""
return {
"blender_version": ".".join(str(v) for v in bpy.app.version),
"scene_name": bpy.context.scene.name,
"object_count": len(bpy.context.scene.objects),
}
def get_scene_info(self):
"""Get information about the current Blender scene"""
try:
print("Getting scene info...")
# Simplify the scene info to reduce data size
scene_info = {
"name": bpy.context.scene.name,
"object_count": len(bpy.context.scene.objects),
"objects": [],
"materials_count": len(bpy.data.materials),
}
# Collect minimal object information (limit to first 10 objects)
for i, obj in enumerate(bpy.context.scene.objects):
if i >= 10: # Reduced from 20 to 10
break
obj_info = {
"name": obj.name,
"type": obj.type,
# Only include basic location data
"location": [
round(float(obj.location.x), 2),
round(float(obj.location.y), 2),
round(float(obj.location.z), 2),
],
}
scene_info["objects"].append(obj_info)
print(f"Scene info collected: {len(scene_info['objects'])} objects")
return scene_info
except Exception as e:
print(f"Error in get_scene_info: {str(e)}")
traceback.print_exc()
return {"error": str(e)}
def create_object(
self,
type="CUBE",
name=None,
location=(0, 0, 0),
rotation=(0, 0, 0),
scale=(1, 1, 1),
):
"""Create a new object in the scene"""
# Deselect all objects
bpy.ops.object.select_all(action="DESELECT")
# Create the object based on type
if type == "CUBE":
bpy.ops.mesh.primitive_cube_add(
location=location, rotation=rotation, scale=scale
)
elif type == "SPHERE":
bpy.ops.mesh.primitive_uv_sphere_add(
location=location, rotation=rotation, scale=scale
)
elif type == "CYLINDER":
bpy.ops.mesh.primitive_cylinder_add(
location=location, rotation=rotation, scale=scale
)
elif type == "PLANE":
bpy.ops.mesh.primitive_plane_add(
location=location, rotation=rotation, scale=scale
)
elif type == "CONE":
bpy.ops.mesh.primitive_cone_add(
location=location, rotation=rotation, scale=scale