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
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
#!/usr/bin/env python3
"""
HO3D 模型规范化工具
统一坐标系约定,为多视角渲染做准备

支持 PyTorch DataLoader 多线程并行处理
"""

import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import trimesh
import os
import time
from scipy.spatial.transform import Rotation
from pathlib import Path
from typing import Optional, List, Dict, Any
from tqdm import tqdm

class HO3DModelNormalizer:
    def __init__(self, output_coordinate_system: str = "z_up_finger_z"):
        """HO3D/Contact 模型标准化器

        内部分析仍按 Y-up 约定进行:
            +Y: 上方向 (Up) - 手腕到指尖
            +Z: 前方向 (Forward) - 手掌法向量
            +X: 右方向 (Right) - 拇指到小指

        参数:
            output_coordinate_system:
                - "y_up"         : 最终 OBJ 仍保持 Y-up
                - "z_up_finger_z": 最终 OBJ 为 Z-up, 手指沿 +Z (推荐给 InstantMesh)
        """
        self.output_coordinate_system = output_coordinate_system
        self.coordinate_convention = {
            'up_axis': 'Y',      # 手腕到指尖方向
            'forward_axis': 'Z', # 手掌朝向
            'right_axis': 'X'    # 拇指到小指方向
        }
    
    def load_mesh(self, obj_path):
        """加载OBJ模型"""
        try:
            mesh = trimesh.load(obj_path)
            if hasattr(mesh, 'vertices'):
                return mesh
            else:
                # 处理多个mesh的情况
                combined_vertices = []
                combined_faces = []
                face_offset = 0
                
                for m in mesh.geometry.values():
                    combined_vertices.append(m.vertices)
                    combined_faces.append(m.faces + face_offset)
                    face_offset += len(m.vertices)
                
                vertices = np.vstack(combined_vertices)
                faces = np.vstack(combined_faces)
                return trimesh.Trimesh(vertices=vertices, faces=faces)
                
        except Exception as e:
            print(f"加载模型失败 {obj_path}: {e}")
            return None
    
    def analyze_hand_orientation(self, hand_vertices):
        """
        分析手部模型的主要朝向
        返回主轴方向向量
        """
        # 计算边界框
        bbox_min = hand_vertices.min(axis=0)
        bbox_max = hand_vertices.max(axis=0)
        bbox_size = bbox_max - bbox_min
        
        # 使用PCA找到主要方向
        centered_vertices = hand_vertices - hand_vertices.mean(axis=0)
        cov_matrix = np.cov(centered_vertices.T)
        eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)
        
        # 按特征值排序
        sorted_indices = np.argsort(eigenvalues)[::-1]
        principal_axes = eigenvectors[:, sorted_indices]
        
        return {
            'bbox_size': bbox_size,
            'center': hand_vertices.mean(axis=0),
            'principal_axes': principal_axes,
            'eigenvalues': eigenvalues[sorted_indices]
        }
    
    def detect_hand_palm_normal(self, hand_vertices, hand_faces):
        """
        检测手掌法向量方向
        """
        mesh = trimesh.Trimesh(vertices=hand_vertices, faces=hand_faces)
        
        # 计算面法向量
        face_normals = mesh.face_normals
        face_areas = mesh.area_faces
        
        # 加权平均法向量(按面积加权)
        weighted_normal = np.average(face_normals, axis=0, weights=face_areas)
        weighted_normal = weighted_normal / np.linalg.norm(weighted_normal)
        
        return weighted_normal

    def compute_wrist_to_fingertip_direction(self, hand_vertices):
        """
        计算手腕到指尖的方向向量
        """
        # 使用手部顶点的边界框来估计手腕到指尖方向
        # 假设手部顶点按照MANO模型的顺序排列

        # 方法1: 使用主成分分析
        centered_vertices = hand_vertices - hand_vertices.mean(axis=0)
        cov_matrix = np.cov(centered_vertices.T)
        eigenvalues, eigenvectors = np.linalg.eigh(cov_matrix)

        # 最大特征值对应的特征向量通常是手的主要延伸方向
        main_direction = eigenvectors[:, -1]  # 最大特征值对应的特征向量

        # 方法2: 使用几何分析 - 找到最远的两个点
        distances = np.linalg.norm(hand_vertices[:, None] - hand_vertices[None, :], axis=2)
        max_dist_indices = np.unravel_index(np.argmax(distances), distances.shape)
        point1, point2 = hand_vertices[max_dist_indices[0]], hand_vertices[max_dist_indices[1]]
        geometric_direction = point2 - point1
        geometric_direction = geometric_direction / np.linalg.norm(geometric_direction)

        # 选择与主成分方向一致的方向
        if np.dot(main_direction, geometric_direction) < 0:
            main_direction = -main_direction

        return main_direction

    def validate_coordinate_system(self, target_x, target_y, target_z, hand_vertices):
        """
        验证并调整坐标系,确保符合约定
        +Y: 上方向 (手腕到指尖) - 主要延伸方向
        +Z: 前方向 (手掌法向量)
        +X: 右方向 (拇指到小指)
        """
        # 检查是否为右手坐标系 Y × Z = X
        cross_product = np.cross(target_y, target_z)
        if np.dot(cross_product, target_x) < 0:
            # 如果不是右手坐标系,翻转X轴
            target_x = -target_x
            print("⚠️  调整X轴方向以确保右手坐标系")

        # 验证Y轴是否为主要延伸方向
        hand_center = hand_vertices.mean(axis=0)

        # 计算沿各轴的投影范围
        x_projections = np.dot(hand_vertices - hand_center, target_x)
        y_projections = np.dot(hand_vertices - hand_center, target_y)
        z_projections = np.dot(hand_vertices - hand_center, target_z)

        x_range = np.max(x_projections) - np.min(x_projections)
        y_range = np.max(y_projections) - np.min(y_projections)
        z_range = np.max(z_projections) - np.min(z_projections)

        print(f"📏 各轴投影范围:")
        print(f"   X轴范围: {x_range:.4f}")
        print(f"   Y轴范围: {y_range:.4f}")
        print(f"   Z轴范围: {z_range:.4f}")

        # Y轴应该是最大的延伸方向
        if y_range < max(x_range, z_range):
            print("⚠️  警告: Y轴不是最大延伸方向,可能需要调整")
        else:
            print("✅ Y轴确实是主要延伸方向")

        print(f"\\n✅ 坐标系验证完成:")
        print(f"   X轴 (拇指到小指): {target_x}")
        print(f"   Y轴 (手腕到指尖): {target_y}")
        print(f"   Z轴 (手掌法向量): {target_z}")

        return target_x, target_y, target_z

    def compute_normalization_transform(self, hand_vertices, hand_faces, object_vertices=None):
        """
        计算规范化变换矩阵
        严格按照坐标系约定: +Y=Up(手腕到指尖), +Z=Forward(手掌法向量), +X=Right(拇指到小指)
        """
        # 分析手部朝向
        hand_analysis = self.analyze_hand_orientation(hand_vertices)

        # 检测手掌法向量
        palm_normal = self.detect_hand_palm_normal(hand_vertices, hand_faces)

        # 重新构建目标坐标系 - 根据用户反馈调整
        # 用户反馈: 前应该是左,后应该是右,上下是对的
        # 这意味着我们需要重新映射坐标轴

        # 首先确定Y轴: 手腕到指尖方向 (主要延伸方向) - 保持不变
        target_y = self.compute_wrist_to_fingertip_direction(hand_vertices)
        target_y = target_y / np.linalg.norm(target_y)

        # 重新定义Z轴: 原来的X轴方向 (这样前后会变成左右)
        # 先计算原来的手掌法向量
        palm_normal_orig = palm_normal / np.linalg.norm(palm_normal)

        # 计算原来的X轴方向
        temp_z = palm_normal_orig - np.dot(palm_normal_orig, target_y) * target_y
        temp_z = temp_z / np.linalg.norm(temp_z)
        temp_x = np.cross(target_y, temp_z)
        temp_x = temp_x / np.linalg.norm(temp_x)

        # 新的坐标系: 交换X和Z的角色
        target_z = temp_x  # 原来的X轴变成新的Z轴
        target_x = -temp_z  # 原来的Z轴的负方向变成新的X轴

        print(f"🔄 重新映射坐标轴: 前后↔左右")

        # 验证并调整方向,确保符合约定
        target_x, target_y, target_z = self.validate_coordinate_system(
            target_x, target_y, target_z, hand_vertices
        )
        
        # 构建旋转矩阵
        # 目标坐标系的轴向量作为行,构成旋转矩阵
        # 这样变换后,原来的X轴变成target_x方向,Y轴变成target_y方向,Z轴变成target_z方向
        rotation_matrix = np.row_stack([target_x, target_y, target_z])
        
        # 计算平移(移到原点)
        if object_vertices is not None:
            all_vertices = np.vstack([hand_vertices, object_vertices])
        else:
            all_vertices = hand_vertices
            
        center = all_vertices.mean(axis=0)
        
        # 构建4x4变换矩阵
        transform_matrix = np.eye(4)
        transform_matrix[:3, :3] = rotation_matrix
        transform_matrix[:3, 3] = -rotation_matrix @ center  # 先旋转再平移
        
        # 重新构建target_axes用于返回
        target_axes = np.column_stack([target_x, target_y, target_z])

        return {
            'transform_matrix': transform_matrix,
            'rotation_matrix': rotation_matrix,
            'translation': -center,
            'center': center,
            'target_axes': target_axes,
            'palm_normal': palm_normal,
            'analysis': hand_analysis
        }
    
    def apply_transform(self, vertices, transform_matrix):
        """应用变换矩阵到顶点"""
        # 转换为齐次坐标
        vertices_homo = np.hstack([vertices, np.ones((len(vertices), 1))])
        # 应用变换
        transformed_homo = (transform_matrix @ vertices_homo.T).T
        # 返回3D坐标
        return transformed_homo[:, :3]
    
    def normalize_combined_model(self, hand_obj_path, output_dir, verbose=True):
        """
        规范化组合模型(手+物体)

        参数:
            hand_obj_path: 输入模型路径
            output_dir: 输出目录
            verbose: 是否打印详细日志(默认True,并行处理时设为False)
        """
        if verbose:
            print(f"正在规范化模型: {hand_obj_path}")
        
        # 加载组合模型
        combined_mesh = self.load_mesh(hand_obj_path)
        if combined_mesh is None:
            return None
        
        # 解析手部和物体部分(基于OBJ文件的组结构)
        hand_vertices, hand_faces, object_vertices, object_faces = self.parse_combined_obj(hand_obj_path)
        
        if hand_vertices is None:
            print("无法解析手部和物体部分")
            return None
        
        # 计算规范化变换
        transform_info = self.compute_normalization_transform(
            hand_vertices, hand_faces, object_vertices
        )
        
        # 应用变换
        normalized_hand = self.apply_transform(hand_vertices, transform_info['transform_matrix'])
        normalized_object = self.apply_transform(object_vertices, transform_info['transform_matrix'])
        
        # 保存规范化后的模型
        output_path = Path(output_dir) / "normalized_hand_object_combined.obj"
        self.save_normalized_obj(
            normalized_hand, hand_faces,
            normalized_object, object_faces,
            output_path, transform_info,
            verbose=verbose
        )
        
        return {
            'output_path': output_path,
            'transform_info': transform_info,
            'original_vertices': {
                'hand': hand_vertices,
                'object': object_vertices
            },
            'normalized_vertices': {
                'hand': normalized_hand,
                'object': normalized_object
            }
        }
    
    def parse_combined_obj(self, obj_path):
        """
        解析组合OBJ文件,分离手部和物体
        基于固定的顶点数量分割:前778个顶点是手部,其余是物体
        """
        try:
            # 使用trimesh加载完整模型
            mesh = trimesh.load(obj_path)
            vertices = mesh.vertices
            faces = mesh.faces

            print(f"📊 加载模型: {len(vertices)}个顶点, {len(faces)}个面片")

            # 基于固定数量分割
            hand_vertex_count = 778

            if len(vertices) < hand_vertex_count:
                print(f"❌ 顶点数量不足: {len(vertices)} < {hand_vertex_count}")
                return None, None, None, None

            # 分离顶点
            hand_vertices = vertices[:hand_vertex_count]
            object_vertices = vertices[hand_vertex_count:]

            # 分离面片
            hand_faces = []
            object_faces = []

            for face in faces:
                # 检查面片的所有顶点是否都属于手部
                if np.all(face < hand_vertex_count):
                    hand_faces.append(face)
                # 检查面片的所有顶点是否都属于物体
                elif np.all(face >= hand_vertex_count):
                    # 调整物体面片的索引,使其从0开始
                    adjusted_face = face - hand_vertex_count
                    object_faces.append(adjusted_face)
                # 跨越手部和物体的面片(通常不应该存在)
                else:
                    print(f"⚠️  发现跨越手部和物体的面片: {face}")

            hand_faces = np.array(hand_faces) if hand_faces else None
            object_faces = np.array(object_faces) if object_faces else None

            print(f"✅ 分离完成:")
            print(f"   手部: {len(hand_vertices)}个顶点, {len(hand_faces) if hand_faces is not None else 0}个面片")
            print(f"   物体: {len(object_vertices)}个顶点, {len(object_faces) if object_faces is not None else 0}个面片")

            return hand_vertices, hand_faces, object_vertices, object_faces

        except Exception as e:
            print(f"❌ 解析OBJ文件失败: {e}")
            import traceback
            traceback.print_exc()
            return None, None, None, None
    
    def save_normalized_obj(
        self,
        hand_vertices,
        hand_faces,
        object_vertices,
        object_faces,
        output_path,
        transform_info,
        verbose=True,
    ):
        """保存规范化后的 OBJ 文件

        说明:
            - 只在磁盘上保存最终标准化后的 OBJ
            - 不再写入 .transform.npz 等中间变换信息文件
        """
        os.makedirs(os.path.dirname(output_path), exist_ok=True)

        # 根据配置决定最终导出的坐标系
        coord = getattr(self, "output_coordinate_system", "y_up")
        hand_vertices_out = hand_vertices
        object_vertices_out = object_vertices

        if coord == "z_up_finger_z":
            # 在内部 Y-up 标准化的基础上,再旋转到 Z-up 且手指朝向 +Z
            # 这里使用和渲染侧一致的约定:
            #   X' = X
            #   Y' = -Z
            #   Z' = Y
            R = np.array(
                [
                    [1.0, 0.0, 0.0],
                    [0.0, 0.0, -1.0],
                    [0.0, 1.0, 0.0],
                ],
                dtype=np.float32,
            )
            hand_vertices_out = hand_vertices_out @ R.T
            object_vertices_out = object_vertices_out @ R.T

        with open(output_path, "w") as f:
            # 写入头部信息
            f.write("# Normalized HO3D Hand-Object Model\n")
            if coord == "z_up_finger_z":
                f.write("# Coordinate Convention: Z-up, fingers along +Z (InstantMesh)\n")
            else:
                f.write("# Coordinate Convention: +Y=Up, +Z=Forward, +X=Right\n")
            f.write("# Transform applied for multi-view rendering\n\n")

            # 写入手部顶点
            f.write("# Hand vertices\n")
            for vertex in hand_vertices_out:
                f.write(f"v {vertex[0]:.6f} {vertex[1]:.6f} {vertex[2]:.6f}\n")

            # 写入物体顶点
            f.write("\n# Object vertices\n")
            for vertex in object_vertices_out:
                f.write(f"v {vertex[0]:.6f} {vertex[1]:.6f} {vertex[2]:.6f}\n")

            # 写入手部面片
            f.write("\n# Hand faces\n")
            f.write("g hand\n")
            for face in hand_faces:
                f.write(f"f {face[0] + 1} {face[1] + 1} {face[2] + 1}\n")

            # 写入物体面片
            f.write("\n# Object faces\n")
            f.write("g object\n")
            vertex_offset = len(hand_vertices)
            for face in object_faces:
                f.write(
                    f"f {face[0] + vertex_offset + 1} "
                    f"{face[1] + vertex_offset + 1} "
                    f"{face[2] + vertex_offset + 1}\n"
                )

        # 不再保存 transform.npz,只在日志中提示 OBJ 路径
        if verbose:
            print(f"规范化模型已保存: {output_path}")


# ====================== DataLoader 并行处理实现 ======================

# Worker 进程级别的全局标准化器缓存
_WORKER_NORMALIZER_CACHE = {}


def _get_worker_normalizer(output_coordinate_system: str) -> HO3DModelNormalizer:
    """为每个 worker 进程懒加载一个 HO3DModelNormalizer 实例"""
    global _WORKER_NORMALIZER_CACHE
    if output_coordinate_system not in _WORKER_NORMALIZER_CACHE:
        _WORKER_NORMALIZER_CACHE[output_coordinate_system] = HO3DModelNormalizer(
            output_coordinate_system=output_coordinate_system
        )
    return _WORKER_NORMALIZER_CACHE[output_coordinate_system]


def _process_single_mesh(task: dict, output_coordinate_system: str) -> dict:
    """在 DataLoader worker 中执行的单个网格标准化逻辑

    参数:
        task: 包含 sequence, frame_id, input_mesh, output_obj 的字典
        output_coordinate_system: 输出坐标系

    返回:
        包含处理结果的字典
    """
    import tempfile
    import shutil

    seq = task["sequence"]
    frame_id = task["frame_id"]
    input_mesh = task["input_mesh"]
    output_obj = task["output_obj"]
    output_dir = os.path.dirname(output_obj)

    # 已存在的文件直接跳过(不需要先创建目录)
    if os.path.exists(output_obj):
        return {
            **task,
            "success": True,
            "skipped": True,
            "error": None,
        }

    # 使用临时目录避免多进程冲突
    temp_dir = None
    try:
        # 创建唯一的临时目录
        temp_dir = tempfile.mkdtemp(prefix=f"normalize_{seq}_{frame_id}_")

        normalizer = _get_worker_normalizer(output_coordinate_system)
        # 并行处理时禁用详细日志,避免输出混乱
        result = normalizer.normalize_combined_model(input_mesh, temp_dir, verbose=False)

        if not result:
            return {
                **task,
                "success": False,
                "skipped": False,
                "error": "normalize_combined_model returned None",
            }

        default_output = os.path.join(temp_dir, "normalized_hand_object_combined.obj")
        if not os.path.exists(default_output):
            return {
                **task,
                "success": False,
                "skipped": False,
                "error": "normalized_hand_object_combined.obj not found in temp dir",
            }

        # 成功后才创建输出目录,避免产生空目录
        os.makedirs(output_dir, exist_ok=True)

        # 移动到目标位置
        shutil.move(default_output, output_obj)

        return {
            **task,
            "success": True,
            "skipped": False,
            "error": None,
        }

    except Exception as e:
        return {
            **task,
            "success": False,
            "skipped": False,
            "error": str(e),
        }
    finally:
        # 清理临时目录
        if temp_dir and os.path.exists(temp_dir):
            try:
                shutil.rmtree(temp_dir)
            except Exception:
                pass


class NormalizeTaskDataset(Dataset):
    """用于 DataLoader 的标准化任务 Dataset

    每个 __getitem__ 会在 worker 进程中执行一个网格的标准化。
    """

    def __init__(self, tasks: List[dict], output_coordinate_system: str):
        self.tasks = tasks
        self.output_coordinate_system = output_coordinate_system

    def __len__(self):
        return len(self.tasks)

    def __getitem__(self, idx):
        task = self.tasks[idx]
        return _process_single_mesh(task, self.output_coordinate_system)


def build_tasks_from_directory(
    input_dir: str,
    output_dir: str,
    max_sequences: Optional[int] = None,
    max_frames_per_sequence: Optional[int] = None,
) -> List[dict]:
    """从输入目录构建所有需要处理的任务列表

    参数:
        input_dir: 输入目录,包含多个序列子目录
        output_dir: 输出目录
        max_sequences: 最大序列数(用于测试)
        max_frames_per_sequence: 每个序列最大帧数(用于测试)

    返回:
        任务列表,每个任务包含 sequence, frame_id, input_mesh, output_obj
    """
    input_path = Path(input_dir)
    output_path = Path(output_dir)

    if not input_path.exists():
        print(f"❌ 输入目录不存在: {input_dir}")
        return []

    tasks = []
    sequences = sorted([d for d in input_path.iterdir() if d.is_dir()])

    if max_sequences is not None:
        sequences = sequences[:max_sequences]

    for seq_dir in sequences:
        seq_name = seq_dir.name

        # 查找该序列下的所有 .ply 和 .obj 文件
        mesh_files = list(seq_dir.glob("*.ply")) + list(seq_dir.glob("*.obj"))
        mesh_files = sorted(mesh_files)

        if max_frames_per_sequence is not None:
            mesh_files = mesh_files[:max_frames_per_sequence]

        # 创建输出目录
        seq_output_dir = output_path / seq_name
        seq_output_dir.mkdir(parents=True, exist_ok=True)

        for mesh_file in mesh_files:
            frame_id = mesh_file.stem  # 文件名(不含扩展名)
            output_obj = seq_output_dir / f"normalized_{frame_id}.obj"

            tasks.append({
                "sequence": seq_name,
                "frame_id": frame_id,
                "input_mesh": str(mesh_file),
                "output_obj": str(output_obj),
            })

    return tasks


def parallel_normalize(
    input_dir: str,
    output_dir: str,
    output_coordinate_system: str = "z_up_finger_z",
    num_workers: int = 4,
    max_sequences: Optional[int] = None,
    max_frames_per_sequence: Optional[int] = None,
) -> bool:
    """使用 PyTorch DataLoader 并行标准化

    参数:
        input_dir: 输入目录
        output_dir: 输出目录
        output_coordinate_system: 输出坐标系
        num_workers: DataLoader worker 数量(CPU 进程数)
        max_sequences: 最大序列数(用于测试)
        max_frames_per_sequence: 每个序列最大帧数(用于测试)

    返回:
        是否成功处理至少一个文件
    """
    print("=" * 60)
    print("🚀 DataLoader 并行标准化模式")
    print(f"📁 输入目录: {input_dir}")
    print(f"📁 输出目录: {output_dir}")
    print(f"📐 输出坐标系: {output_coordinate_system}")
    print(f"🔧 并行进程数: {num_workers}")
    if max_sequences:
        print(f"🧪 测试模式: 最多处理 {max_sequences} 个序列")
    if max_frames_per_sequence:
        print(f"🧪 测试模式: 每序列最多 {max_frames_per_sequence} 帧")
    print("=" * 60)

    # 构建任务列表
    tasks = build_tasks_from_directory(
        input_dir=input_dir,
        output_dir=output_dir,
        max_sequences=max_sequences,
        max_frames_per_sequence=max_frames_per_sequence,
    )

    if not tasks:
        print("❌ 没有找到可处理的网格文件")
        return False

    print(f"📦 共构建 {len(tasks)} 个任务")

    # 创建 Dataset 和 DataLoader
    dataset = NormalizeTaskDataset(tasks, output_coordinate_system)

    # 自定义 collate_fn 直接返回结果列表
    def collate_fn(batch):
        return batch

    dataloader = DataLoader(
        dataset,
        batch_size=1,
        shuffle=False,
        num_workers=num_workers,
        collate_fn=collate_fn,
        prefetch_factor=2 if num_workers > 0 else None,
    )

    # 统计计数器
    success_count = 0
    skipped_count = 0
    failed_count = 0
    failed_tasks = []

    start_time = time.time()

    # 使用 tqdm 显示进度条
    for batch_results in tqdm(dataloader, desc="处理进度", unit="帧"):
        for result in batch_results:
            if result["success"]:
                if result["skipped"]:
                    skipped_count += 1
                else:
                    success_count += 1
            else:
                failed_count += 1
                failed_tasks.append({
                    "sequence": result["sequence"],
                    "frame_id": result["frame_id"],
                    "error": result["error"],
                })

    elapsed_time = time.time() - start_time

    # 打印统计结果
    print("\n" + "=" * 60)
    print("📊 并行标准化完成!")
    print(f"✅ 成功处理: {success_count} 个")
    print(f"⏭️  跳过已存在: {skipped_count} 个")
    print(f"❌ 失败: {failed_count} 个")
    print(f"⏱️  总耗时: {elapsed_time:.1f} 秒")
    if success_count + skipped_count > 0:
        avg_time = elapsed_time / (success_count + skipped_count + failed_count)
        print(f"📈 平均速度: {avg_time:.3f} 秒/帧")

    if failed_tasks and len(failed_tasks) <= 10:
        print("\n❌ 失败任务详情:")
        for ft in failed_tasks:
            print(f"  - {ft['sequence']}/{ft['frame_id']}: {ft['error']}")
    elif failed_tasks:
        print(f"\n❌ 失败任务太多,只显示前10个:")
        for ft in failed_tasks[:10]:
            print(f"  - {ft['sequence']}/{ft['frame_id']}: {ft['error']}")

    print("=" * 60)

    return success_count > 0 or skipped_count > 0


def main():
    """批量规范化所有重建结果 - 支持多数据集和并行处理"""
    import argparse

    parser = argparse.ArgumentParser(
        description="HO3D 手-物体模型标准化工具(支持多线程并行处理)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例用法:
  # 单个文件标准化
  python model_normalizer.py --input path/to/file.obj --output path/to/output_dir

  # 目录批量并行处理(推荐!)
  python model_normalizer.py --input /path/to/input_dir --output /path/to/output_dir --parallel --workers 8

  # 测试模式(每序列处理3帧,共处理5个序列)
  python model_normalizer.py --input dir --output out --parallel --workers 4 --max-sequences 5 --max-frames 3

  # 批量处理(使用配置文件)
  python model_normalizer.py --batch

  # 指定输出坐标系
  python model_normalizer.py --input input.obj --output out/ --coord z_up_finger_z
        """,
    )
    parser.add_argument(
        "--input", "-i", type=str, help="输入文件/目录路径"
    )
    parser.add_argument(
        "--output", "-o", type=str, help="输出目录路径"
    )
    parser.add_argument(
        "--parallel", "-p",
        action="store_true",
        help="启用 DataLoader 多线程并行处理(用于目录批量处理)",
    )
    parser.add_argument(
        "--workers", "-w",
        type=int,
        default=4,
        help="并行处理的 worker 数量(默认: 4)",
    )
    parser.add_argument(
        "--max-sequences",
        type=int,
        default=None,
        help="最大处理序列数(用于测试)",
    )
    parser.add_argument(
        "--max-frames",
        type=int,
        default=None,
        help="每序列最大处理帧数(用于测试)",
    )
    parser.add_argument(
        "--batch",
        action="store_true",
        help="批量处理模式(使用 simple_multiview_config.py 配置)",
    )
    parser.add_argument(
        "--coord",
        type=str,
        default=None,
        choices=["y_up", "z_up_finger_z"],
        help="输出坐标系(默认: z_up_finger_z)",
    )

    args = parser.parse_args()

    # 导入配置
    try:
        import sys as _sys
        import os as _os

        # 确保可以从 render 根目录导入 simple_multiview_config
        render_root = _os.path.dirname(_os.path.dirname(__file__))
        if render_root not in _sys.path:
            _sys.path.insert(0, render_root)

        from simple_multiview_config import (
            get_dataset_config,
            PROCESSING_CONFIG,
            NORMALIZATION_OUTPUT_CONFIG,
        )

        dataset_config = get_dataset_config()
        config_coord = NORMALIZATION_OUTPUT_CONFIG.get("coordinate_system", "z_up_finger_z")
    except ImportError as e:
        # 向后兼容:如果没有新配置,使用默认设置
        print(f"⚠️  无法导入配置: {e}")
        dataset_config = {
            "input_dir": "ho3d_reconstruction_results",
            "output_dir": "ho3d_reconstruction_results",
            "input_file": "hand_object_combined.obj",
            "output_subdir": "clean_combined",
            "normalized_subdir": "normalized",
        }
        config_coord = "z_up_finger_z"
        print("⚠️  使用默认配置 (向后兼容模式)")

    # 确定最终使用的坐标系
    coord = args.coord if args.coord else config_coord

    # 并行目录批量处理模式(推荐)
    if args.input and args.output and args.parallel:
        input_path = Path(args.input)
        if input_path.is_dir():
            success = parallel_normalize(
                input_dir=args.input,
                output_dir=args.output,
                output_coordinate_system=coord,
                num_workers=args.workers,
                max_sequences=args.max_sequences,
                max_frames_per_sequence=args.max_frames,
            )
            return 0 if success else 1
        else:
            print("❌ 并行模式需要 --input 为目录路径")
            return 1

    # 单文件模式
    elif args.input and args.output:
        input_path = Path(args.input)

        # 如果 input 是目录,使用单线程批量处理
        if input_path.is_dir():
            print("=" * 60)
            print("🔧 目录批量标准化模式(单线程)")
            print(f"📁 输入目录: {args.input}")
            print(f"📁 输出目录: {args.output}")
            print(f"📐 输出坐标系: {coord}")
            print("💡 提示: 使用 --parallel 启用多线程加速")
            print("=" * 60)

            normalizer = HO3DModelNormalizer(output_coordinate_system=coord)
            output_path = Path(args.output)

            success_count = 0
            fail_count = 0

            sequences = sorted([d for d in input_path.iterdir() if d.is_dir()])
            for seq_dir in sequences:
                mesh_files = list(seq_dir.glob("*.ply")) + list(seq_dir.glob("*.obj"))
                for mesh_file in sorted(mesh_files):
                    seq_output_dir = output_path / seq_dir.name
                    seq_output_dir.mkdir(parents=True, exist_ok=True)

                    output_obj = seq_output_dir / f"normalized_{mesh_file.stem}.obj"
                    if output_obj.exists():
                        print(f"⏭️  跳过: {output_obj}")
                        success_count += 1
                        continue

                    print(f"处理: {mesh_file}")
                    result = normalizer.normalize_combined_model(
                        str(mesh_file), str(seq_output_dir)
                    )

                    if result:
                        # 重命名输出文件
                        default_out = seq_output_dir / "normalized_hand_object_combined.obj"
                        if default_out.exists():
                            default_out.rename(output_obj)
                        success_count += 1
                    else:
                        fail_count += 1

            print("\n" + "=" * 60)
            print(f"📊 批量处理完成: 成功 {success_count} 个,失败 {fail_count} 个")
            print("=" * 60)
            return 0 if fail_count == 0 else 1

        # 单文件处理
        else:
            print("=" * 60)
            print("🔧 单文件标准化模式")
            print(f"📄 输入文件: {args.input}")
            print(f"📁 输出目录: {args.output}")
            print(f"📐 输出坐标系: {coord}")
            print("=" * 60)

            normalizer = HO3DModelNormalizer(output_coordinate_system=coord)
            result = normalizer.normalize_combined_model(args.input, args.output)

            if result:
                print(f"\n✅ 标准化完成!")
                print(f"   输出文件: {result['output_path']}")
                return 0
            else:
                print(f"\n❌ 标准化失败")
                return 1

    # 批量处理模式(使用配置文件)
    elif args.batch or (not args.input and not args.output):
        print("=" * 60)
        print("🔧 批量标准化模式(配置文件)")
        print(f"📂 当前数据集: {PROCESSING_CONFIG.get('active_dataset', 'N/A')}")
        print(f"📁 输入目录: {dataset_config['input_dir']}")
        print(f"📁 输出目录: {dataset_config['output_dir']}")
        print(f"📐 输出坐标系: {coord}")
        print("=" * 60)

        normalizer = HO3DModelNormalizer(output_coordinate_system=coord)

        # 处理所有重建结果
        input_dir = Path(dataset_config["input_dir"])
        output_base_dir = Path(dataset_config["output_dir"])

        if not input_dir.exists():
            print(f"❌ 输入目录不存在: {input_dir}")
            return 1

        success_count = 0
        fail_count = 0

        for sequence_dir in input_dir.iterdir():
            if sequence_dir.is_dir():
                combined_obj = sequence_dir / dataset_config["input_file"]
                if combined_obj.exists():
                    print(f"\n处理序列: {sequence_dir.name}")

                    # 创建输出目录结构
                    output_sequence_dir = (
                        output_base_dir
                        / dataset_config["output_subdir"]
                        / sequence_dir.name
                    )
                    normalized_dir = (
                        output_sequence_dir / dataset_config["normalized_subdir"]
                    )
                    normalized_dir.mkdir(parents=True, exist_ok=True)

                    # 执行规范化
                    result = normalizer.normalize_combined_model(
                        str(combined_obj), str(normalized_dir)
                    )

                    if result:
                        print(f"✅ 规范化完成: {sequence_dir.name}")
                        success_count += 1
                    else:
                        print(f"❌ 规范化失败: {sequence_dir.name}")
                        fail_count += 1

        print("\n" + "=" * 60)
        print(f"📊 批量处理完成: 成功 {success_count} 个,失败 {fail_count} 个")
        print("=" * 60)
        return 0 if fail_count == 0 else 1

    else:
        parser.print_help()
        print("\n❌ 错误: 请指定 --input 和 --output,或使用 --batch 模式")
        return 1


if __name__ == "__main__":
    import sys
    sys.exit(main())