-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathnodes.py
More file actions
2014 lines (1642 loc) · 87.2 KB
/
nodes.py
File metadata and controls
2014 lines (1642 loc) · 87.2 KB
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
from PIL import Image, ImageSequence, ImageOps
from torch.utils.data import Dataset
import torch
import shutil
import argparse
import copy
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision.utils import save_image as imwrite
from torchvision import transforms
import os
import time
import re
import numpy as np
import torch.nn.functional as F
import trimesh as Trimesh
import gc
import json
from .hy3dshape.hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline
from .hy3dshape.hy3dshape.postprocessors import FaceReducer, FloaterRemover, DegenerateFaceRemover
from .hy3dshape.hy3dshape.rembg import BackgroundRemover
from typing import Union, Optional, Tuple, List, Any, Callable
from pathlib import Path
#painting
from .hy3dpaint.DifferentiableRenderer.MeshRender import MeshRender
from .hy3dpaint.utils.simplify_mesh_utils import remesh_mesh
from .hy3dpaint.utils.multiview_utils import multiviewDiffusionNet
from .hy3dpaint.utils.pipeline_utils import ViewProcessor
from .hy3dpaint.utils.image_super_utils import imageSuperNet
from .hy3dpaint.utils.uvwrap_utils import mesh_uv_wrap
from .hy3dpaint.convert_utils import create_glb_with_pbr_materials
from .hy3dpaint.textureGenPipeline import Hunyuan3DPaintPipeline, Hunyuan3DPaintConfig
from .hy3dshape.hy3dshape.models.autoencoders import ShapeVAE
from .hy3dshape.hy3dshape.meshlib import postprocessmesh
from spandrel import ModelLoader, ImageModelDescriptor
import folder_paths
import node_helpers
import hashlib
import comfy.model_management as mm
from comfy.utils import load_torch_file, ProgressBar
import comfy.utils
script_directory = os.path.dirname(os.path.abspath(__file__))
comfy_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
diffusions_dir = os.path.join(comfy_path, "models", "diffusers")
def parse_string_to_int_list(number_string):
"""
Parses a string containing comma-separated numbers into a list of integers.
Args:
number_string: A string containing comma-separated numbers (e.g., "20000,10000,5000").
Returns:
A list of integers parsed from the input string.
Returns an empty list if the input string is empty or None.
"""
if not number_string:
return []
try:
# Split the string by comma and convert each part to an integer
int_list = [int(num.strip()) for num in number_string.split(',')]
return int_list
except ValueError as e:
print(f"Error converting string to integer: {e}. Please ensure all values are valid numbers.")
return []
def hy3dpaintimages_to_tensor(images):
tensors = []
for pil_img in images:
np_img = np.array(pil_img).astype(np.uint8)
np_img = np_img / 255.0
tensor_img = torch.from_numpy(np_img).float()
tensors.append(tensor_img)
tensors = torch.stack(tensors)
return tensors
def get_picture_files(folder_path):
"""
Retrieves all picture files (based on common extensions) from a given folder.
Args:
folder_path (str): The path to the folder to search.
Returns:
list: A list of full paths to the picture files found.
"""
picture_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp')
picture_files = []
if not os.path.isdir(folder_path):
print(f"Error: Folder '{folder_path}' not found.")
return []
for entry_name in os.listdir(folder_path):
full_path = os.path.join(folder_path, entry_name)
# Check if the entry is actually a file (and not a sub-directory)
if os.path.isfile(full_path):
file_name, file_extension = os.path.splitext(entry_name)
if file_extension.lower().endswith(picture_extensions):
picture_files.append(full_path)
return picture_files
def get_mesh_files(folder_path, name_filter = None):
"""
Retrieves all picture files (based on common extensions) from a given folder.
Args:
folder_path (str): The path to the folder to search.
Returns:
list: A list of full paths to the picture files found.
"""
mesh_extensions = ('.obj', '.glb')
mesh_files = []
if not os.path.isdir(folder_path):
print(f"Error: Folder '{folder_path}' not found.")
return []
for entry_name in os.listdir(folder_path):
full_path = os.path.join(folder_path, entry_name)
# Check if the entry is actually a file (and not a sub-directory)
if os.path.isfile(full_path):
file_name, file_extension = os.path.splitext(entry_name)
if file_extension.lower().endswith(mesh_extensions):
if name_filter is None or name_filter.lower() in file_name.lower():
mesh_files.append(full_path)
return mesh_files
def get_filename_without_extension_os_path(full_file_path):
"""
Extracts the filename without its extension from a full file path using os.path.
Args:
full_file_path (str): The complete path to the file.
Returns:
str: The filename without its extension.
"""
# 1. Get the base name (filename with extension)
base_name = os.path.basename(full_file_path)
# 2. Split the base name into root (filename without ext) and extension
file_name_without_ext, _ = os.path.splitext(base_name)
return file_name_without_ext
def _convert_texture_format(tex: Union[np.ndarray, torch.Tensor, Image.Image],
texture_size: Tuple[int, int], device: str, force_set: bool = False) -> torch.Tensor:
"""Unified texture format conversion logic."""
if not force_set:
if isinstance(tex, np.ndarray):
tex = Image.fromarray((tex * 255).astype(np.uint8))
elif isinstance(tex, torch.Tensor):
tex_np = tex.cpu().numpy()
# 2. Handle potential batch dimension (B, C, H, W) or (B, H, W, C)
if tex_np.ndim == 4:
if tex_np.shape[0] == 1:
tex_np = tex_np.squeeze(0)
else:
tex_np = tex_np[0]
# 3. Handle data type and channel order for PIL
if tex_np.ndim == 3:
if tex_np.shape[0] in [1, 3, 4] and tex_np.shape[0] < tex_np.shape[1] and tex_np.shape[0] < tex_np.shape[2]:
tex_np = np.transpose(tex_np, (1, 2, 0))
elif tex_np.shape[2] in [1, 3, 4] and tex_np.shape[0] > 4 and tex_np.shape[1] > 4:
pass
else:
raise ValueError(f"Unsupported 3D tensor shape after squeezing batch and moving to CPU. "
f"Expected (C, H, W) or (H, W, C) but got {tex_np.shape}")
if tex_np.shape[2] == 1:
tex_np = tex_np.squeeze(2) # Remove the channel dimension
elif tex_np.ndim == 2:
pass
else:
raise ValueError(f"Unsupported tensor dimension after squeezing batch and moving to CPU: {tex_np.ndim} "
f"with shape {tex_np.shape}. Expected 2D or 3D image data.")
tex_np_uint8 = (tex_np * 255).astype(np.uint8)
tex = Image.fromarray(tex_np_uint8)
tex = tex.resize(texture_size).convert("RGB")
tex = np.array(tex) / 255.0
return torch.from_numpy(tex).to(device).float()
else:
if isinstance(tex, np.ndarray):
tex = torch.from_numpy(tex)
return tex.to(device).float()
def convert_ndarray_to_pil(texture):
texture_size = len(texture)
tex = _convert_texture_format(texture,(texture_size, texture_size),"cuda")
tex = tex.cpu().numpy()
processed_texture = (tex * 255).astype(np.uint8)
pil_texture = Image.fromarray(processed_texture)
return pil_texture
def get_filename_list(folder_name: str):
files = [f for f in os.listdir(folder_name)]
return files
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def numpy2pil(image):
return Image.fromarray(np.clip(255. * image.squeeze(), 0, 255).astype(np.uint8))
def convert_pil_images_to_tensor(images):
tensor_array = []
for image in images:
tensor_array.append(pil2tensor(image))
return tensor_array
def convert_tensor_images_to_pil(images):
pil_array = []
for image in images:
pil_array.append(tensor2pil(image))
return pil_array
class MetaData:
def __init__(self):
self.camera_config = None
self.albedos = None
self.mrs = None
self.albedos_upscaled = None
self.mrs_upscaled = None
self.mesh_file = None
class Hy3DMeshGenerator:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (folder_paths.get_filename_list("diffusion_models"), {"tooltip": "These models are loaded from the 'ComfyUI/models/diffusion_models' -folder"}),
"image": ("IMAGE", {"tooltip": "Image to generate mesh from"}),
"steps": ("INT", {"default": 50, "min": 1, "max": 100, "step": 1, "tooltip": "Number of diffusion steps"}),
"guidance_scale": ("FLOAT", {"default": 5.0, "min": 1, "max": 30, "step": 0.1, "tooltip": "Guidance scale"}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"attention_mode": (["sdpa", "sageattn"], {"default": "sdpa"}),
},
}
RETURN_TYPES = ("HY3DLATENT",)
RETURN_NAMES = ("latents",)
FUNCTION = "loadmodel"
CATEGORY = "Hunyuan3D21Wrapper"
def loadmodel(self, model, image, steps, guidance_scale, seed, attention_mode):
device = mm.get_torch_device()
offload_device=mm.unet_offload_device()
seed = seed % (2**32)
#from .hy3dshape.hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline
#from .hy3dshape.hy3dshape.rembg import BackgroundRemover
#import torchvision.transforms as T
model_path = folder_paths.get_full_path("diffusion_models", model)
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_single_file(
config_path=os.path.join(script_directory, 'configs', 'dit_config_2_1.yaml'),
ckpt_path=model_path,
offload_device=offload_device,
attention_mode=attention_mode)
# to_pil = T.ToPILImage()
# image = to_pil(image[0].permute(2, 0, 1))
# if image.mode == 'RGB':
# rembg = BackgroundRemover()
# image = rembg(image)
image = tensor2pil(image)
latents = pipeline(
image=image,
num_inference_steps=steps,
guidance_scale=guidance_scale,
generator=torch.manual_seed(seed)
)
del pipeline
#del vae
mm.soft_empty_cache()
torch.cuda.empty_cache()
gc.collect()
return (latents,)
# class Hy3D21MultiViewsMeshGenerator:
# @classmethod
# def INPUT_TYPES(s):
# return {
# "required": {
# "model": (folder_paths.get_filename_list("diffusion_models"), {"tooltip": "These models are loaded from the 'ComfyUI/models/diffusion_models' -folder"}),
# "steps": ("INT", {"default": 50, "min": 1, "max": 100, "step": 1, "tooltip": "Number of diffusion steps"}),
# "guidance_scale": ("FLOAT", {"default": 5.0, "min": 1, "max": 30, "step": 0.1, "tooltip": "Guidance scale"}),
# "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
# "attention_mode": (["sdpa", "sageattn"], {"default": "sdpa"}),
# },
# "optional":{
# "front": ("IMAGE", {"tooltip": "front image"}),
# "left": ("IMAGE", {"tooltip": "left image"}),
# "back": ("IMAGE", {"tooltip": "back image"}),
# "right": ("IMAGE", {"tooltip": "right image"}),
# },
# }
# RETURN_TYPES = ("HY3DLATENT",)
# RETURN_NAMES = ("latents",)
# FUNCTION = "loadmodel"
# CATEGORY = "Hunyuan3D21Wrapper"
# def loadmodel(self, model, steps, guidance_scale, seed, attention_mode, front = None, left = None, back = None, right = None):
# device = mm.get_torch_device()
# offload_device=mm.unet_offload_device()
# seed = seed % (2**32)
# #from .hy3dshape.hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline
# #from .hy3dshape.hy3dshape.rembg import BackgroundRemover
# #import torchvision.transforms as T
# model_path = folder_paths.get_full_path("diffusion_models", model)
# pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_single_file(
# config_path=os.path.join(script_directory, 'configs', 'dit_config_2_1_mv.yaml'),
# ckpt_path=model_path,
# offload_device=offload_device,
# attention_mode=attention_mode)
# # to_pil = T.ToPILImage()
# # image = to_pil(image[0].permute(2, 0, 1))
# # if image.mode == 'RGB':
# # rembg = BackgroundRemover()
# # image = rembg(image)
# if front is not None:
# front = tensor2pil(front)
# if left is not None:
# left = tensor2pil(left)
# if right is not None:
# right = tensor2pil(right)
# if back is not None:
# back = tensor2pil(back)
# view_dict = {
# 'front': front,
# 'left': left,
# 'right': right,
# 'back': back
# }
# latents = pipeline(
# image=view_dict,
# num_inference_steps=steps,
# guidance_scale=guidance_scale,
# generator=torch.manual_seed(seed)
# )
# del pipeline
# #del vae
# mm.soft_empty_cache()
# torch.cuda.empty_cache()
# gc.collect()
# return (latents,)
class Hy3DMultiViewsGenerator:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"trimesh": ("TRIMESH",),
"camera_config": ("HY3D21CAMERA",),
"view_size": ("INT", {"default": 512, "min": 512, "max":1024, "step":256}),
"image": ("IMAGE", {"tooltip": "Image to generate mesh from"}),
"steps": ("INT", {"default": 10, "min": 1, "max": 100, "step": 1, "tooltip": "Number of steps"}),
"guidance_scale": ("FLOAT", {"default": 3.0, "min": 1, "max": 10, "step": 0.1, "tooltip": "Guidance scale"}),
"texture_size": ("INT", {"default":1024,"min":512,"max":4096,"step":512}),
"unwrap_mesh": ("BOOLEAN", {"default":True}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
},
}
RETURN_TYPES = ("HY3DPIPELINE", "IMAGE","IMAGE","IMAGE","IMAGE","HY3D21CAMERA","HY3D21METADATA",)
RETURN_NAMES = ("pipeline", "albedo","mr","positions","normals","camera_config", "metadata")
FUNCTION = "genmultiviews"
CATEGORY = "Hunyuan3D21Wrapper"
def genmultiviews(self, trimesh, camera_config, view_size, image, steps, guidance_scale, texture_size, unwrap_mesh, seed):
device = mm.get_torch_device()
offload_device=mm.unet_offload_device()
seed = seed % (2**32)
conf = Hunyuan3DPaintConfig(view_size, camera_config["selected_camera_azims"], camera_config["selected_camera_elevs"], camera_config["selected_view_weights"], camera_config["ortho_scale"], texture_size)
paint_pipeline = Hunyuan3DPaintPipeline(conf)
image = tensor2pil(image)
temp_folder_path = os.path.join(comfy_path, "temp")
os.makedirs(temp_folder_path, exist_ok=True)
temp_output_path = os.path.join(temp_folder_path, "textured_mesh.obj")
albedo, mr, normal_maps, position_maps = paint_pipeline(mesh=trimesh, image_path=image, output_mesh_path=temp_output_path, num_steps=steps, guidance_scale=guidance_scale, unwrap=unwrap_mesh, seed=seed)
albedo_tensor = hy3dpaintimages_to_tensor(albedo)
mr_tensor = hy3dpaintimages_to_tensor(mr)
normals_tensor = hy3dpaintimages_to_tensor(normal_maps)
positions_tensor = hy3dpaintimages_to_tensor(position_maps)
return (paint_pipeline, albedo_tensor, mr_tensor, positions_tensor, normals_tensor, camera_config,)
class Hy3DBakeMultiViews:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"pipeline": ("HY3DPIPELINE", ),
"camera_config": ("HY3D21CAMERA", ),
"albedo": ("IMAGE", ),
"mr": ("IMAGE", )
},
}
RETURN_TYPES = ("HY3DPIPELINE", "NPARRAY", "NPARRAY", "NPARRAY", "NPARRAY", "IMAGE", "IMAGE",)
RETURN_NAMES = ("pipeline", "albedo", "albedo_mask", "mr", "mr_mask", "albedo_texture", "mr_texture",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, pipeline, camera_config, albedo, mr):
albedo = convert_tensor_images_to_pil(albedo)
mr = convert_tensor_images_to_pil(mr)
texture, mask, texture_mr, mask_mr = pipeline.bake_from_multiview(albedo,mr,camera_config["selected_camera_elevs"], camera_config["selected_camera_azims"], camera_config["selected_view_weights"])
texture_pil = convert_ndarray_to_pil(texture)
#mask_pil = convert_ndarray_to_pil(mask)
texture_mr_pil = convert_ndarray_to_pil(texture_mr)
#mask_mr_pil = convert_ndarray_to_pil(mask_mr)
texture_tensor = pil2tensor(texture_pil)
#mask_tensor = pil2tensor(mask_pil)
texture_mr_tensor = pil2tensor(texture_mr_pil)
#mask_mr_tensor = pil2tensor(mask_mr_pil)
return (pipeline, texture, mask, texture_mr, mask_mr, texture_tensor, texture_mr_tensor)
class Hy3DInPaint:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"pipeline": ("HY3DPIPELINE", ),
"albedo": ("NPARRAY", ),
"albedo_mask": ("NPARRAY", ),
"mr": ("NPARRAY", ),
"mr_mask": ("NPARRAY",),
"output_mesh_name": ("STRING",),
},
}
RETURN_TYPES = ("IMAGE","IMAGE","TRIMESH", "STRING",)
RETURN_NAMES = ("albedo", "mr", "trimesh", "output_glb_path")
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
OUTPUT_NODE = True
def process(self, pipeline, albedo, albedo_mask, mr, mr_mask, output_mesh_name):
#albedo = tensor2pil(albedo)
#albedo_mask = tensor2pil(albedo_mask)
#mr = tensor2pil(mr)
#mr_mask = tensor2pil(mr_mask)
vertex_inpaint = True
method = "NS"
albedo, mr = pipeline.inpaint(albedo, albedo_mask, mr, mr_mask, vertex_inpaint, method)
pipeline.set_texture_albedo(albedo)
pipeline.set_texture_mr(mr)
temp_folder_path = os.path.join(comfy_path, "temp")
os.makedirs(temp_folder_path, exist_ok=True)
output_mesh_path = os.path.join(temp_folder_path, f"{output_mesh_name}.obj")
output_temp_path = pipeline.save_mesh(output_mesh_path)
output_glb_path = os.path.join(comfy_path, "output", f"{output_mesh_name}.glb")
shutil.copyfile(output_temp_path, output_glb_path)
trimesh = Trimesh.load(output_glb_path, force="mesh")
texture_pil = convert_ndarray_to_pil(albedo)
texture_mr_pil = convert_ndarray_to_pil(mr)
texture_tensor = pil2tensor(texture_pil)
texture_mr_tensor = pil2tensor(texture_mr_pil)
output_glb_path = f"{output_mesh_name}.glb"
pipeline.clean_memory()
del pipeline
mm.soft_empty_cache()
torch.cuda.empty_cache()
gc.collect()
return (texture_tensor, texture_mr_tensor, trimesh, output_glb_path)
class Hy3D21CameraConfig:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"camera_azimuths": ("STRING", {"default": "0, 90, 180, 270, 0, 180", "multiline": False}),
"camera_elevations": ("STRING", {"default": "0, 0, 0, 0, 90, -90", "multiline": False}),
"view_weights": ("STRING", {"default": "1, 0.1, 0.5, 0.1, 0.05, 0.05", "multiline": False}),
"ortho_scale": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 2.0, "step": 0.01}),
},
}
RETURN_TYPES = ("HY3D21CAMERA",)
RETURN_NAMES = ("camera_config",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, camera_azimuths, camera_elevations, view_weights, ortho_scale):
angles_list = list(map(int, camera_azimuths.replace(" ", "").split(',')))
elevations_list = list(map(int, camera_elevations.replace(" ", "").split(',')))
weights_list = list(map(float, view_weights.replace(" ", "").split(',')))
camera_config = {
"selected_camera_azims": angles_list,
"selected_camera_elevs": elevations_list,
"selected_view_weights": weights_list,
"ortho_scale": ortho_scale,
}
return (camera_config,)
class Hy3D21VAELoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model_name": (folder_paths.get_filename_list("vae"), {"tooltip": "These models are loaded from 'ComfyUI/models/vae'"}),
},
"optional":{
"vae_config": ("HY3D21VAECONFIG",),
}
}
RETURN_TYPES = ("HY3DVAE",)
RETURN_NAMES = ("vae",)
FUNCTION = "loadmodel"
CATEGORY = "Hunyuan3D21Wrapper"
def loadmodel(self, model_name, vae_config=None):
device = mm.get_torch_device()
offload_device=mm.unet_offload_device()
model_path = folder_paths.get_full_path("vae", model_name)
vae_sd = load_torch_file(model_path)
if(vae_config==None):
vae_config = {
'num_latents': 4096,
'embed_dim': 64,
'num_freqs': 8,
'include_pi': False,
'heads': 16,
'width': 1024,
'num_encoder_layers': 8,
'num_decoder_layers': 16,
'qkv_bias': False,
'qk_norm': True,
'scale_factor': 1.0039506158752403,
'geo_decoder_mlp_expand_ratio': 4,
'geo_decoder_downsample_ratio': 1,
'geo_decoder_ln_post': True,
'point_feats': 4,
'pc_size': 81920,
'pc_sharpedge_size': 0
}
vae = ShapeVAE(**vae_config)
vae.load_state_dict(vae_sd)
vae.eval().to(torch.float16)
return (vae,)
class Hy3D21VAEConfig:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"num_latents": ("INT", {"default": 4096, "min":0, "max":256000}),
"embed_dim": ("INT", {"default": 64, "min":0, "max":256000}),
"num_freqs": ("INT", {"default": 8, "min":0, "max":256000}),
"include_pi": ("BOOLEAN", {"default": False}),
"heads": ("INT", {"default":16, "min":0, "max":256000}),
"width": ("INT", {"default":1024, "min":0, "max":256000}),
"num_encoder_layers": ("INT", {"default":8, "min":0, "max":256000}),
"num_decoder_layers": ("INT", {"default":16, "min":0, "max":256000}),
"qkv_bias": ("BOOLEAN", {"default":False}),
"qk_norm": ("BOOLEAN", {"default":True}),
"scale_factor": ("FLOAT", {"default":1.0039506158752403}),
"geo_decoder_mlp_expand_ratio": ("INT", {"default":4, "min":0, "max":256000}),
"geo_decoder_downsample_ratio": ("INT", {"default":1, "min":0, "max":256000}),
"geo_decoder_ln_post": ("BOOLEAN", {"default":True}),
"point_feats": ("INT", {"default":4, "min":0, "max":256000}),
"pc_size": ("INT", {"default":81920, "min":0, "max":256000}),
"pc_sharpedge_size": ("INT", {"default":0, "min":0, "max":256000}),
},
}
RETURN_TYPES = ("HY3D21VAECONFIG",)
RETURN_NAMES = ("vae_config",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, num_latents, embed_dim, num_freqs, include_pi, heads, width, num_encoder_layers, num_decoder_layers, qkv_bias, qk_norm, scale_factor, geo_decoder_mlp_expand_ratio, geo_decoder_downsample_ratio, geo_decoder_ln_post, point_feats, pc_size, pc_sharpedge_size):
vae_config = {
"num_latents": num_latents,
"embed_dim": embed_dim,
"num_freqs": num_freqs,
"include_pi": include_pi,
"heads":heads,
"width":width,
"num_encoder_layers":num_encoder_layers,
"num_decoder_layers":num_decoder_layers,
"qkv_bias":qkv_bias,
"qk_norm":qk_norm,
"scale_factor":scale_factor,
"geo_decoder_mlp_expand_ratio":geo_decoder_mlp_expand_ratio,
"geo_decoder_downsample_ratio":geo_decoder_downsample_ratio,
"geo_decoder_ln_post":geo_decoder_ln_post,
"point_feats":point_feats,
"pc_size":pc_size,
"pc_sharpedge_size":pc_sharpedge_size
}
return (vae_config,)
class Hy3D21VAEDecode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"vae": ("HY3DVAE",),
"latents": ("HY3DLATENT", ),
"box_v": ("FLOAT", {"default": 1.01, "min": -10.0, "max": 10.0, "step": 0.001}),
"octree_resolution": ("INT", {"default": 384, "min": 8, "max": 4096, "step": 8}),
"num_chunks": ("INT", {"default": 8000, "min": 1, "max": 10000000, "step": 1, "tooltip": "Number of chunks to process at once, higher values use more memory, but make the process faster"}),
"mc_level": ("FLOAT", {"default": 0, "min": -1.0, "max": 1.0, "step": 0.0001}),
"mc_algo": (["mc", "dmc"], {"default": "mc"}),
},
"optional": {
"enable_flash_vdm": ("BOOLEAN", {"default": True}),
"force_offload": ("BOOLEAN", {"default": False, "tooltip": "Offloads the model to the offload device once the process is done."}),
}
}
RETURN_TYPES = ("TRIMESH",)
RETURN_NAMES = ("trimesh",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, vae, latents, box_v, octree_resolution, mc_level, num_chunks, mc_algo, enable_flash_vdm, force_offload):
device = mm.get_torch_device()
offload_device = mm.unet_offload_device()
mm.soft_empty_cache()
torch.cuda.empty_cache()
vae.to(device)
vae.enable_flashvdm_decoder(enabled=enable_flash_vdm, mc_algo=mc_algo)
latents = vae.decode(latents)
outputs = vae.latents2mesh(
latents,
output_type='trimesh',
bounds=box_v,
mc_level=mc_level,
num_chunks=num_chunks,
octree_resolution=octree_resolution,
mc_algo=mc_algo,
enable_pbar=True
)[0]
if force_offload==True:
vae.to(offload_device)
outputs.mesh_f = outputs.mesh_f[:, ::-1]
mesh_output = Trimesh.Trimesh(outputs.mesh_v, outputs.mesh_f)
print(f"Decoded mesh with {mesh_output.vertices.shape[0]} vertices and {mesh_output.faces.shape[0]} faces")
#del pipeline
del vae
mm.soft_empty_cache()
torch.cuda.empty_cache()
gc.collect()
return (mesh_output, )
class Hy3D21ResizeImages:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"width": ("INT", {"default":1024, "min":16, "max":8192} ),
"height": ("INT", {"default":1024, "min":16, "max":8192} ),
"sampling": (["NEAREST","LANCZOS","BILINEAR","BICUBIC","BOX","HAMMING"], {"default":"BICUBIC"})
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, images, width, height, sampling):
if sampling=='NEAREST':
resampling = Image.Resampling.NEAREST
elif sampling=='LANCZOS':
resampling = Image.Resampling.LANCZOS
elif sampling=='BILINEAR':
resampling = Image.Resampling.BILINEAR
elif sampling=='BICUBIC':
resampling = Image.Resampling.BICUBIC
elif sampling=='BOX':
resampling = Image.Resampling.BOX
elif sampling=='HAMMING':
resampling = Image.Resampling.HAMMING
else:
raise Exception('Unknown sampling')
if isinstance(images, List):
for i in range(len(images)):
if isinstance(images[i], torch.Tensor):
images[i] = tensor2pil(images[i])
images[i] = images[i].resize((width,height), resampling)
images[i] = pil2tensor(images[i])
elif isinstance(images, torch.Tensor):
pil_images = convert_tensor_images_to_pil(images)
for index, img in enumerate(pil_images):
img = img.resize((width,height), resampling)
pil_images[index] = img
tensors = hy3dpaintimages_to_tensor(pil_images)
return (tensors,)
elif isinstance(images, Image):
images = images.resize((width,height), resampling)
images = pil2tensor(images)
else:
raise Exception("Unsupported images format")
return (images, )
class Hy3D21LoadImageWithTransparency:
@classmethod
def INPUT_TYPES(s):
input_dir = folder_paths.get_input_directory()
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
files = folder_paths.filter_files_content_types(files, ["image"])
return {"required":
{"image": (sorted(files), {"image_upload": True})},
}
CATEGORY = "Hunyuan3D21Wrapper"
RETURN_TYPES = ("IMAGE", "MASK", "IMAGE", )
RETURN_NAMES = ("image", "mask", "image_with_alpha")
FUNCTION = "load_image"
def load_image(self, image):
image_path = folder_paths.get_annotated_filepath(image)
img = node_helpers.pillow(Image.open, image_path)
output_images = []
output_masks = []
output_images_ori = []
w, h = None, None
excluded_formats = ['MPO']
for i in ImageSequence.Iterator(img):
i = node_helpers.pillow(ImageOps.exif_transpose, i)
output_images_ori.append(pil2tensor(i))
if i.mode == 'I':
i = i.point(lambda i: i * (1 / 255))
image = i.convert("RGB")
if len(output_images) == 0:
w = image.size[0]
h = image.size[1]
if image.size[0] != w or image.size[1] != h:
continue
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
elif i.mode == 'P' and 'transparency' in i.info:
mask = np.array(i.convert('RGBA').getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
output_images.append(image)
output_masks.append(mask.unsqueeze(0))
if len(output_images) > 1 and img.format not in excluded_formats:
output_image = torch.cat(output_images, dim=0)
output_mask = torch.cat(output_masks, dim=0)
output_image_ori = torch.cat(output_images_ori, dim=0)
else:
output_image = output_images[0]
output_mask = output_masks[0]
output_image_ori = output_images_ori[0]
return (output_image, output_mask, output_image_ori)
@classmethod
def IS_CHANGED(s, image):
image_path = folder_paths.get_annotated_filepath(image)
m = hashlib.sha256()
with open(image_path, 'rb') as f:
m.update(f.read())
return m.digest().hex()
@classmethod
def VALIDATE_INPUTS(s, image):
if not folder_paths.exists_annotated_filepath(image):
return "Invalid image file: {}".format(image)
return True
class Hy3D21PostprocessMesh:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"trimesh": ("TRIMESH",),
"remove_floaters": ("BOOLEAN", {"default": True}),
"remove_degenerate_faces": ("BOOLEAN", {"default": True}),
"reduce_faces": ("BOOLEAN", {"default": True}),
"max_facenum": ("INT", {"default": 40000, "min": 1, "max": 10000000, "step": 1}),
"smooth_normals": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("TRIMESH",)
RETURN_NAMES = ("trimesh",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, trimesh, remove_floaters, remove_degenerate_faces, reduce_faces, max_facenum, smooth_normals):
new_mesh = trimesh.copy()
if remove_floaters:
new_mesh = FloaterRemover()(new_mesh)
print(f"Removed floaters, resulting in {new_mesh.vertices.shape[0]} vertices and {new_mesh.faces.shape[0]} faces")
if remove_degenerate_faces:
new_mesh = DegenerateFaceRemover()(new_mesh)
print(f"Removed degenerate faces, resulting in {new_mesh.vertices.shape[0]} vertices and {new_mesh.faces.shape[0]} faces")
if reduce_faces:
new_mesh = FaceReducer()(new_mesh, max_facenum=max_facenum)
print(f"Reduced faces, resulting in {new_mesh.vertices.shape[0]} vertices and {new_mesh.faces.shape[0]} faces")
if smooth_normals:
new_mesh.vertex_normals = Trimesh.smoothing.get_vertices_normals(new_mesh)
return (new_mesh, )
class Hy3D21ExportMesh:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"trimesh": ("TRIMESH",),
"filename_prefix": ("STRING", {"default": "3D/Hy3D"}),
"file_format": (["glb", "obj", "ply", "stl", "3mf", "dae"],),
},
"optional": {
"save_file": ("BOOLEAN", {"default": True}),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("glb_path",)
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
OUTPUT_NODE = True
def process(self, trimesh, filename_prefix, file_format, save_file=True):
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, folder_paths.get_output_directory())
output_glb_path = Path(full_output_folder, f'{filename}_{counter:05}_.{file_format}')
output_glb_path.parent.mkdir(exist_ok=True)
if save_file:
trimesh.export(output_glb_path, file_type=file_format)
relative_path = Path(subfolder) / f'{filename}_{counter:05}_.{file_format}'
else:
temp_file = Path(full_output_folder, f'hy3dtemp_.{file_format}')
trimesh.export(temp_file, file_type=file_format)
relative_path = Path(subfolder) / f'hy3dtemp_.{file_format}'
return (str(relative_path), )
class Hy3D21MeshUVWrap:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"trimesh": ("TRIMESH",),
},
}
RETURN_TYPES = ("TRIMESH", )
RETURN_NAMES = ("trimesh", )
FUNCTION = "process"
CATEGORY = "Hunyuan3D21Wrapper"
def process(self, trimesh):
trimesh = mesh_uv_wrap(trimesh)
return (trimesh,)
class Hy3D21LoadMesh:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"glb_path": ("STRING", {"default": "", "tooltip": "The glb path with mesh to load."}),
}
}
RETURN_TYPES = ("TRIMESH",)
RETURN_NAMES = ("trimesh",)
OUTPUT_TOOLTIPS = ("The glb model with mesh to texturize.",)
FUNCTION = "load"
CATEGORY = "Hunyuan3D21Wrapper"
DESCRIPTION = "Loads a glb model from the given path."
def load(self, glb_path):
if not os.path.exists(glb_path):
glb_path = os.path.join(folder_paths.get_input_directory(), glb_path)
trimesh = Trimesh.load(glb_path, force="mesh")
return (trimesh,)
class Hy3D21IMRemesh:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"trimesh": ("TRIMESH",),
"merge_vertices": ("BOOLEAN", {"default": True}),
"vertex_count": ("INT", {"default": 10000, "min": 100, "max": 10000000, "step": 1}),
"smooth_iter": ("INT", {"default": 8, "min": 0, "max": 100, "step": 1}),
"align_to_boundaries": ("BOOLEAN", {"default": True}),
"triangulate_result": ("BOOLEAN", {"default": True}),
"max_facenum": ("INT", {"default": 40000, "min": 1, "max": 10000000, "step": 1}),
},