File size: 57,432 Bytes
73a87be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
#!/usr/bin/env python3
"""
Blender Python script: render a prepared SMPL-X vertex sequence.

Run with Blender:
    blender -b blender/template_smplx_uv.blend \
      --python scripts/render_blender_sequence.py -- \
      --sequence-dir cache/seq_000001 \
      --out-dir renders/seq_000001 \
      --manifest assets/asset_manifest.json \
      --smplx-object SMPLX_BODY \
      --camera-name Camera \
      --width 832 \
      --height 480 \
      --frames 0:120:1 \
      --seed 42

Important:
    The opened .blend must contain a SMPL-X mesh object with correct UVs.
    This script updates the object's vertex coordinates per frame.
"""

from __future__ import annotations

import argparse
import importlib
import json
import math
import random
import sys
from pathlib import Path
from typing import Any

import bpy
import mathutils
import numpy as np

SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

import render_helpers as rh

DEFAULT_ADDON_DIR = Path(__file__).resolve().parents[1] / "addons" / "smplx_blender_addon"


def parse_blender_args() -> argparse.Namespace:
    """Parse args after '--' when called from Blender."""
    argv = sys.argv
    if "--" in argv:
        argv = argv[argv.index("--") + 1 :]
    else:
        argv = []

    parser = argparse.ArgumentParser()
    parser.add_argument("--sequence-dir", required=True, type=Path)
    parser.add_argument("--out-dir", required=True, type=Path)
    parser.add_argument("--manifest", default=None, type=Path)
    parser.add_argument("--render-config", default=None, type=Path)
    parser.add_argument("--smplx-object", default="SMPLX_BODY")
    parser.add_argument("--render-mesh-source", choices=["addon", "template"], default="addon")
    parser.add_argument("--addon-dir", default=DEFAULT_ADDON_DIR, type=Path)
    parser.add_argument("--model-variant", default=None)
    parser.add_argument("--uv-version", default=None)
    parser.add_argument("--uv-donor-object", default="SMPLX_UPRIGHT_CAMERA_REFERENCE")
    parser.add_argument("--camera-name", default="Camera")
    parser.add_argument("--width", type=int, default=832)
    parser.add_argument("--height", type=int, default=480)
    parser.add_argument("--frames", default=None, help="Format start:end:stride. Example 0:120:1. Default all frames.")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--engine", default="BLENDER_EEVEE", help="BLENDER_EEVEE or CYCLES.")
    parser.add_argument("--texture-node-name", default="BASE_COLOR_IMAGE")
    parser.add_argument("--force-identity", action="store_true", default=True)
    parser.add_argument("--no-force-identity", dest="force_identity", action="store_false")
    parser.add_argument("--fps", type=int, default=16)
    parser.add_argument("--crf", type=int, default=8)
    parser.add_argument("--no-video", action="store_true")
    parser.add_argument("--motion-blur", action="store_true", help="Enable Blender render motion blur. Default is off.")
    parser.add_argument("--camera-radius-min", type=float, default=2.2)
    parser.add_argument("--camera-radius-max", type=float, default=4.0)
    parser.add_argument("--camera-height-min", type=float, default=0.8)
    parser.add_argument("--camera-height-max", type=float, default=1.8)
    parser.add_argument("--target-height", type=float, default=0.9)
    parser.add_argument("--focal-length-min", type=float, default=35.0)
    parser.add_argument("--focal-length-max", type=float, default=70.0)
    parser.add_argument("--disable-script-lights", action="store_true")
    parser.add_argument("--texture-per-frame", action="store_true")
    parser.add_argument("--hair-enabled", action="store_true", help="Force hair rendering when render_config has a hair_item.")
    parser.add_argument("--disable-hair", action="store_true", help="Disable hair even if render_config selects one.")
    parser.add_argument("--hair-head-indices", default=None, type=Path, help="Optional JSON list or {'indices': [...]} for head anchor vertices.")
    parser.add_argument("--hair-unit-scale", type=float, default=0.01, help="Scale imported BEDLAM groom coordinates from centimeters to meters.")
    parser.add_argument("--hand-only-video", action="store_true", help="Render hand-only reference outputs after main RGB.")
    parser.add_argument("--hand-index-file", default=None, type=Path, help="Optional JSON with hand vertex indices.")
    parser.add_argument("--hand-vertex-groups", default="Lhand,Rhand")
    parser.add_argument("--hand-face-rule", choices=["any", "majority", "all"], default="majority")
    parser.add_argument("--hand-bg", choices=["black", "transparent"], default="black")
    parser.add_argument("--hand-outputs", default="rgb", help="Comma-separated hand outputs: rgb,mask,depth.")
    parser.add_argument("--hand-light-mode", choices=["scene", "flat"], default="flat")
    parser.add_argument("--hand-flat-strength", type=float, default=1.25)
    parser.add_argument("--hand-depth-near", type=float, default=None)
    parser.add_argument("--hand-depth-far", type=float, default=None)
    parser.add_argument("--hand-depth-margin", type=float, default=0.05)
    parser.add_argument("--hand-depth-invert", action="store_true")
    return parser.parse_args(argv)


def parse_frame_spec(frame_spec: str | None, num_frames: int) -> list[int]:
    """Parse frame range string start:end:stride."""
    if frame_spec is None:
        return list(range(num_frames))

    parts = frame_spec.split(":")
    if len(parts) not in (2, 3):
        raise ValueError("--frames must be start:end or start:end:stride")

    start = int(parts[0])
    end = int(parts[1])
    stride = int(parts[2]) if len(parts) == 3 else 1

    if stride <= 0:
        raise ValueError("Frame stride must be positive.")
    if start < 0 or end > num_frames or start >= end:
        raise ValueError(f"Invalid frame range {frame_spec} for num_frames={num_frames}.")

    return list(range(start, end, stride))


def load_manifest(manifest_path: Path | None) -> dict:
    """Load asset manifest."""
    if manifest_path is None:
        return {"textures": []}
    if not manifest_path.exists():
        raise FileNotFoundError(f"Manifest not found: {manifest_path}")
    with open(manifest_path, "r", encoding="utf-8") as f:
        manifest = json.load(f)
    if "textures" not in manifest:
        raise KeyError("Manifest must contain a 'textures' list.")
    return manifest


def load_render_config(config_path: Path | None) -> dict:
    if config_path is None:
        return {}
    if not config_path.exists():
        raise FileNotFoundError(f"Render config not found: {config_path}")
    with open(config_path, "r", encoding="utf-8") as f:
        return json.load(f)


def first_mapping_node(world: bpy.types.World, preferred_name: str | None = None) -> bpy.types.Node:
    if not world.use_nodes or world.node_tree is None:
        raise RuntimeError(f"World '{world.name}' does not use nodes.")
    if preferred_name and preferred_name in world.node_tree.nodes:
        node = world.node_tree.nodes[preferred_name]
        if node.type != "MAPPING":
            raise RuntimeError(f"World node '{preferred_name}' is not a Mapping node.")
        return node
    for node in world.node_tree.nodes:
        if node.type == "MAPPING":
            return node
    raise RuntimeError(f"World '{world.name}' has no Mapping node.")


def apply_world_config(config: dict) -> dict:
    world_name = config.get("world_name")
    if not world_name:
        return {"enabled": False}

    source_world = bpy.data.worlds.get(world_name)
    if source_world is None:
        raise KeyError(f"World not found in blend: {world_name}")

    # Use a copy so the original datablock remains unchanged inside the session.
    world = source_world.copy()
    world.name = f"{source_world.name}__render"
    bpy.context.scene.world = world

    mapping = first_mapping_node(world, config.get("world_mapping_node"))
    rotation_degrees = float(config.get("world_rotation_z_degrees", 0.0))
    if "Rotation" not in mapping.inputs:
        raise RuntimeError(f"Mapping node '{mapping.name}' has no Rotation input.")
    mapping.inputs["Rotation"].default_value[2] = math.radians(rotation_degrees)

    return {
        "enabled": True,
        "source_world": source_world.name,
        "render_world": world.name,
        "mapping_node": mapping.name,
        "rotation_z_degrees": rotation_degrees,
    }


def enable_addon(addon_dir: Path) -> None:
    addon_dir = addon_dir.resolve()
    if not addon_dir.exists():
        raise FileNotFoundError(f"SMPL-X Blender addon not found: {addon_dir}")
    parent = addon_dir.parent
    if str(parent) not in sys.path:
        sys.path.insert(0, str(parent))
    module = importlib.import_module(addon_dir.name)
    try:
        module.register()
    except ValueError:
        pass


def create_addon_render_body(gender: str, model_variant: str, uv_version: str, addon_dir: Path) -> bpy.types.Object:
    enable_addon(addon_dir)
    if bpy.context.active_object is not None and bpy.context.active_object.mode != "OBJECT":
        bpy.ops.object.mode_set(mode="OBJECT")
    bpy.ops.object.select_all(action="DESELECT")
    wm_tool = bpy.context.window_manager.smplx_tool
    wm_tool.body_model = "smplx"
    wm_tool.smplx_gender = gender
    wm_tool.smplx_version = model_variant
    wm_tool.smplx_uv = uv_version
    wm_tool.smplx_handpose = "flat"
    result = bpy.ops.scene.smplx_add_gender()
    if "FINISHED" not in result:
        raise RuntimeError(f"bpy.ops.scene.smplx_add_gender failed: {result}")
    obj = bpy.context.view_layer.objects.active
    if obj is None or obj.type != "MESH":
        raise RuntimeError("SMPL-X addon did not create an active mesh object.")
    obj.name = "SMPLX_BODY_RENDER"
    obj["render_mesh_source"] = "smplx_blender_addon"
    if obj.parent is not None:
        obj.parent.hide_render = True
        obj.parent.hide_viewport = True
        obj.parent = None
    for modifier in list(obj.modifiers):
        obj.modifiers.remove(modifier)
    if obj.data.shape_keys is not None:
        bpy.ops.object.select_all(action="DESELECT")
        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)
        bpy.ops.object.shape_key_remove(all=True)
    return obj


def triangulated_faces(obj: bpy.types.Object) -> np.ndarray:
    faces: list[list[int]] = []
    for poly in obj.data.polygons:
        verts = [int(v) for v in poly.vertices]
        if len(verts) == 3:
            faces.append(verts)
        else:
            for i in range(1, len(verts) - 1):
                faces.append([verts[0], verts[i], verts[i + 1]])
    return np.asarray(faces, dtype=np.int32)


def validate_topology(obj: bpy.types.Object, sequence_dir: Path, expected_vertex_count: int) -> None:
    if len(obj.data.vertices) != expected_vertex_count:
        raise ValueError(
            f"Render mesh '{obj.name}' has {len(obj.data.vertices)} vertices, "
            f"but vertices.npy has {expected_vertex_count}."
        )
    if not obj.data.uv_layers.active:
        raise ValueError(f"Render mesh '{obj.name}' has no active UV map.")

    faces_path = sequence_dir / "faces.npy"
    if faces_path.exists():
        expected_faces = np.load(faces_path)
        actual_faces = triangulated_faces(obj)
        if expected_faces.shape != actual_faces.shape or not np.array_equal(expected_faces, actual_faces):
            raise ValueError(
                f"Render mesh topology does not match faces.npy: "
                f"mesh faces {actual_faces.shape}, cache faces {expected_faces.shape}."
            )


def same_mesh_topology(a: bpy.types.Object, b: bpy.types.Object) -> bool:
    if a.type != "MESH" or b.type != "MESH":
        return False
    if len(a.data.vertices) != len(b.data.vertices) or len(a.data.polygons) != len(b.data.polygons):
        return False
    for poly_a, poly_b in zip(a.data.polygons, b.data.polygons):
        if list(poly_a.vertices) != list(poly_b.vertices):
            return False
    return True


def copy_active_uv_by_loop(source: bpy.types.Object, target: bpy.types.Object) -> dict:
    if source.type != "MESH" or target.type != "MESH":
        raise TypeError("UV copy requires mesh objects.")
    source_uv = source.data.uv_layers.active
    if source_uv is None:
        raise RuntimeError(f"UV donor '{source.name}' has no active UV map.")
    if not same_mesh_topology(source, target):
        raise ValueError(f"UV donor '{source.name}' topology does not match render mesh '{target.name}'.")

    target_uv = target.data.uv_layers.get(source_uv.name) or target.data.uv_layers.new(name=source_uv.name)
    if len(target_uv.data) != len(source_uv.data):
        raise ValueError(
            f"UV loop count mismatch: donor {len(source_uv.data)}, target {len(target_uv.data)}."
        )
    for src_loop, dst_loop in zip(source_uv.data, target_uv.data):
        dst_loop.uv = src_loop.uv
    target.data.uv_layers.active = target_uv
    target["uv_donor_object"] = source.name
    target["uv_donor_layer"] = source_uv.name
    return {"enabled": True, "donor_object": source.name, "uv_layer": source_uv.name}


def find_uv_donor(preferred_name: str, target: bpy.types.Object) -> bpy.types.Object | None:
    preferred = bpy.data.objects.get(preferred_name) if preferred_name else None
    if preferred is not None and same_mesh_topology(preferred, target) and preferred.data.uv_layers.active:
        return preferred
    for obj in bpy.data.objects:
        if obj == target or obj.type != "MESH":
            continue
        if same_mesh_topology(obj, target) and obj.data.uv_layers.active:
            return obj
    return None


def find_hand_group_donor(expected_vertex_count: int, group_names: list[str], exclude: bpy.types.Object | None) -> bpy.types.Object | None:
    for obj in bpy.data.objects:
        if obj == exclude or obj.type != "MESH" or len(obj.data.vertices) != expected_vertex_count:
            continue
        names = {group.name for group in obj.vertex_groups}
        if all(name in names for name in group_names):
            return obj
    return None


def copy_vertex_groups_by_index(source: bpy.types.Object, target: bpy.types.Object, group_names: list[str]) -> None:
    for group_name in group_names:
        if group_name in target.vertex_groups:
            continue
        if group_name not in source.vertex_groups:
            raise KeyError(f"Missing vertex group '{group_name}' on donor mesh '{source.name}'.")
        source_group = source.vertex_groups[group_name]
        target_group = target.vertex_groups.new(name=group_name)
        for vertex in source.data.vertices:
            weight = None
            for membership in vertex.groups:
                if membership.group == source_group.index:
                    weight = membership.weight
                    break
            if weight is not None and weight > 0.0:
                target_group.add([vertex.index], float(weight), "ADD")


def hide_other_body_meshes(selected: bpy.types.Object, expected_vertex_count: int) -> None:
    for obj in bpy.data.objects:
        if obj == selected or obj.type != "MESH":
            continue
        if len(obj.data.vertices) == expected_vertex_count:
            obj.hide_render = True
            obj.hide_viewport = True


def ensure_camera(camera_name: str) -> bpy.types.Object:
    """Get or create a Blender camera."""
    if camera_name in bpy.data.objects:
        cam_obj = bpy.data.objects[camera_name]
        if cam_obj.type != "CAMERA":
            raise TypeError(f"Object '{camera_name}' exists but is not a camera.")
        return cam_obj

    cam_data = bpy.data.cameras.new(camera_name)
    cam_obj = bpy.data.objects.new(camera_name, cam_data)
    bpy.context.collection.objects.link(cam_obj)
    bpy.context.scene.camera = cam_obj
    return cam_obj


def look_at(obj: bpy.types.Object, target: mathutils.Vector) -> None:
    """Rotate object so its local -Z points to target."""
    direction = target - obj.location
    quat = direction.to_track_quat("-Z", "Y")
    obj.rotation_euler = quat.to_euler()


def randomize_camera(
    cam_obj: bpy.types.Object,
    rng: random.Random,
    radius_min: float,
    radius_max: float,
    height_min: float,
    height_max: float,
    target_height: float,
    focal_min: float,
    focal_max: float,
) -> None:
    """Set a random orbit camera around the body."""
    radius = rng.uniform(radius_min, radius_max)
    azimuth = rng.uniform(0.0, math.tau)
    height = rng.uniform(height_min, height_max)

    x = radius * math.cos(azimuth)
    y = radius * math.sin(azimuth)
    z = height

    cam_obj.location = (x, y, z)
    look_at(cam_obj, mathutils.Vector((0.0, 0.0, target_height)))
    cam_obj.data.lens = rng.uniform(focal_min, focal_max)
    cam_obj.data.sensor_fit = "AUTO"


def copy_camera_data(dst: bpy.types.Object, src: bpy.types.Object) -> None:
    if src.type != "CAMERA" or dst.type != "CAMERA":
        raise TypeError("copy_camera_data requires camera objects.")
    dst.matrix_world = src.matrix_world.copy()
    dst.data.type = src.data.type
    dst.data.lens = src.data.lens
    dst.data.sensor_width = src.data.sensor_width
    dst.data.sensor_height = src.data.sensor_height
    dst.data.sensor_fit = src.data.sensor_fit
    dst.data.shift_x = src.data.shift_x
    dst.data.shift_y = src.data.shift_y
    dst.data.clip_start = src.data.clip_start
    dst.data.clip_end = src.data.clip_end
    dst.data.display_size = src.data.display_size


def apply_camera_config(cam_obj: bpy.types.Object, config: dict) -> dict:
    preset_name = config.get("camera_preset_name")
    if not preset_name:
        return {"enabled": False}
    preset = bpy.data.objects.get(preset_name)
    if preset is None or preset.type != "CAMERA":
        raise KeyError(f"Camera preset not found: {preset_name}")

    copy_camera_data(cam_obj, preset)

    dolly = float(config.get("camera_dolly_meters", 0.0))
    roll_degrees = float(config.get("camera_roll_degrees", 0.0))

    forward = cam_obj.matrix_world.to_quaternion() @ mathutils.Vector((0.0, 0.0, -1.0))
    cam_obj.location = cam_obj.location + forward * dolly

    roll_matrix = mathutils.Matrix.Rotation(math.radians(roll_degrees), 4, "Z")
    cam_obj.matrix_world = cam_obj.matrix_world @ roll_matrix

    return {
        "enabled": True,
        "preset": preset.name,
        "collection": config.get("camera_collection"),
        "roll_degrees": roll_degrees,
        "dolly_meters": dolly,
        "local_forward_world": [float(v) for v in forward],
    }


def hide_scene_lights() -> list[str]:
    hidden = []
    for obj in bpy.data.objects:
        if obj.type == "LIGHT":
            obj.hide_render = True
            obj.hide_viewport = True
            hidden.append(obj.name)
    return hidden


def hide_background_planes() -> list[str]:
    hidden = []
    for obj in bpy.data.objects:
        if obj.type == "MESH" and "backgroundplane" in obj.name.lower():
            obj.hide_render = True
            obj.hide_viewport = True
            hidden.append(obj.name)
    return hidden


def setup_lights(rng: random.Random) -> None:
    """Create/update a simple randomized three-point-ish light setup."""
    light_names = ["Key_Light", "Fill_Light"]
    for name in light_names:
        if name in bpy.data.objects:
            bpy.data.objects.remove(bpy.data.objects[name], do_unlink=True)

    key_data = bpy.data.lights.new("Key_Light", type="AREA")
    key_obj = bpy.data.objects.new("Key_Light", key_data)
    bpy.context.collection.objects.link(key_obj)
    key_obj.location = (rng.uniform(-2.5, 2.5), rng.uniform(-3.0, -1.5), rng.uniform(2.0, 4.0))
    key_data.energy = rng.uniform(350.0, 900.0)
    key_data.size = rng.uniform(2.0, 5.0)

    fill_data = bpy.data.lights.new("Fill_Light", type="AREA")
    fill_obj = bpy.data.objects.new("Fill_Light", fill_data)
    bpy.context.collection.objects.link(fill_obj)
    fill_obj.location = (rng.uniform(-2.0, 2.0), rng.uniform(1.5, 3.0), rng.uniform(1.0, 3.0))
    fill_data.energy = rng.uniform(50.0, 250.0)
    fill_data.size = rng.uniform(3.0, 6.0)


def set_render_settings(width: int, height: int, engine: str, fps: int, motion_blur: bool) -> None:
    """Set render engine and resolution."""
    scene = bpy.context.scene
    scene.render.resolution_x = width
    scene.render.resolution_y = height
    scene.render.resolution_percentage = 100
    scene.render.pixel_aspect_x = 1.0
    scene.render.pixel_aspect_y = 1.0
    scene.render.image_settings.file_format = "PNG"
    scene.render.fps = int(fps)
    scene.render.use_motion_blur = bool(motion_blur)

    try:
        scene.render.engine = engine
    except TypeError:
        print(f"[WARN] Render engine {engine} not available. Falling back to BLENDER_EEVEE.")
        scene.render.engine = "BLENDER_EEVEE"

    # This pipeline lights bodies from an HDRI World and deliberately hides all
    # scene lights.  Raster shadow maps therefore add no useful lighting, while
    # dense Alembic grooms can exhaust EEVEE's virtual shadow pages and make a
    # frame 10-20x slower (or abort Blender).  Disable that unused path.
    if scene.render.engine == "BLENDER_EEVEE" and hasattr(scene, "eevee"):
        scene.eevee.use_shadows = False

    if scene.render.engine == "CYCLES":
        scene.cycles.samples = 32
        scene.cycles.use_denoising = True


def set_mesh_vertices(obj: bpy.types.Object, vertices: np.ndarray) -> None:
    """Replace mesh vertices with prepared SMPL-X vertices."""
    if obj.type != "MESH":
        raise TypeError(f"Object '{obj.name}' must be a MESH, got {obj.type}.")

    mesh = obj.data
    if len(mesh.vertices) != vertices.shape[0]:
        raise ValueError(
            f"Vertex count mismatch for '{obj.name}': template has {len(mesh.vertices)}, "
            f"vertices.npy has {vertices.shape[0]}. Use a matching SMPL-X UV mesh."
        )

    mesh.vertices.foreach_set("co", vertices.astype(np.float32).reshape(-1))
    mesh.update()


def mesh_vertices_array(obj: bpy.types.Object) -> np.ndarray:
    return np.asarray([vertex.co[:] for vertex in obj.data.vertices], dtype=np.float64)


def auto_head_anchor_indices(rest_vertices: np.ndarray, min_count: int = 80) -> np.ndarray:
    z = rest_vertices[:, 2]
    z_min = float(z.min())
    z_max = float(z.max())
    threshold = z_min + 0.82 * (z_max - z_min)
    indices = np.flatnonzero(z >= threshold)
    if indices.size < min_count:
        indices = np.argsort(z)[-min_count:]
    return np.asarray(indices, dtype=np.int32)


def load_head_anchor_indices(path: Path | None, rest_vertices: np.ndarray) -> np.ndarray:
    if path is None:
        return auto_head_anchor_indices(rest_vertices)
    if not path.exists():
        raise FileNotFoundError(f"Hair head index file not found: {path}")
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    indices = data.get("indices") if isinstance(data, dict) else data
    arr = np.asarray(indices, dtype=np.int32)
    if arr.ndim != 1 or arr.size < 3:
        raise ValueError("--hair-head-indices must contain at least 3 vertex indices.")
    if int(arr.min()) < 0 or int(arr.max()) >= rest_vertices.shape[0]:
        raise ValueError("--hair-head-indices contains out-of-range vertex indices.")
    return arr


def umeyama_similarity_matrix(source: np.ndarray, target: np.ndarray) -> mathutils.Matrix:
    if source.shape != target.shape or source.ndim != 2 or source.shape[1] != 3:
        raise ValueError("Hair transform source/target anchors must both have shape [N,3].")

    src_mean = source.mean(axis=0)
    dst_mean = target.mean(axis=0)
    src_centered = source - src_mean
    dst_centered = target - dst_mean
    variance = float((src_centered**2).sum() / source.shape[0])
    if variance <= 1e-12:
        return mathutils.Matrix.Identity(4)

    covariance = (dst_centered.T @ src_centered) / source.shape[0]
    u, singular_values, vt = np.linalg.svd(covariance)
    correction = np.eye(3)
    if np.linalg.det(u @ vt) < 0:
        correction[-1, -1] = -1.0
    rotation = u @ correction @ vt
    scale = float(np.sum(singular_values * np.diag(correction)) / variance)
    translation = dst_mean - scale * (rotation @ src_mean)

    matrix = mathutils.Matrix.Identity(4)
    for row in range(3):
        for col in range(3):
            matrix[row][col] = float(scale * rotation[row, col])
        matrix[row][3] = float(translation[row])
    return matrix


def set_input_if_present(node: bpy.types.Node, names: tuple[str, ...], value: Any) -> None:
    for name in names:
        if name in node.inputs:
            node.inputs[name].default_value = value
            return


def create_hair_material(color: list[float] | None, shader_mode: str = "hair_bsdf") -> bpy.types.Material:
    rgba = color if color is not None else [0.04, 0.025, 0.015, 1.0]
    mat = bpy.data.materials.new("BEDLAM_Hair_Material")
    mat.diffuse_color = tuple(float(v) for v in rgba)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    output = next((node for node in nodes if node.type == "OUTPUT_MATERIAL"), None)
    if output is None:
        output = nodes.new(type="ShaderNodeOutputMaterial")

    if shader_mode == "portrait_matte":
        # Stable EEVEE portrait material without the broad, tinted highlights
        # seen with Hair BSDF under some of the HDRI worlds.
        shader = next((node for node in nodes if node.type == "BSDF_PRINCIPLED"), None)
        if shader is None:
            shader = nodes.new(type="ShaderNodeBsdfPrincipled")
        set_input_if_present(shader, ("Base Color",), mat.diffuse_color)
        set_input_if_present(shader, ("Roughness",), 0.76)
        set_input_if_present(shader, ("Specular IOR Level", "Specular"), 0.16)
        set_input_if_present(shader, ("Coat Weight", "Coat"), 0.0)
        set_input_if_present(shader, ("Sheen Weight", "Sheen"), 0.08)
        resolved_shader_mode = "eevee_principled_matte_hair"
    else:
        # Preserve the original video pipeline's hair shader behavior.
        try:
            shader = nodes.new(type="ShaderNodeBsdfHairPrincipled")
            set_input_if_present(shader, ("Color", "Tint"), mat.diffuse_color)
            set_input_if_present(shader, ("Roughness",), 0.62)
            set_input_if_present(shader, ("Radial Roughness",), 0.78)
            set_input_if_present(shader, ("Random Color",), 0.18)
        except Exception:
            shader = next((node for node in nodes if node.type == "BSDF_PRINCIPLED"), None)
            if shader is None:
                shader = nodes.new(type="ShaderNodeBsdfPrincipled")
            set_input_if_present(shader, ("Base Color",), mat.diffuse_color)
            set_input_if_present(shader, ("Roughness",), 0.88)
            set_input_if_present(shader, ("Specular IOR Level", "Specular"), 0.22)
            set_input_if_present(shader, ("Sheen Weight", "Sheen"), 0.35)
        resolved_shader_mode = "principled_hair_bsdf_preferred"

    if shader is not None and "BSDF" in shader.outputs and "Surface" in output.inputs:
        links.new(shader.outputs["BSDF"], output.inputs["Surface"])
    mat["shader_model"] = resolved_shader_mode
    return mat


def import_hair_objects(
    render_config: dict,
    args: argparse.Namespace,
    rest_vertices: np.ndarray,
    anchor_indices: np.ndarray | None = None,
) -> tuple[list[bpy.types.Object], dict]:
    if args.disable_hair:
        return [], {"enabled": False, "reason": "disabled_by_arg"}
    hair_item = render_config.get("hair_item")
    enabled = bool(args.hair_enabled or render_config.get("hair_enabled"))
    if not enabled or not hair_item:
        return [], {
            "enabled": False,
            "reason": render_config.get("hair_disabled_reason") or "not_selected",
        }

    hair_path = Path(hair_item["path"])
    if not hair_path.exists():
        raise FileNotFoundError(f"Hair Alembic not found: {hair_path}")

    before = set(bpy.data.objects)
    result = bpy.ops.wm.alembic_import(filepath=str(hair_path))
    if "FINISHED" not in result:
        raise RuntimeError(f"bpy.ops.wm.alembic_import failed for hair: {result}")
    hair_objects = [obj for obj in bpy.data.objects if obj not in before]
    renderable = [obj for obj in hair_objects if obj.type in {"CURVES", "MESH"}]
    if not renderable:
        raise RuntimeError(f"Hair Alembic imported no renderable objects: {hair_path}")

    material = create_hair_material(
        render_config.get("hair_color"),
        getattr(args, "hair_shader_mode", "hair_bsdf"),
    )
    unit_scale_matrix = mathutils.Matrix.Scale(float(args.hair_unit_scale), 4)
    vertical_offset = float(getattr(args, "hair_vertical_offset", 0.0))
    alignment_matrix = mathutils.Matrix.Translation((0.0, 0.0, vertical_offset)) @ unit_scale_matrix
    for index, obj in enumerate(renderable):
        obj.name = f"BEDLAM_HAIR_{index:02d}_{obj.name}"
        obj.matrix_world = alignment_matrix @ obj.matrix_world
        if hasattr(obj.data, "materials"):
            obj.data.materials.clear()
            obj.data.materials.append(material)
        obj.hide_render = False
        obj.hide_viewport = False

    if anchor_indices is None:
        anchor_indices = load_head_anchor_indices(args.hair_head_indices, rest_vertices)
        anchor_mode = "file" if args.hair_head_indices else "auto_top_18_percent"
    else:
        anchor_indices = np.asarray(anchor_indices, dtype=np.int32)
        if anchor_indices.ndim != 1 or anchor_indices.size < 3:
            raise ValueError("Explicit hair anchor indices must contain at least 3 vertices")
        anchor_mode = "head_vertex_group"
    meta = {
        "enabled": True,
        "path": str(hair_path),
        "item": hair_item,
        "objects": [obj.name for obj in renderable],
        "material": material.name,
        "color": render_config.get("hair_color"),
        "anchor_mode": anchor_mode,
        "anchor_count": int(anchor_indices.size),
        "anchor_indices": anchor_indices.tolist(),
        "unit_scale": float(args.hair_unit_scale),
        "vertical_offset_meters": vertical_offset,
        "base_matrices": {obj.name: [[float(v) for v in row] for row in obj.matrix_world] for obj in renderable},
    }
    for obj in renderable:
        obj["hair_base_matrix"] = json.dumps(meta["base_matrices"][obj.name])
    return renderable, meta


def update_hair_transform(
    hair_objects: list[bpy.types.Object],
    hair_meta: dict,
    rest_vertices: np.ndarray,
    current_vertices: np.ndarray,
) -> None:
    if not hair_objects or not hair_meta.get("enabled"):
        return
    indices = np.asarray(hair_meta["anchor_indices"], dtype=np.int32)
    transform = umeyama_similarity_matrix(rest_vertices[indices], current_vertices[indices].astype(np.float64))
    base_matrices = hair_meta.get("base_matrices", {})
    for obj in hair_objects:
        base = mathutils.Matrix(base_matrices.get(obj.name, [[float(v) for v in row] for row in mathutils.Matrix.Identity(4)]))
        obj.matrix_world = transform @ base


def set_hair_visibility(hair_objects: list[bpy.types.Object], visible: bool) -> dict[str, tuple[bool, bool]]:
    state = {}
    for obj in hair_objects:
        state[obj.name] = (obj.hide_render, obj.hide_viewport)
        obj.hide_render = not visible
        obj.hide_viewport = not visible
    return state


def restore_hair_visibility(hair_objects: list[bpy.types.Object], state: dict[str, tuple[bool, bool]]) -> None:
    for obj in hair_objects:
        if obj.name in state:
            obj.hide_render, obj.hide_viewport = state[obj.name]


def resolve_smplx_object(name: str, expected_vertex_count: int) -> bpy.types.Object:
    """Resolve the body mesh by name, or auto-detect a compatible SMPL-X mesh."""
    if name in bpy.data.objects:
        obj = bpy.data.objects[name]
        if obj.type != "MESH":
            raise TypeError(f"Object '{name}' exists but is not a mesh.")
        return obj

    candidates = []
    for obj in bpy.data.objects:
        if obj.type != "MESH":
            continue
        if len(obj.data.vertices) != expected_vertex_count:
            continue
        group_names = {group.name for group in obj.vertex_groups}
        score = int("Lhand" in group_names) + int("Rhand" in group_names)
        candidates.append((score, obj.name, obj))

    if not candidates:
        raise KeyError(
            f"SMPL-X object '{name}' not found, and no mesh with "
            f"{expected_vertex_count} vertices was found in the current .blend file."
        )

    candidates.sort(key=lambda row: (-row[0], row[1]))
    selected = candidates[0][2]
    print(
        f"[WARN] SMPL-X object '{name}' not found. "
        f"Auto-selected '{selected.name}' with {expected_vertex_count} vertices."
    )
    return selected


def find_or_create_image_node(mat: bpy.types.Material, node_name: str) -> bpy.types.Node:
    """Find or create an image texture node connected to Principled base color."""
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links

    if node_name in nodes:
        node = nodes[node_name]
        if node.type != "TEX_IMAGE":
            raise TypeError(f"Node '{node_name}' exists but is not an Image Texture node.")
        return node

    tex_node = nodes.new(type="ShaderNodeTexImage")
    tex_node.name = node_name
    tex_node.label = node_name

    bsdf = None
    for node in nodes:
        if node.type == "BSDF_PRINCIPLED":
            bsdf = node
            break
    if bsdf is None:
        bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")

    # Blender 4.x uses input name 'Base Color'. Older versions also have it.
    if "Base Color" in bsdf.inputs:
        links.new(tex_node.outputs["Color"], bsdf.inputs["Base Color"])
    set_input_if_present(bsdf, ("Roughness",), 0.72)
    set_input_if_present(bsdf, ("Specular IOR Level", "Specular"), 0.28)
    set_input_if_present(bsdf, ("Sheen Weight", "Sheen"), 0.12)
    set_input_if_present(bsdf, ("Subsurface Weight", "Subsurface"), 0.025)

    output = None
    for node in nodes:
        if node.type == "OUTPUT_MATERIAL":
            output = node
            break
    if output is None:
        output = nodes.new(type="ShaderNodeOutputMaterial")

    if "BSDF" in bsdf.outputs and "Surface" in output.inputs:
        try:
            links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
        except RuntimeError:
            pass

    return tex_node


def load_image_node(nodes: bpy.types.Nodes, path: Path, name: str) -> bpy.types.Node:
    if not path.exists():
        raise FileNotFoundError(f"Texture not found: {path}")
    node = nodes.new(type="ShaderNodeTexImage")
    node.name = name
    node.label = name
    node.image = bpy.data.images.load(str(path), check_existing=True)
    return node


def create_layered_bedlam_material(texture_item: dict[str, Any], node_name: str) -> bpy.types.Material:
    """Create a layered skin/eye/cloth shader from BEDLAM SMPL-X texture paths."""
    skin_path = Path(texture_item["skin_path"])
    cloth_value = texture_item.get("clothing_overlay_path")
    cloth_path = Path(cloth_value) if cloth_value else None
    eye_value = texture_item.get("eye_path")
    eye_path = Path(eye_value) if eye_value else None

    mat = bpy.data.materials.new("SMPLX_BEDLAM_Layered_Material")
    mat.diffuse_color = (1.0, 1.0, 1.0, 1.0)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()

    output = nodes.new(type="ShaderNodeOutputMaterial")
    skin_bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
    cloth_bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
    mix_shader = nodes.new(type="ShaderNodeMixShader")

    skin_tex = load_image_node(nodes, skin_path, node_name)
    base_color_source = skin_tex.outputs["Color"]

    if eye_path is not None and eye_path.exists():
        eye_tex = load_image_node(nodes, eye_path, "BEDLAM_Eye_Overlay")
        eye_dark = nodes.new(type="ShaderNodeMix")
        eye_dark.data_type = "RGBA"
        eye_dark.factor_mode = "UNIFORM"
        eye_dark.inputs["Factor"].default_value = float(texture_item.get("eye_rgb_scale", 0.2))
        eye_dark.inputs[6].default_value = (0.0, 0.0, 0.0, 1.0)
        links.new(eye_tex.outputs["Color"], eye_dark.inputs[7])

        eye_mix = nodes.new(type="ShaderNodeMix")
        eye_mix.data_type = "RGBA"
        eye_mix.factor_mode = "UNIFORM"
        links.new(eye_tex.outputs["Alpha"], eye_mix.inputs["Factor"])
        links.new(base_color_source, eye_mix.inputs[6])
        links.new(eye_dark.outputs[2], eye_mix.inputs[7])
        base_color_source = eye_mix.outputs[2]

    links.new(base_color_source, skin_bsdf.inputs["Base Color"])
    set_input_if_present(skin_bsdf, ("Roughness",), 0.56)
    set_input_if_present(skin_bsdf, ("Specular IOR Level", "Specular"), 0.32)
    set_input_if_present(skin_bsdf, ("Subsurface Weight", "Subsurface"), 0.035)

    if cloth_path is not None and cloth_path.exists():
        cloth_tex = load_image_node(nodes, cloth_path, "BEDLAM_Cloth_Overlay")
        links.new(cloth_tex.outputs["Color"], cloth_bsdf.inputs["Base Color"])
        links.new(cloth_tex.outputs["Alpha"], mix_shader.inputs["Fac"])
        set_input_if_present(cloth_bsdf, ("Roughness",), 0.84)
        set_input_if_present(cloth_bsdf, ("Specular IOR Level", "Specular"), 0.18)
        set_input_if_present(cloth_bsdf, ("Sheen Weight", "Sheen"), 0.35)
        links.new(skin_bsdf.outputs["BSDF"], mix_shader.inputs[1])
        links.new(cloth_bsdf.outputs["BSDF"], mix_shader.inputs[2])
        links.new(mix_shader.outputs["Shader"], output.inputs["Surface"])
    else:
        links.new(skin_bsdf.outputs["BSDF"], output.inputs["Surface"])

    mat["texture_mode"] = "layered_skin_eye_cloth"
    mat["skin_path"] = str(skin_path)
    mat["eye_path"] = str(eye_path) if eye_path is not None else ""
    mat["clothing_overlay_path"] = str(cloth_path) if cloth_path is not None else ""
    return mat


def apply_texture_item(obj: bpy.types.Object, texture_item: dict[str, Any], node_name: str) -> Path | None:
    if texture_item.get("skin_path"):
        mat = create_layered_bedlam_material(texture_item, node_name)
        obj.data.materials.clear()
        obj.data.materials.append(mat)
        texture_value = texture_item.get("texture")
        return Path(texture_value) if texture_value else None

    texture_value = texture_item.get("texture")
    if not texture_value:
        return None
    texture_path = Path(texture_value)
    apply_texture(obj, texture_path, node_name)
    return texture_path


def apply_texture(obj: bpy.types.Object, texture_path: Path, node_name: str) -> None:
    """Apply a single base-color texture to the first material slot."""
    if not texture_path.exists():
        raise FileNotFoundError(f"Texture not found: {texture_path}")

    mat = bpy.data.materials.new("SMPLX_BEDLAM_Texture_Material")
    mat.diffuse_color = (1.0, 1.0, 1.0, 1.0)
    mat.use_nodes = True
    obj.data.materials.clear()
    obj.data.materials.append(mat)

    tex_node = find_or_create_image_node(mat, node_name)
    image = bpy.data.images.load(str(texture_path), check_existing=True)
    tex_node.image = image


def build_hand_reference_object(
    smplx_obj: bpy.types.Object,
    args: argparse.Namespace,
    selected_texture: Path | None,
) -> tuple[bpy.types.Object, dict] | tuple[None, None]:
    if not args.hand_only_video:
        return None, None

    if args.hand_index_file is not None:
        hand_info = rh.load_hand_indices_from_json(
            args.hand_index_file,
            expected_vertex_count=len(smplx_obj.data.vertices),
        )
    else:
        group_names = rh.parse_csv_values(args.hand_vertex_groups)
        hand_info = rh.load_hand_indices_from_vertex_groups(smplx_obj, group_names)

    rgb_material = smplx_obj.data.materials[0] if smplx_obj.data.materials else None
    hand_obj, hand_meta = rh.build_hand_mesh_from_body(
        body_obj=smplx_obj,
        hand_info=hand_info,
        face_rule=args.hand_face_rule,
        material=rgb_material,
    )

    texture_path = selected_texture or rh.material_image_path(smplx_obj)
    if texture_path is not None:
        flat_material = rh.create_textured_emission_material(texture_path, args.hand_flat_strength)
        hand_obj["flat_rgb_material_name"] = flat_material.name

    hand_obj.hide_render = True
    hand_obj.hide_viewport = True
    return hand_obj, hand_meta


def render_hand_reference_outputs(
    args: argparse.Namespace,
    smplx_obj: bpy.types.Object,
    hand_obj: bpy.types.Object,
    hand_meta: dict,
    vertices: np.ndarray,
    frame_indices: list[int],
) -> dict:
    outputs = set(rh.parse_csv_values(args.hand_outputs))
    valid_outputs = {"rgb", "mask", "depth"}
    unknown = outputs - valid_outputs
    if unknown:
        raise ValueError(f"Unknown hand outputs: {', '.join(sorted(unknown))}")
    if not outputs:
        return {"enabled": False, "outputs": {}}

    source_vertex_indices = hand_meta["source_vertex_indices"]
    rgb_material = hand_obj.data.materials[0] if hand_obj.data.materials else None
    flat_rgb_material = bpy.data.materials.get(hand_obj.get("flat_rgb_material_name", ""))
    mask_material = rh.create_white_emission_material() if "mask" in outputs else None

    depth_meta = None
    depth_material = None
    if "depth" in outputs:
        if args.hand_depth_near is not None and args.hand_depth_far is not None:
            depth_meta = {
                "mode": "manual",
                "near": float(args.hand_depth_near),
                "far": float(args.hand_depth_far),
                "margin": 0.0,
            }
        else:
            depth_meta = rh.compute_depth_range_for_frames(
                hand_obj=hand_obj,
                body_obj=smplx_obj,
                source_vertex_indices=source_vertex_indices,
                frame_indices=frame_indices,
                vertices=vertices,
                set_body_vertices=set_mesh_vertices,
                margin_ratio=args.hand_depth_margin,
            )
            if args.hand_depth_near is not None:
                depth_meta["near"] = float(args.hand_depth_near)
            if args.hand_depth_far is not None:
                depth_meta["far"] = float(args.hand_depth_far)
        depth_meta["invert"] = bool(args.hand_depth_invert)
        depth_material = rh.create_depth_emission_material(
            depth_meta["near"],
            depth_meta["far"],
            invert=args.hand_depth_invert,
        )

    visibility = {}
    for obj in bpy.data.objects:
        if obj.type == "MESH":
            visibility[obj.name] = (obj.hide_render, obj.hide_viewport)
            obj.hide_render = obj != hand_obj
            obj.hide_viewport = obj != hand_obj

    bg_state = rh.save_black_background(transparent=args.hand_bg == "transparent")
    result = {"enabled": True, "outputs": {}, "mesh": hand_meta, "background": args.hand_bg}

    try:
        for output_name in ("rgb", "mask", "depth"):
            if output_name not in outputs:
                continue

            color_state = None
            hand_obj.data.materials.clear()
            if output_name == "rgb":
                if args.hand_light_mode == "flat" and flat_rgb_material is not None:
                    hand_obj.data.materials.append(flat_rgb_material)
                elif rgb_material is not None:
                    hand_obj.data.materials.append(rgb_material)
            elif output_name == "mask":
                hand_obj.data.materials.append(mask_material)
            else:
                hand_obj.data.materials.append(depth_material)
                color_state = rh.save_depth_color_management()

            frames_dir = args.out_dir / f"hand_{output_name}_frames"
            frames_dir.mkdir(parents=True, exist_ok=True)
            # A shorter rerun must not leave stale frames from an older render.
            for stale_frame in frames_dir.glob("frame_*.png"):
                stale_frame.unlink()
            rendered_paths: list[Path] = []
            try:
                for frame_idx in frame_indices:
                    set_mesh_vertices(smplx_obj, np.asarray(vertices[frame_idx]))
                    rh.update_hand_mesh_vertices(hand_obj, smplx_obj, source_vertex_indices)
                    bpy.context.view_layer.update()
                    frame_path = frames_dir / f"frame_{frame_idx:06d}.png"
                    bpy.context.scene.frame_set(frame_idx)
                    bpy.context.scene.render.filepath = str(frame_path)
                    bpy.ops.render.render(write_still=True)
                    rendered_paths.append(frame_path)
            finally:
                if color_state is not None:
                    rh.restore_depth_color_management(color_state)

            video_path = args.out_dir / f"{args.out_dir.name}_hand_{output_name}.mp4"
            video_encoded = False
            if not args.no_video:
                video_encoded = rh.encode_video_ffmpeg(rendered_paths, video_path, args.fps, args.crf)
            result["outputs"][output_name] = {
                "frames_dir": str(frames_dir),
                "video_path": str(video_path),
                "video_encoded": video_encoded,
                "frame_count": len(rendered_paths),
            }
            if output_name == "depth":
                result["outputs"][output_name]["depth"] = depth_meta
    finally:
        rh.restore_black_background(bg_state)
        if rgb_material is not None:
            hand_obj.data.materials.clear()
            hand_obj.data.materials.append(rgb_material)
        for obj in bpy.data.objects:
            if obj.name in visibility:
                obj.hide_render, obj.hide_viewport = visibility[obj.name]
        smplx_obj.hide_render = False
        smplx_obj.hide_viewport = False
        bpy.context.view_layer.update()

    return result


def render_sequence(args: argparse.Namespace) -> None:
    rng = random.Random(args.seed)
    render_config = load_render_config(args.render_config)

    vertices_path = args.sequence_dir / "vertices.npy"
    if not vertices_path.exists():
        raise FileNotFoundError(f"Missing vertices.npy: {vertices_path}")

    sequence_meta = {}
    sequence_meta_path = args.sequence_dir / "meta.json"
    if sequence_meta_path.exists():
        with open(sequence_meta_path, "r", encoding="utf-8") as f:
            sequence_meta = json.load(f)

    vertices = np.load(vertices_path, mmap_mode="r")
    if vertices.ndim != 3 or vertices.shape[2] != 3:
        raise ValueError(f"vertices.npy must have shape [F,V,3], got {vertices.shape}")

    num_frames = vertices.shape[0]
    frame_indices = parse_frame_spec(args.frames, num_frames)

    hand_group_names = rh.parse_csv_values(args.hand_vertex_groups)
    uv_meta = {"enabled": False}
    config_gender = render_config.get("gender")
    if args.render_mesh_source == "addon":
        gender = sequence_meta.get("gender", "neutral")
        if gender not in {"female", "male", "neutral"}:
            gender = "neutral"
        if config_gender in {"female", "male"} and gender != config_gender:
            raise ValueError(f"Sequence gender '{gender}' does not match render_config gender '{config_gender}'.")
        model_variant = args.model_variant or sequence_meta.get("model_variant") or "locked_head"
        uv_version = args.uv_version or sequence_meta.get("uv_version") or "UV_2023"
        donor = find_hand_group_donor(vertices.shape[1], hand_group_names, exclude=None)
        smplx_obj = create_addon_render_body(gender, model_variant, uv_version, args.addon_dir)
        uv_donor = find_uv_donor(args.uv_donor_object, smplx_obj)
        if uv_donor is None:
            raise RuntimeError(
                f"No UV donor with matching topology was found. Expected '{args.uv_donor_object}' "
                f"or another {len(smplx_obj.data.vertices)}-vertex SMPL-X mesh in the template."
            )
        uv_meta = copy_active_uv_by_loop(uv_donor, smplx_obj)
        print(f"[OK] Copied active UV from '{uv_donor.name}' to '{smplx_obj.name}'.")
        if donor is not None:
            copy_vertex_groups_by_index(donor, smplx_obj, hand_group_names)
            print(f"[OK] Copied hand vertex groups from '{donor.name}' to '{smplx_obj.name}'.")
        elif args.hand_only_video:
            existing = {group.name for group in smplx_obj.vertex_groups}
            missing = [name for name in hand_group_names if name not in existing]
            if missing and args.hand_index_file is None:
                raise KeyError(
                    f"No donor mesh with hand vertex groups was found, and addon mesh is missing: {', '.join(missing)}. "
                    "Pass --hand-index-file or use a template with matching Lhand/Rhand groups."
                )
    else:
        smplx_obj = resolve_smplx_object(args.smplx_object, expected_vertex_count=vertices.shape[1])

    validate_topology(smplx_obj, args.sequence_dir, expected_vertex_count=vertices.shape[1])
    hide_other_body_meshes(smplx_obj, expected_vertex_count=vertices.shape[1])

    if args.force_identity:
        smplx_obj.matrix_world = mathutils.Matrix.Identity(4)

    cam_obj = ensure_camera(args.camera_name)
    bpy.context.scene.camera = cam_obj

    set_render_settings(
        width=args.width,
        height=args.height,
        engine=args.engine,
        fps=args.fps,
        motion_blur=args.motion_blur,
    )

    world_meta = apply_world_config(render_config)
    hidden_background_planes = hide_background_planes() if world_meta.get("enabled") else []
    disable_script_lights = bool(args.disable_script_lights or render_config.get("disable_script_lights", False))
    if disable_script_lights:
        hidden_lights = hide_scene_lights()
    else:
        setup_lights(rng)
        hidden_lights = []

    manifest = load_manifest(args.manifest)
    texture_items = manifest.get("texture_items") or []
    textures = [Path(p) for p in manifest.get("textures", [])]
    config_texture_item = render_config.get("texture_item") if render_config else None
    if config_texture_item:
        selected_texture_item = config_texture_item
        selected_texture = Path(selected_texture_item["texture"]) if selected_texture_item.get("texture") else None
    elif texture_items:
        selected_texture_item = rng.choice(texture_items)
        selected_texture = Path(selected_texture_item["texture"]) if selected_texture_item.get("texture") else None
    else:
        selected_texture = rng.choice(textures) if textures else None
        selected_texture_item = {"texture": str(selected_texture)} if selected_texture is not None else None

    if selected_texture_item:
        selected_texture = apply_texture_item(smplx_obj, selected_texture_item, args.texture_node_name)
    elif selected_texture is not None:
        apply_texture(smplx_obj, selected_texture, args.texture_node_name)

    rest_vertices = mesh_vertices_array(smplx_obj)
    hair_objects, hair_meta = import_hair_objects(render_config, args, rest_vertices)

    hand_obj, hand_meta = build_hand_reference_object(smplx_obj, args, selected_texture)

    images_dir = args.out_dir / "images"
    cameras_dir = args.out_dir / "cameras"
    images_dir.mkdir(parents=True, exist_ok=True)
    cameras_dir.mkdir(parents=True, exist_ok=True)
    # COCO generation scans these directories, so remove stale tail frames when
    # a previous render was longer than the current capped sequence.
    for stale_frame in images_dir.glob("frame_*.png"):
        stale_frame.unlink()
    for stale_camera in cameras_dir.glob("frame_*.json"):
        stale_camera.unlink()

    # One camera per rendered sequence by default.
    if render_config.get("camera_preset_name"):
        camera_meta = apply_camera_config(cam_obj, render_config)
    else:
        randomize_camera(
            cam_obj=cam_obj,
            rng=rng,
            radius_min=args.camera_radius_min,
            radius_max=args.camera_radius_max,
            height_min=args.camera_height_min,
            height_max=args.camera_height_max,
            target_height=args.target_height,
            focal_min=args.focal_length_min,
            focal_max=args.focal_length_max,
        )
        camera_meta = {
            "enabled": False,
            "mode": "random_orbit",
            "name": cam_obj.name,
        }

    # Preserve the preset's horizontal field of view when changing output
    # aspect ratio.  832x480 therefore reveals a little more vertically than
    # 16:9 instead of cropping or zooming the subject.
    cam_obj.data.sensor_fit = "HORIZONTAL"
    camera_meta["sensor_fit"] = "HORIZONTAL"

    rgb_frame_paths: list[Path] = []
    for frame_idx in frame_indices:
        if not render_config and args.texture_per_frame and textures:
            selected_texture = rng.choice(textures)
            apply_texture(smplx_obj, selected_texture, args.texture_node_name)

        current_vertices = np.asarray(vertices[frame_idx])
        set_mesh_vertices(smplx_obj, current_vertices)
        update_hair_transform(hair_objects, hair_meta, rest_vertices, current_vertices)
        bpy.context.view_layer.update()

        image_path = images_dir / f"frame_{frame_idx:06d}.png"
        camera_path = cameras_dir / f"frame_{frame_idx:06d}.json"

        bpy.context.scene.frame_set(frame_idx)
        bpy.context.scene.render.filepath = str(image_path)
        bpy.ops.render.render(write_still=True)
        rgb_frame_paths.append(image_path)

        rh.export_camera_calibration(
            camera_obj=cam_obj,
            smplx_obj=smplx_obj,
            out_json_path=camera_path,
            image_width=args.width,
            image_height=args.height,
        )

        if selected_texture is not None or selected_texture_item is not None:
            texture_record = {
                "texture": str(selected_texture) if selected_texture is not None else None,
                "texture_item": selected_texture_item,
            }
            with open(camera_path, "r", encoding="utf-8") as f:
                cam_json = json.load(f)
            cam_json.update(texture_record)
            with open(camera_path, "w", encoding="utf-8") as f:
                json.dump(cam_json, f, indent=2)

    rgb_video_path = args.out_dir / f"{args.out_dir.name}.mp4"
    rgb_video_encoded = False
    if not args.no_video:
        rgb_video_encoded = rh.encode_video_ffmpeg(rgb_frame_paths, rgb_video_path, args.fps, args.crf)

    hand_only_meta = {"enabled": False}
    if hand_obj is not None:
        hair_visibility_state = set_hair_visibility(hair_objects, visible=False)
        try:
            hand_only_meta = render_hand_reference_outputs(
                args=args,
                smplx_obj=smplx_obj,
                hand_obj=hand_obj,
                hand_meta=hand_meta,
                vertices=vertices,
                frame_indices=frame_indices,
            )
        finally:
            restore_hair_visibility(hair_objects, hair_visibility_state)

    run_meta = {
        "sequence_dir": str(args.sequence_dir),
        "out_dir": str(args.out_dir),
        "frames": frame_indices,
        "fps": args.fps,
        "motion_blur": bool(args.motion_blur),
        "rgb_video_path": str(rgb_video_path),
        "rgb_video_encoded": rgb_video_encoded,
        "selected_texture": str(selected_texture) if selected_texture is not None else None,
        "selected_texture_item": selected_texture_item,
        "render_config_path": str(args.render_config) if args.render_config else None,
        "render_config": render_config,
        "world": world_meta,
        "disable_script_lights": disable_script_lights,
        "hidden_lights": hidden_lights,
        "hidden_background_planes": hidden_background_planes,
        "camera": camera_meta,
        "hair": hair_meta,
        "final_camera_matrix_world": [[float(value) for value in row] for row in cam_obj.matrix_world],
        "render_mesh_source": args.render_mesh_source,
        "render_mesh": {
            "name": smplx_obj.name,
            "vertex_count": len(smplx_obj.data.vertices),
            "face_count": int(triangulated_faces(smplx_obj).shape[0]),
            "uv_active": smplx_obj.data.uv_layers.active.name if smplx_obj.data.uv_layers.active else None,
            "uv_version": smplx_obj.get("smplx_uv"),
            "uv_source": uv_meta,
        },
        "sequence_meta": sequence_meta,
        "betas": sequence_meta.get("betas"),
        "beta_seed": sequence_meta.get("beta_seed"),
        "camera_name": args.camera_name,
        "smplx_object": args.smplx_object,
        "hand_only": hand_only_meta,
        "args": {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()},
    }
    with open(args.out_dir / "render_meta.json", "w", encoding="utf-8") as f:
        json.dump(run_meta, f, indent=2, ensure_ascii=False)

    print(f"[OK] Rendered {len(frame_indices)} frames to {args.out_dir}")


def main() -> None:
    args = parse_blender_args()
    render_sequence(args)


if __name__ == "__main__":
    main()