File size: 90,325 Bytes
b546a02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
import bpy
import json
import math
import re
import numpy as np
import bmesh
from pathlib import Path
from mathutils import Vector
from mathutils.bvhtree import BVHTree
from mathutils.geometry import barycentric_transform
import random
import time
import sys
import argparse

IMAGE_PREFIX = "dens_"
VGROUP_PREFIX = "len_"

ANIMALLIFT_ROOT = Path("path/to/AnimalLift")

REGIONS = [
    "face", "ear", "neck", "body", "leg", "tail"
]

CURVE_REGION_MAP = {
    "face_fur": "face",
    "ear_fur": "ear",
    "body_fur": "body",
    "leg_fur": "leg",
    "neck_fur": "neck",
    "neck": "neck",
    "mouse_fur": "face",
    "tail_fur": "tail",
}

IGNORE_NAME_KEYWORDS = ["undercoat"]

MOUSE_LENGTH_VALUE = 0.05

BASE_PART_RESOLUTION = 512
SAMPLES_PER_STRAND = 32
ATLAS_TILE_PADDING = 0.02

IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".exr"}

META_ROOT = ANIMALLIFT_ROOT / "meta"
HDR_DIR = META_ROOT / "render_elements" / "hdr"
HDR_IMAGE_EXTS = {".hdr", ".exr"}

UNDERHAIR_MASK_PATH = META_ROOT / "used_version_obj" / "part_masks" / "merged.png"
UNDERHAIR_LENGTH = 0.005
UNDERHAIR_INTERP_DENSITY = 500000.0
UNDERHAIR_MASK_GROUP = "underhair_mask"


def log(msg: str):
    print(f"[hair-load] {msg}")


def natural_key(path: Path):
    parts = re.split(r"(\d+)", path.stem.lower())
    key = []
    for p in parts:
        if p.isdigit():
            key.append(int(p))
        else:
            key.append(p)
    key.append(path.suffix.lower())
    return key


def is_hidden_or_metadata_name(name: str) -> bool:
    """Return True for hidden files and common macOS metadata entries."""
    return (
        not name
        or name.startswith(".")
        or name.startswith("._")
        or name in {".DS_Store", "Thumbs.db"}
    )


def is_usable_file(path: Path) -> bool:
    """Accept only real, visible files."""
    path = Path(path)
    return path.is_file() and not is_hidden_or_metadata_name(path.name)


def is_usable_directory(path: Path) -> bool:
    """Accept only real, visible directories."""
    path = Path(path)
    return path.is_dir() and not is_hidden_or_metadata_name(path.name)


def require_usable_file(path, description: str = "File") -> Path:
    """Resolve and validate an explicitly supplied file path."""
    path = Path(path).expanduser().resolve()
    if not is_usable_file(path):
        raise FileNotFoundError(
            f"{description} is missing, hidden, or a macOS metadata file: {path}"
        )
    return path


# Backward-compatible alias used by older helper functions.
is_usable_dataset_file = is_usable_file



def pick_random_hdr_image(hdr_dir: str, rng_seed: int = None):
    hdr_dir = Path(hdr_dir).resolve()
    if not is_usable_directory(hdr_dir):
        raise FileNotFoundError(
            f"HDR directory is missing or hidden: {hdr_dir}"
        )

    hdr_files = sorted(
        [
            path
            for path in hdr_dir.iterdir()
            if is_usable_file(path)
            and path.suffix.lower() in HDR_IMAGE_EXTS
        ],
        key=natural_key,
    )

    rejected = sorted(
        [
            path.name
            for path in hdr_dir.iterdir()
            if path.suffix.lower() in HDR_IMAGE_EXTS
            and not is_usable_file(path)
        ]
    )
    if rejected:
        log(f"Ignored hidden HDR metadata files: {rejected}")

    if not hdr_files:
        raise FileNotFoundError(
            f"No usable HDR/EXR files found in: {hdr_dir}"
        )

    rng = random.Random(rng_seed)
    chosen = rng.choice(hdr_files)
    log(f"Randomly selected HDR: {chosen.name}")
    return chosen

def list_hair_files(hair_dir: Path):
    """Prefer .pt files exactly as the training dataset does."""
    pt_files = sorted(
        [p for p in hair_dir.glob("*.pt") if is_usable_file(p)],
        key=natural_key,
    )
    if pt_files:
        return pt_files

    return sorted(
        [p for p in hair_dir.glob("*.npz") if is_usable_file(p)],
        key=natural_key,
    )


def select_hair_map_for_obj(obj_path: Path, dataset_dir: Path):
    """
    Match the training dataset's auxiliary-file rule.

    - Prefer hair_maps_single_512_uvlocal.
    - Prefer .pt over .npz.
    - If there is one hair file, reuse it for every shape.
    - Otherwise pair hair and shape files by natural-sort index.
    """
    hair_dir_candidates = [
        dataset_dir / "hair_maps_single_512_uvlocal",
        dataset_dir / "hair_maps_curl",
        dataset_dir / "hair_maps",
    ]

    shapes_dir = dataset_dir / "shapes"
    shape_files = sorted(
        [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)],
        key=natural_key,
    )

    try:
        shape_index = next(
            index
            for index, path in enumerate(shape_files)
            if path.resolve() == obj_path.resolve()
        )
    except StopIteration as exc:
        raise FileNotFoundError(
            f"OBJ file is not present in the dataset shapes directory: {obj_path}"
        ) from exc

    checked = []
    for hair_dir in hair_dir_candidates:
        checked.append(str(hair_dir))
        hair_files = list_hair_files(hair_dir)
        if not hair_files:
            continue

        same_stem = [
            path for path in hair_files
            if path.stem == obj_path.stem
        ]
        if same_stem:
            return same_stem[0]

        if len(hair_files) == 1:
            return hair_files[0]

        if shape_index < len(hair_files):
            return hair_files[shape_index]

        raise IndexError(
            f"Hair index out of range for {obj_path.name}: "
            f"shapes={len(shape_files)}, hair_files={len(hair_files)}, "
            f"shape_index={shape_index}, hair_dir={hair_dir}"
        )

    raise FileNotFoundError(
        "Could not find a compatible .pt or .npz hair map in:\n  "
        + "\n  ".join(checked)
    )


def resolve_paths_from_obj(obj_path: str):
    obj_path = Path(obj_path).expanduser().resolve()
    if not is_usable_file(obj_path):
        raise FileNotFoundError(
            f"OBJ file is missing or is a hidden/macOS metadata file: {obj_path}"
        )
    if obj_path.parent.name != "shapes":
        raise ValueError(
            "Expected an OBJ inside a dataset group 'shapes' directory, for example:\n"
            "  /path/to/animallift/cat/dataset/<group>/shapes/<sample>.obj"
        )

    dataset_dir = obj_path.parent.parent
    hair_map_path = select_hair_map_for_obj(obj_path, dataset_dir)

    return {
        "dataset_dir": dataset_dir,
        "datasets_root": dataset_dir.parent,
        "sample_name": obj_path.stem,
        "textures_dir": dataset_dir / "textures",
        "hair_map": hair_map_path,
        "hair_meta": META_ROOT / "hair_map_meta_uvanchor.npz",
        "hair_map_curl_out": hair_map_path,
        "mesh_normal": META_ROOT / "render_elements" / "Normal.png",
        "mesh_roughness": META_ROOT / "render_elements" / "Roughness.png",
        "hdr_dir": HDR_DIR,
    }


def discover_dataset_case(
    root: Path,
    species: str = "cat",
    group_name: str = None,
    sample_index: int = 0,
):
    """
    Discover a real case from:
      <root>/<species>/dataset/<group>/shapes/*.obj

    The group must also contain textures and a compatible hair-map directory.
    """
    root = Path(root).expanduser().resolve()
    species_root = root / species / "dataset"
    if not species_root.is_dir():
        raise FileNotFoundError(f"Species dataset directory not found: {species_root}")

    if group_name:
        explicit_group = species_root / group_name
        if not is_usable_directory(explicit_group):
            raise FileNotFoundError(
                f"Requested dataset group not found: {explicit_group}"
            )
        group_dirs = [explicit_group]
    else:
        group_dirs = sorted(
            [
                path
                for path in species_root.iterdir()
                if is_usable_directory(path)
            ],
            key=natural_key,
        )

    failures = []
    for group_dir in group_dirs:
        shapes_dir = group_dir / "shapes"
        textures_dir = group_dir / "textures"
        if not shapes_dir.is_dir() or not textures_dir.is_dir():
            failures.append(f"{group_dir}: missing shapes or textures")
            continue

        shape_files = sorted(
            [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)],
            key=natural_key,
        )
        texture_files = sorted(
            [
                p for p in textures_dir.iterdir()
                if is_usable_file(p) and p.suffix.lower() in IMAGE_EXTS
            ],
            key=natural_key,
        )
        if not shape_files or not texture_files:
            failures.append(f"{group_dir}: empty shapes or textures")
            continue

        usable_count = min(len(shape_files), len(texture_files))
        if sample_index < 0 or sample_index >= usable_count:
            failures.append(
                f"{group_dir}: sample_index={sample_index} outside 0..{usable_count - 1}"
            )
            continue

        obj_path = shape_files[sample_index]
        try:
            hair_path = select_hair_map_for_obj(obj_path, group_dir)
        except Exception as exc:
            failures.append(f"{group_dir}: {exc}")
            continue

        deformed_candidate = group_dir / "deformed_shapes" / obj_path.name
        deformed_path = (
            deformed_candidate
            if is_usable_file(deformed_candidate)
            else None
        )

        log(f"Using dataset group: {group_dir.name}")
        log(f"Selected OBJ: {obj_path.name}")
        log(f"Selected hair map: {hair_path.name}")
        if deformed_path is None:
            log("No matching deformed shape found; using the original mesh")
        else:
            log(f"Selected deformed shape: {deformed_path.name}")

        return obj_path, deformed_path

    detail = "\n".join(f"  - {item}" for item in failures[:20])
    raise RuntimeError(
        f"No usable visualization case found under {species_root}.\n{detail}"
    )



def load_global_hair_meta(meta_path: str):
    meta_path = require_usable_file(
        meta_path,
        "Global hair metadata",
    )

    data = np.load(str(meta_path), allow_pickle=True)

    required_keys = [
        "group_names",
        "guide_group_id_map",
        "uv_face_index_map",
        "uv_bary_map",
    ]
    for key in required_keys:
        if key not in data:
            raise KeyError(f"Missing key '{key}' in global hair meta: {meta_path}")

    group_names = [str(n) for n in data["group_names"]]
    guide_group_id_map = data["guide_group_id_map"].astype(np.int32)
    uv_face_index_map = data["uv_face_index_map"].astype(np.int32)
    uv_bary_map = data["uv_bary_map"].astype(np.float32)

    log(f"Loaded global hair meta: {meta_path}")
    log(f"  Groups: {group_names}")
    log(f"  guide_group_id_map shape: {guide_group_id_map.shape}")
    log(f"  uv_face_index_map shape: {uv_face_index_map.shape}")
    log(f"  uv_bary_map shape: {uv_bary_map.shape}")

    return group_names, guide_group_id_map, uv_face_index_map, uv_bary_map


def import_obj_as_mesh(obj_path: str, object_name: str = None):
    obj_path = str(require_usable_file(obj_path, "OBJ file"))

    bpy.ops.object.select_all(action='DESELECT')
    if hasattr(bpy.ops.wm, "obj_import"):
        bpy.ops.wm.obj_import(filepath=obj_path)
    else:
        bpy.ops.import_scene.obj(filepath=obj_path)

    imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
    if not imported_meshes:
        raise Exception(f"No mesh imported from {obj_path}")

    mesh_obj = imported_meshes[0]
    if object_name:
        mesh_obj.name = object_name
        mesh_obj.data.name = object_name

    bpy.ops.object.select_all(action='DESELECT')
    mesh_obj.select_set(True)
    bpy.context.view_layer.objects.active = mesh_obj
    bpy.ops.object.shade_smooth()

    log(f"Imported mesh: {mesh_obj.name} ({len(mesh_obj.data.vertices)} verts, smooth shading)")
    return mesh_obj


def apply_deformed_shape_directly(mesh_obj, deformed_obj_path: str):
    """Overwrite base mesh vertex positions with deformed OBJ vertex positions.

    This avoids shape keys entirely so the base mesh IS the deformed shape,
    and all curves bound to its surface will follow naturally.
    """
    deformed_obj_path = str(
        require_usable_file(deformed_obj_path, "Deformed OBJ file")
    )

    bpy.ops.object.select_all(action='DESELECT')
    if hasattr(bpy.ops.wm, "obj_import"):
        bpy.ops.wm.obj_import(filepath=deformed_obj_path)
    else:
        bpy.ops.import_scene.obj(filepath=deformed_obj_path)

    imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
    if not imported_meshes:
        raise Exception(f"No mesh imported from {deformed_obj_path}")
    imported = imported_meshes[0]

    if len(mesh_obj.data.vertices) != len(imported.data.vertices):
        bpy.data.objects.remove(imported, do_unlink=True)
        raise Exception(
            f"Vertex count mismatch! Target: {len(mesh_obj.data.vertices)}, "
            f"Imported: {len(imported.data.vertices)}"
        )

    for i, v in enumerate(imported.data.vertices):
        mesh_obj.data.vertices[i].co = v.co

    bpy.data.objects.remove(imported, do_unlink=True)
    mesh_obj.data.update()

    log(f"Applied deformed shape directly to '{mesh_obj.name}' from {deformed_obj_path}")


def import_obj_as_shape_key(target, obj_path: str, shape_key_name: str):
    obj_path = str(require_usable_file(obj_path, "Shape-key OBJ file"))

    bpy.ops.object.select_all(action='DESELECT')
    if hasattr(bpy.ops.wm, "obj_import"):
        bpy.ops.wm.obj_import(filepath=obj_path)
    else:
        bpy.ops.import_scene.obj(filepath=obj_path)

    imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
    if not imported_meshes:
        raise Exception(f"No imported mesh found from {obj_path}")
    imported = imported_meshes[0]

    try:
        if len(target.data.vertices) != len(imported.data.vertices):
            raise Exception(
                f"Vertex count mismatch! Target: {len(target.data.vertices)}, "
                f"Imported: {len(imported.data.vertices)}"
            )

        if not target.data.shape_keys:
            target.shape_key_add(name="Basis")

        old = target.data.shape_keys.key_blocks.get(shape_key_name)
        if old is not None:
            bpy.context.view_layer.objects.active = target
            target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(old)
            bpy.ops.object.shape_key_remove(all=False)

        sk = target.shape_key_add(name=shape_key_name, from_mix=False)
        for i, v in enumerate(imported.data.vertices):
            sk.data[i].co = v.co

        sk.value = 1.0
        target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(sk)

        log(f"Shape key created and enabled: {shape_key_name}")
        return sk
    finally:
        bpy.data.objects.remove(imported, do_unlink=True)


def resolve_corresponding_deformed_shape_path(source_obj_path: str, deformed_obj_path: str = None):
    if deformed_obj_path is not None:
        p = Path(deformed_obj_path).resolve()
    else:
        source_obj_path = Path(source_obj_path).resolve()
        dataset_dir = source_obj_path.parent.parent
        p = dataset_dir / "deformed_shapes" / source_obj_path.name

    if not is_usable_file(p):
        raise FileNotFoundError(
            f"Deformed shape OBJ is missing or hidden: {p}"
        )
    return p


def open_image_simple(image_path: str, non_color: bool = True):
    image_path = str(require_usable_file(image_path, "Image file"))
    img = bpy.data.images.load(filepath=image_path, check_existing=True)
    img.colorspace_settings.name = 'Non-Color' if non_color else 'sRGB'
    img.pixels[:]
    return img


def open_image_color(image_path: str):
    return open_image_simple(image_path, non_color=False)

def is_green_rgb(rgb, green_threshold=0.45, green_margin=0.08):
    r, g, b = float(rgb[0]), float(rgb[1]), float(rgb[2])
    return (
        g >= green_threshold and
        g > r + green_margin and
        g > b + green_margin
    )


def remove_green_screen_from_image(
    src_image_path: str,
    out_image_path: str = None,
    green_threshold: float = 0.45,
    green_margin: float = 0.08,
    rng_seed: int = None,
):
    """
    Replace green pixels with randomly sampled non-green colors from the same image.
    Returns the output image path.
    """
    src_image_path = require_usable_file(
        src_image_path,
        "Texture image",
    )

    img = bpy.data.images.load(filepath=str(src_image_path), check_existing=False)
    width, height = img.size

    pixel_count = width * height * 4
    pixels = np.empty(pixel_count, dtype=np.float32)
    img.pixels.foreach_get(pixels)
    pixels = pixels.reshape((height, width, 4))

    rgb = pixels[:, :, :3]
    alpha = pixels[:, :, 3:4]

    green_mask = (
        (rgb[:, :, 1] >= green_threshold) &
        (rgb[:, :, 1] > rgb[:, :, 0] + green_margin) &
        (rgb[:, :, 1] > rgb[:, :, 2] + green_margin)
    )

    non_green_coords = np.argwhere(~green_mask)
    green_coords = np.argwhere(green_mask)

    if len(green_coords) == 0:
        log(f"No green pixels detected in texture: {src_image_path.name}")
        return src_image_path

    if len(non_green_coords) == 0:
        log(f"[WARN] Texture has no non-green pixels to sample from: {src_image_path.name}")
        return src_image_path

    rng = np.random.default_rng(rng_seed)

    sampled_ids = rng.integers(0, len(non_green_coords), size=len(green_coords))
    sampled_coords = non_green_coords[sampled_ids]

    replacement_colors = rgb[sampled_coords[:, 0], sampled_coords[:, 1]]
    rgb[green_coords[:, 0], green_coords[:, 1]] = replacement_colors

    out_pixels = np.concatenate([rgb, alpha], axis=2).astype(np.float32).reshape(-1)

    if out_image_path is None:
        out_image_path = src_image_path.parent / f"{src_image_path.stem}_nogreen.png"
    else:
        out_image_path = Path(out_image_path).resolve()

    out_image_path.parent.mkdir(parents=True, exist_ok=True)

    out_img = bpy.data.images.new(
        name=f"{src_image_path.stem}_nogreen",
        width=width,
        height=height,
        alpha=True,
        float_buffer=False,
    )
    out_img.colorspace_settings.name = 'sRGB'
    out_img.filepath_raw = str(out_image_path)
    out_img.file_format = 'PNG'
    out_img.pixels.foreach_set(out_pixels.tolist())
    out_img.save()

    try:
        bpy.data.images.remove(img)
    except Exception:
        pass

    log(f"Saved green-removed texture: {out_image_path}")
    return out_image_path


def resolve_render_output_path(obj_path: str, render_filename: str = None):
    obj_path = Path(obj_path).resolve()
    dataset_dir = obj_path.parent.parent
    render_dir = dataset_dir / "render_images"
    render_dir.mkdir(parents=True, exist_ok=True)

    if render_filename is None:
        render_filename = f"{obj_path.stem}.png"

    return render_dir / render_filename


def render_and_save_image(output_path: str):
    output_path = Path(output_path).resolve()
    output_path.parent.mkdir(parents=True, exist_ok=True)

    scene = bpy.context.scene
    scene.render.image_settings.file_format = 'PNG'
    scene.render.image_settings.color_mode = 'RGBA'
    scene.render.filepath = str(output_path)

    bpy.ops.render.render(write_still=True)
    log(f"Saved render image: {output_path}")


def load_density_images(mesh_obj, density_dir: str):
    density_images = {}
    for region in REGIONS:
        image_path = Path(density_dir) / f"{region}.png"
        if not is_usable_file(image_path):
            log(f"  [WARN] Density image not found: {image_path}")
            continue
        img = open_image_simple(str(image_path), non_color=True)
        img.name = f"{IMAGE_PREFIX}{region}_{mesh_obj.name}"
        density_images[region] = img
    return density_images


def create_vertex_group_from_image(obj, image_path: str, group_name: str, scale: float = 1.0):
    mesh = obj.data
    if not mesh.uv_layers:
        raise Exception("Target mesh has no UVs")

    img = open_image_simple(image_path, non_color=True)
    width, height = img.size

    pixel_count = width * height * 4
    pixels_np = np.empty(pixel_count, dtype=np.float32)
    img.pixels.foreach_get(pixels_np)
    pixels_np = pixels_np.reshape((height, width, 4))

    lum = (
        0.2126 * pixels_np[:, :, 0]
        + 0.7152 * pixels_np[:, :, 1]
        + 0.0722 * pixels_np[:, :, 2]
    )

    total_loops = len(mesh.loops)
    loop_uvs = np.empty(total_loops * 2, dtype=np.float32)
    mesh.uv_layers.active.data.foreach_get("uv", loop_uvs)
    loop_uvs = loop_uvs.reshape((total_loops, 2))

    loop_verts = np.empty(total_loops, dtype=np.int32)
    mesh.loops.foreach_get("vertex_index", loop_verts)

    u = np.clip(loop_uvs[:, 0], 0.0, 1.0)
    v = np.clip(loop_uvs[:, 1], 0.0, 1.0)
    xi = (u * (width - 1)).astype(np.int32)
    yi = (v * (height - 1)).astype(np.int32)
    loop_weights = lum[yi, xi] * float(scale)

    num_verts = len(mesh.vertices)
    weight_sum = np.zeros(num_verts, dtype=np.float64)
    weight_cnt = np.zeros(num_verts, dtype=np.int32)
    np.add.at(weight_sum, loop_verts, loop_weights)
    np.add.at(weight_cnt, loop_verts, 1)

    mask = weight_cnt > 0
    avg_weights = np.zeros(num_verts, dtype=np.float64)
    avg_weights[mask] = weight_sum[mask] / weight_cnt[mask]

    old_vg = obj.vertex_groups.get(group_name)
    if old_vg is not None:
        obj.vertex_groups.remove(old_vg)
    vg = obj.vertex_groups.new(name=group_name)

    indices = np.where(mask)[0]
    for vid in indices:
        vg.add([int(vid)], float(avg_weights[vid]), 'REPLACE')

    return vg, img


def load_hair_info(json_path):
    json_path = Path(json_path).resolve()
    if not is_usable_file(json_path):
        raise FileNotFoundError(
            f"hair_info.json is missing or hidden: {json_path}"
        )
    with open(json_path, "r", encoding="utf-8") as f:
        return json.load(f)


def get_region_length_scale(hair_info: dict, region: str) -> float:
    params = hair_info.get("resolved_hair_params", {})
    if region not in params:
        raise KeyError(f"Region '{region}' not found in resolved_hair_params")
    return float(params[region]["length"])


def create_length_vertex_groups(mesh_obj, length_dir: str, hair_info: dict):
    for region in REGIONS:
        image_path = Path(length_dir) / f"{region}.png"
        if not is_usable_file(image_path):
            log(f"  [WARN] Length image not found: {image_path}")
            continue
        vg_name = f"{VGROUP_PREFIX}{region}"
        scale = get_region_length_scale(hair_info, region)
        vg, img = create_vertex_group_from_image(mesh_obj, str(image_path), vg_name, scale=scale)
        img.name = f"lenimg_{region}_{mesh_obj.name}"
        log(f"  Created vertex group: {vg.name}, scale={scale:.4f}")


def ensure_triangulated_bmesh(mesh):
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.triangulate(bm, faces=bm.faces[:])
    bm.faces.ensure_lookup_table()
    bm.verts.ensure_lookup_table()
    return bm


def get_evaluated_mesh(mesh_obj):
    """Return the evaluated (deformed) mesh data, accounting for shape keys
    and modifiers. Caller must call eval_obj.to_mesh_clear() when done if needed.
    """
    depsgraph = bpy.context.evaluated_depsgraph_get()
    eval_obj = mesh_obj.evaluated_get(depsgraph)
    eval_mesh = eval_obj.to_mesh()
    return eval_obj, eval_mesh


def compute_root_uvs(roots, mesh_obj):
    mesh = mesh_obj.data
    if not mesh.uv_layers.active:
        raise RuntimeError("Mesh has no active UV layer")

    # Use evaluated mesh so roots snap to deformed positions
    eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)

    bm = bmesh.new()
    bm.from_mesh(eval_mesh)
    bmesh.ops.triangulate(bm, faces=bm.faces[:])
    bm.faces.ensure_lookup_table()
    bm.verts.ensure_lookup_table()

    # UV layer name comes from the original mesh
    uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name)
    if uv_layer is None:
        bm.free()
        eval_obj.to_mesh_clear()
        raise RuntimeError("Could not access active UV layer")

    bvh = BVHTree.FromBMesh(bm)
    uvs = []

    for root in roots:
        hit = bvh.find_nearest(Vector(root))
        if hit is None or hit[2] is None:
            uvs.append((0.5, 0.5))
            continue

        location, normal, face_index, dist = hit
        face = bm.faces[face_index]
        if len(face.verts) != 3:
            uvs.append((0.5, 0.5))
            continue

        v0, v1, v2 = [f.co for f in face.verts]
        uv0 = face.loops[0][uv_layer].uv
        uv1 = face.loops[1][uv_layer].uv
        uv2 = face.loops[2][uv_layer].uv

        uv = barycentric_transform(
            location, v0, v1, v2,
            uv0.to_3d(), uv1.to_3d(), uv2.to_3d()
        )
        uvs.append((float(uv.x), float(uv.y)))

    bm.free()
    eval_obj.to_mesh_clear()
    return uvs


def build_face_geom(mesh_obj):
    """Build triangle face geometry from the evaluated (deformed) mesh."""
    mesh = mesh_obj.data
    if not mesh.uv_layers.active:
        raise RuntimeError("Mesh has no active UV layer")

    # Use evaluated mesh to pick up shape key / modifier deformations
    eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)

    bm = bmesh.new()
    bm.from_mesh(eval_mesh)
    bmesh.ops.triangulate(bm, faces=bm.faces[:])
    bm.faces.ensure_lookup_table()
    bm.verts.ensure_lookup_table()

    uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name)
    if uv_layer is None:
        bm.free()
        eval_obj.to_mesh_clear()
        raise RuntimeError("Could not access active UV layer")

    num_faces = len(bm.faces)
    face_pos = np.empty((num_faces, 3, 3), dtype=np.float32)
    face_uvs = np.empty((num_faces, 3, 2), dtype=np.float32)

    for fi, face in enumerate(bm.faces):
        for vi in range(3):
            co = face.verts[vi].co
            uv = face.loops[vi][uv_layer].uv
            face_pos[fi, vi] = (co.x, co.y, co.z)
            face_uvs[fi, vi] = (uv.x, uv.y)

    bm.free()
    eval_obj.to_mesh_clear()
    return face_pos, face_uvs


def reconstruct_surface_points_and_frames(mesh_obj, uv_face_index_map, uv_bary_map):
    face_pos, face_uvs = build_face_geom(mesh_obj)

    height, width = uv_face_index_map.shape
    roots = np.zeros((height, width, 3), dtype=np.float32)
    Tu = np.zeros((height, width, 3), dtype=np.float32)
    Tv = np.zeros((height, width, 3), dtype=np.float32)
    N = np.zeros((height, width, 3), dtype=np.float32)

    ys, xs = np.where(uv_face_index_map >= 0)
    fids = uv_face_index_map[ys, xs].astype(np.int32)
    bary = uv_bary_map[ys, xs].astype(np.float32)

    p0 = face_pos[fids, 0]
    p1 = face_pos[fids, 1]
    p2 = face_pos[fids, 2]

    uv0 = face_uvs[fids, 0]
    uv1 = face_uvs[fids, 1]
    uv2 = face_uvs[fids, 2]

    roots_pts = (
        bary[:, 0:1] * p0 +
        bary[:, 1:2] * p1 +
        bary[:, 2:3] * p2
    )

    dp1 = p1 - p0
    dp2 = p2 - p0
    duv1 = uv1 - uv0
    duv2 = uv2 - uv0

    det = duv1[:, 0] * duv2[:, 1] - duv1[:, 1] * duv2[:, 0]
    safe = np.abs(det) > 1e-12
    det_safe = det.copy()
    det_safe[~safe] = 1.0

    Tu_pts = np.empty_like(dp1)
    Tv_pts = np.empty_like(dp1)

    Tu_pts[:, 0] = (dp1[:, 0] * duv2[:, 1] - dp2[:, 0] * duv1[:, 1]) / det_safe
    Tu_pts[:, 1] = (dp1[:, 1] * duv2[:, 1] - dp2[:, 1] * duv1[:, 1]) / det_safe
    Tu_pts[:, 2] = (dp1[:, 2] * duv2[:, 1] - dp2[:, 2] * duv1[:, 1]) / det_safe

    Tv_pts[:, 0] = (-dp1[:, 0] * duv2[:, 0] + dp2[:, 0] * duv1[:, 0]) / det_safe
    Tv_pts[:, 1] = (-dp1[:, 1] * duv2[:, 0] + dp2[:, 1] * duv1[:, 0]) / det_safe
    Tv_pts[:, 2] = (-dp1[:, 2] * duv2[:, 0] + dp2[:, 2] * duv1[:, 0]) / det_safe

    N_pts = np.cross(dp1, dp2)

    def normalize(v):
        lens = np.linalg.norm(v, axis=1, keepdims=True)
        lens[lens < 1e-12] = 1.0
        return v / lens

    Tu_pts = normalize(Tu_pts)
    Tv_pts = normalize(Tv_pts)
    N_pts = normalize(N_pts)

    if np.any(~safe):
        Tu_pts[~safe] = normalize(dp1[~safe])
        Tv_pts[~safe] = normalize(np.cross(N_pts[~safe], Tu_pts[~safe]))
        N_pts[~safe] = normalize(np.cross(Tu_pts[~safe], Tv_pts[~safe]))

    roots[ys, xs] = roots_pts
    Tu[ys, xs] = Tu_pts
    Tv[ys, xs] = Tv_pts
    N[ys, xs] = N_pts

    return roots, Tu, Tv, N


def load_quantized_hair_map(hair_map_path: str):
    """
    Load either the uploaded .pt cache format or the legacy .npz format.

    Returns:
      hair_q: [H, W, S-1, 3] float32
      scale: [3] float32
      samples: S
      hair_mask: [H, W] bool
    """
    path = require_usable_file(hair_map_path, "Hair map")
    suffix = path.suffix.lower()

    if suffix == ".pt":
        try:
            import torch
        except ImportError as exc:
            raise ImportError(
                "Reading uploaded .pt hair maps requires PyTorch in Blender's "
                "Python environment. Install torch for the Blender Python version."
            ) from exc

        data = torch.load(str(path), map_location="cpu")
        required = ["hair_q", "scale", "hair_mask"]
        missing = [key for key in required if key not in data]
        if missing:
            raise KeyError(f"Missing keys {missing} in PT hair map: {path}")

        hair_q = data["hair_q"].detach().cpu().numpy().astype(np.float32)
        scale = data["scale"].detach().cpu().numpy().astype(np.float32)
        hair_mask = data["hair_mask"].detach().cpu().numpy().astype(bool)
        samples = int(hair_q.shape[2]) + 1
        return hair_q, scale, samples, hair_mask

    if suffix == ".npz":
        data = np.load(str(path), allow_pickle=True)
        required = ["hair_offsets_local_q", "offset_scale"]
        missing = [key for key in required if key not in data]
        if missing:
            raise KeyError(f"Missing keys {missing} in NPZ hair map: {path}")

        hair_q = data["hair_offsets_local_q"].astype(np.float32)
        scale = data["offset_scale"].astype(np.float32)
        samples = (
            int(data["samples"])
            if "samples" in data
            else int(hair_q.shape[2]) + 1
        )
        hair_mask = np.abs(hair_q).sum(axis=(2, 3)) > 0
        return hair_q, scale, samples, hair_mask

    raise ValueError(f"Unsupported hair map extension: {path.suffix}")


def decode_hair_map(hair_map_path: str, meta_path: str, mesh_obj):
    hair_offsets_local_q, offset_scale, samples, hair_mask = (
        load_quantized_hair_map(hair_map_path)
    )

    group_names, guide_group_id_map, uv_face_index_map, uv_bary_map = (
        load_global_hair_meta(meta_path)
    )

    if samples < 1:
        raise ValueError(f"Invalid samples={samples} in hair map")

    height, width = guide_group_id_map.shape[:2]
    if hair_offsets_local_q.shape[:2] != (height, width):
        raise ValueError(
            "Shape mismatch between hair map and global metadata: "
            f"{hair_offsets_local_q.shape[:2]} vs {(height, width)}"
        )
    if hair_mask.shape[:2] != (height, width):
        raise ValueError(
            f"Hair mask shape mismatch: {hair_mask.shape[:2]} vs {(height, width)}"
        )
    if uv_face_index_map.shape[:2] != (height, width):
        raise ValueError(
            f"UV face map shape mismatch: {uv_face_index_map.shape[:2]} "
            f"vs {(height, width)}"
        )
    if uv_bary_map.shape[:2] != (height, width):
        raise ValueError(
            f"UV barycentric map shape mismatch: {uv_bary_map.shape[:2]} "
            f"vs {(height, width)}"
        )

    offsets_local = (
        hair_offsets_local_q / 127.0
    ) * offset_scale.reshape(1, 1, 1, 3)
    strands_by_group = {name: [] for name in group_names}

    roots_map, Tu_map, Tv_map, N_map = reconstruct_surface_points_and_frames(
        mesh_obj,
        uv_face_index_map,
        uv_bary_map,
    )

    valid_map = (
        (guide_group_id_map >= 0)
        & hair_mask
        & (uv_face_index_map >= 0)
    )
    ys, xs = np.where(valid_map)
    gids = guide_group_id_map[ys, xs].astype(np.int32)

    for y, x, gid in zip(ys, xs, gids):
        gid = int(gid)
        if gid < 0 or gid >= len(group_names):
            continue

        root = roots_map[y, x]
        Tu = Tu_map[y, x]
        Tv = Tv_map[y, x]
        normal = N_map[y, x]

        local = offsets_local[y, x]
        world_offsets = (
            local[:, 0:1] * Tu[None, :]
            + local[:, 1:2] * Tv[None, :]
            + local[:, 2:3] * normal[None, :]
        )

        strand = np.empty((samples, 3), dtype=np.float32)
        strand[0] = root
        if samples > 1:
            strand[1:] = root[None, :] + world_offsets

        strands_by_group[group_names[gid]].append(strand)

    for group_name, strands in list(strands_by_group.items()):
        if strands:
            strands_by_group[group_name] = np.stack(strands, axis=0)
        else:
            strands_by_group[group_name] = np.zeros(
                (0, samples, 3),
                dtype=np.float32,
            )

    total_strands = sum(value.shape[0] for value in strands_by_group.values())
    log(f"Decoded hair map: {hair_map_path}")
    log(f"  Samples per strand: {samples}")
    log(f"  Total guide strands: {total_strands}")

    return group_names, strands_by_group, samples



def sanitize_name(name):
    out = []
    for ch in str(name):
        if ch.isalnum() or ch in "._-":
            out.append(ch)
        else:
            out.append("_")
    s = "".join(out).strip("_")
    return s if s else "HairPart"


def build_curve_object_from_strands(obj_name, strands, root_uvs, mesh_obj):
    if len(strands) == 0:
        return None

    curve_data = bpy.data.curves.new(obj_name, type='CURVE')
    curve_data.dimensions = '3D'

    curve_obj = bpy.data.objects.new(obj_name, curve_data)
    bpy.context.collection.objects.link(curve_obj)

    curve_obj.parent = mesh_obj
    curve_obj.location = (0, 0, 0)
    curve_obj.rotation_euler = (0, 0, 0)
    curve_obj.scale = (1, 1, 1)

    for strand in strands:
        spline = curve_data.splines.new('POLY')
        spline.points.add(len(strand) - 1)
        for i, p in enumerate(strand):
            spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)

    if bpy.ops.object.mode_set.poll():
        bpy.ops.object.mode_set(mode='OBJECT')

    bpy.ops.object.select_all(action='DESELECT')
    curve_obj.select_set(True)
    bpy.context.view_layer.objects.active = curve_obj
    bpy.ops.object.convert(target='CURVES')

    curve_obj = bpy.context.view_layer.objects.active
    curves = curve_obj.data

    curves.surface = mesh_obj
    curves.surface_uv_map = mesh_obj.data.uv_layers.active.name

    if "surface_uv_coordinate" in curves.attributes:
        uv_attr = curves.attributes["surface_uv_coordinate"]
    else:
        uv_attr = curves.attributes.new(
            name="surface_uv_coordinate",
            type='FLOAT2',
            domain='CURVE'
        )

    for i in range(len(root_uvs)):
        uv_attr.data[i].vector = (float(root_uvs[i][0]), float(root_uvs[i][1]))

    log(f"  Created '{curve_obj.name}' with {len(strands)} guide strands")
    return curve_obj


def build_curve_object_from_strands_no_uv(obj_name, strands, mesh_obj):
    if len(strands) == 0:
        return None

    curve_data = bpy.data.curves.new(obj_name, type='CURVE')
    curve_data.dimensions = '3D'

    curve_obj = bpy.data.objects.new(obj_name, curve_data)
    bpy.context.collection.objects.link(curve_obj)

    curve_obj.matrix_world = mesh_obj.matrix_world.copy()

    for strand in strands:
        spline = curve_data.splines.new('POLY')
        spline.points.add(len(strand) - 1)
        for i, p in enumerate(strand):
            spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)

    if bpy.ops.object.mode_set.poll():
        bpy.ops.object.mode_set(mode='OBJECT')

    bpy.ops.object.select_all(action='DESELECT')
    curve_obj.select_set(True)
    bpy.context.view_layer.objects.active = curve_obj
    bpy.ops.object.convert(target='CURVES')

    curve_obj = bpy.context.view_layer.objects.active
    curve_obj.matrix_world = mesh_obj.matrix_world.copy()
    curve_obj.parent = mesh_obj
    curve_obj.matrix_parent_inverse = mesh_obj.matrix_world.inverted()

    curves = curve_obj.data
    curves.surface = mesh_obj

    log(f"  Created '{curve_obj.name}' with {len(strands)} guide strands (no UV attr)")
    return curve_obj


def describe_node_group_inputs(mod):
    if getattr(mod, "node_group", None) is None:
        return []
    items = []
    try:
        for item in mod.node_group.interface.items_tree:
            if getattr(item, "in_out", None) == 'INPUT':
                items.append((item.name, item.identifier, getattr(item, "socket_type", "")))
    except Exception:
        pass
    return items


def get_node_input_identifier_by_name(mod, display_name):
    for name, identifier, socket_type in describe_node_group_inputs(mod):
        if name == display_name:
            return identifier
    return None


def set_gn_input(mod, display_name, value):
    identifier = get_node_input_identifier_by_name(mod, display_name)
    if identifier is None:
        log(f"    [WARN] GN input '{display_name}' not found on '{mod.name}'")
        return False
    try:
        mod[identifier] = value
        return True
    except Exception as e:
        log(f"    [WARN] Failed to set '{display_name}' on '{mod.name}': {e}")
        return False


def find_gn_input_identifier_contains(mod, keywords):
    keywords = [k.lower() for k in keywords]
    for name, identifier, socket_type in describe_node_group_inputs(mod):
        lname = (name or "").lower()
        if all(k in lname for k in keywords):
            return identifier, name
    return None, None


def set_gn_input_by_keywords(mod, keywords, value):
    identifier, display_name = find_gn_input_identifier_contains(mod, keywords)
    if identifier is None:
        log(f"    [WARN] No GN input matching keywords {keywords} on '{mod.name}'")
        return False
    try:
        mod[identifier] = value
        log(f"    + {mod.name} '{display_name}' = {value}")
        return True
    except Exception as e:
        log(f"    [WARN] Failed setting '{display_name}' on '{mod.name}': {e}")
        return False


def debug_modifier_inputs(mod):
    log(f"--- Modifier inputs for {mod.name} ---")
    for name, identifier, socket_type in describe_node_group_inputs(mod):
        log(f"    name='{name}' identifier='{identifier}' socket_type='{socket_type}'")


def select_and_activate(obj):
    bpy.ops.object.select_all(action='DESELECT')
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj


def get_essentials_blend_path():
    candidates = []

    try:
        local_root = Path(bpy.utils.resource_path('LOCAL'))
        candidates.append(local_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
    except Exception:
        pass

    try:
        system_root = Path(bpy.utils.resource_path('SYSTEM'))
        candidates.append(system_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
    except Exception:
        pass

    try:
        user_datafiles = Path(bpy.utils.user_resource('DATAFILES'))
        candidates.append(user_datafiles / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
    except Exception:
        pass

    for p in candidates:
        if p.exists():
            return p

    raise FileNotFoundError(
        "Could not locate procedural_hair_node_assets.blend in Blender datafiles."
    )


def ensure_node_group_loaded_from_blend(node_group_name, blend_path):
    ng = bpy.data.node_groups.get(node_group_name)
    if ng is not None:
        return ng

    blend_path = Path(blend_path)
    if not blend_path.exists():
        raise FileNotFoundError(f"Blend library not found: {blend_path}")

    with bpy.data.libraries.load(str(blend_path), link=False) as (data_from, data_to):
        if node_group_name not in data_from.node_groups:
            raise RuntimeError(f"Node group '{node_group_name}' not found in {blend_path}")
        data_to.node_groups = [node_group_name]

    ng = bpy.data.node_groups.get(node_group_name)
    if ng is None:
        raise RuntimeError(f"Failed to append node group '{node_group_name}' from {blend_path}")
    return ng


def add_gn_modifier(curves_obj, node_group_name, modifier_name):
    select_and_activate(curves_obj)

    blend_path = get_essentials_blend_path()
    node_group = ensure_node_group_loaded_from_blend(node_group_name, blend_path)

    mod = curves_obj.modifiers.new(name=modifier_name, type='NODES')
    mod.node_group = node_group
    return mod


def try_add_gn_modifier(curves_obj, node_group_names, modifier_name):
    last_err = None
    for ng_name in node_group_names:
        try:
            mod = add_gn_modifier(curves_obj, ng_name, modifier_name)
            log(f"    + Loaded node group '{ng_name}' as '{modifier_name}'")
            return mod
        except Exception as e:
            last_err = e
    log(f"    [WARN] Could not load any of {node_group_names} for '{modifier_name}': {last_err}")
    return None


def add_custom_post_duplicate_modifier(curves_obj):
    select_and_activate(curves_obj)

    blend_path = get_essentials_blend_path()
    noise_ng = ensure_node_group_loaded_from_blend("Hair Curves Noise", blend_path)
    trim_ng = ensure_node_group_loaded_from_blend("Trim Hair Curves", blend_path)

    bpy.ops.object.modifier_add(type='NODES')
    mod = curves_obj.modifiers[-1]
    mod.name = "Custom Post Duplicate Trim"

    bpy.ops.node.new_geometry_node_group_assign()
    ng = mod.node_group
    ng.name = f"{curves_obj.name}_CustomPostDuplicateTrim"

    nodes = ng.nodes
    links = ng.links

    group_in = None
    group_out = None
    for node in nodes:
        if node.bl_idname == "NodeGroupInput":
            group_in = node
        elif node.bl_idname == "NodeGroupOutput":
            group_out = node

    if group_in is None or group_out is None:
        raise RuntimeError("Failed to get default GN group input/output nodes")

    for node in list(nodes):
        if node not in {group_in, group_out}:
            nodes.remove(node)

    group_in.location = (-1000, 0)
    group_out.location = (500, 0)

    try:
        id_node = nodes.new("GeometryNodeInputID")
    except RuntimeError:
        id_node = nodes.new("GeometryNodeInputIndex")
    id_node.location = (-1000, -220)

    random_value = nodes.new("FunctionNodeRandomValue")
    random_value.location = (-760, -220)
    random_value.data_type = 'BOOLEAN'
    random_value.inputs["Probability"].default_value = 0.08
    if "Seed" in random_value.inputs:
        random_value.inputs["Seed"].default_value = 0

    separate = nodes.new("GeometryNodeSeparateGeometry")
    separate.location = (-520, 0)
    separate.domain = 'CURVE'

    noise = nodes.new("GeometryNodeGroup")
    noise.location = (-220, -40)
    noise.node_tree = noise_ng

    trim = nodes.new("GeometryNodeGroup")
    trim.location = (40, -40)
    trim.node_tree = trim_ng

    join = nodes.new("GeometryNodeJoinGeometry")
    join.location = (260, 20)

    if "Factor" in noise.inputs:
        noise.inputs["Factor"].default_value = 1.0
    if "Distance" in noise.inputs:
        noise.inputs["Distance"].default_value = 0.002
    if "Shape" in noise.inputs:
        noise.inputs["Shape"].default_value = 0.5
    if "Scale" in noise.inputs:
        noise.inputs["Scale"].default_value = 1.0
    if "Scale Along Length" in noise.inputs:
        noise.inputs["Scale Along Length"].default_value = 1.0
    if "Offset" in noise.inputs:
        noise.inputs["Offset"].default_value = 0.0
    if "Cumulative Offset" in noise.inputs:
        noise.inputs["Cumulative Offset"].default_value = False
    if "Seed" in noise.inputs:
        noise.inputs["Seed"].default_value = 0

    if "Mask" in trim.inputs:
        trim.inputs["Mask"].default_value = 1.0
    if "Random Offset" in trim.inputs:
        trim.inputs["Random Offset"].default_value = 0.03
    if "Pin at Parameter" in trim.inputs:
        trim.inputs["Pin at Parameter"].default_value = 0.0
    if "Seed" in trim.inputs:
        trim.inputs["Seed"].default_value = 0
    if "Replace Length" in trim.inputs:
        trim.inputs["Replace Length"].default_value = False

    if "ID" in random_value.inputs:
        if "ID" in id_node.outputs:
            links.new(id_node.outputs["ID"], random_value.inputs["ID"])
        else:
            links.new(id_node.outputs["Index"], random_value.inputs["ID"])

    links.new(group_in.outputs["Geometry"], separate.inputs["Geometry"])
    links.new(random_value.outputs["Value"], separate.inputs["Selection"])

    links.new(separate.outputs["Selection"], noise.inputs["Geometry"])
    links.new(noise.outputs["Geometry"], trim.inputs["Geometry"])

    links.new(separate.outputs["Inverted"], join.inputs["Geometry"])
    links.new(trim.outputs["Geometry"], join.inputs["Geometry"])
    links.new(join.outputs["Geometry"], group_out.inputs["Geometry"])

    log(f"    + Custom Post Duplicate Trim on {curves_obj.name}")
    return mod


def setup_modifiers(curves_obj, group_name, mesh_obj, hair_info):
    is_mouse = group_name == "mouse_fur"
    is_face = group_name == "face_fur"
    is_ear = group_name == "ear_fur"

    profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "Set Hair Curve Profile")
    set_gn_input(profile_mod, "Radius", 0.00012)
    log("    + Set Hair Curve Profile (radius=0.0001)")

    add_custom_post_duplicate_modifier(curves_obj)

    if (not is_mouse) and (not is_face):
        if(not is_ear):
            mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves")
            set_gn_input(mod, "Amount", 8)
            set_gn_input(mod, "Radius", 0.007)
            set_gn_input(mod, "Distribution Shape", 1.0)
            log("    + Duplicate Hair Curves (radius=0.005, distribution_shape=1.0)")

        frizz_mod = try_add_gn_modifier(
            curves_obj,
            ["Frizz Hair Curves", "Hair Curves Frizz"],
            "Frizz Hair Curves"
        )
        if frizz_mod is not None:
            set_gn_input(frizz_mod, "Factor", 0.7)
            set_gn_input(frizz_mod, "Distance", 0.001)
            set_gn_input(frizz_mod, "Shape", 0.01)
            log("    + Frizz Hair Curves (factor=0.7, distance=0.001, shape=0.01)")
    else:
        log("    + Skip Duplicate Hair Curves for mouse_fur/face")

    if is_face or is_ear:
        mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves")
        set_gn_input(mod, "Amount", 3)
        set_gn_input(mod, "Radius", 0.005)
        set_gn_input(mod, "Distribution Shape", 1.0)



def delete_default_cube():
    cube = bpy.data.objects.get("Cube")
    if cube is None:
        return

    bpy.ops.object.select_all(action='DESELECT')
    cube.select_set(True)
    bpy.context.view_layer.objects.active = cube
    bpy.ops.object.delete()

    log("Deleted default Cube")


def clear_material_slots(obj):
    if not hasattr(obj.data, "materials"):
        return
    obj.data.materials.clear()


def assign_material(obj, material):
    if not hasattr(obj.data, "materials"):
        return
    obj.data.materials.clear()
    obj.data.materials.append(material)
    if hasattr(obj, "active_material"):
        obj.active_material = material


def extract_numeric_suffix(name: str):
    m = re.search(r"(\d+)$", name)
    return int(m.group(1)) if m else None


def natural_key(path: Path):
    parts = re.split(r"(\d+)", path.stem.lower())
    key = []
    for p in parts:
        if p.isdigit():
            key.append(int(p))
        else:
            key.append(p)
    key.append(path.suffix.lower())
    return key


def find_texture_for_obj(obj_path: str, textures_dir: str):
    """
    Match a shape OBJ to a texture by natural-sort index.

    This mirrors the dataset auxiliary-file rule after excluding hidden and
    macOS resource-fork files. For a group with five real shapes and five
    textures, only those five files participate in pairing.
    """
    obj_path = Path(obj_path).expanduser().resolve()
    textures_dir = Path(textures_dir).expanduser().resolve()
    shapes_dir = obj_path.parent.resolve()

    if not shapes_dir.is_dir():
        raise FileNotFoundError(f"Shapes directory not found: {shapes_dir}")
    if not textures_dir.is_dir():
        raise FileNotFoundError(f"Textures directory not found: {textures_dir}")
    if not is_usable_file(obj_path):
        raise FileNotFoundError(
            f"OBJ is missing or is a hidden/macOS metadata file: {obj_path}"
        )

    shape_files = sorted(
        [
            path
            for path in shapes_dir.iterdir()
            if is_usable_file(path)
            and path.suffix.lower() == ".obj"
        ],
        key=natural_key,
    )
    texture_files = sorted(
        [
            path
            for path in textures_dir.iterdir()
            if is_usable_file(path)
            and path.suffix.lower() in IMAGE_EXTS
        ],
        key=natural_key,
    )

    if not shape_files:
        raise FileNotFoundError(f"No usable shape OBJ files found in: {shapes_dir}")
    if not texture_files:
        raise FileNotFoundError(f"No usable texture files found in: {textures_dir}")

    try:
        shape_index = next(
            index
            for index, path in enumerate(shape_files)
            if path.resolve() == obj_path
        )
    except StopIteration as exc:
        raise FileNotFoundError(
            f"Could not find usable OBJ {obj_path.name} in: {shapes_dir}"
        ) from exc

    if len(texture_files) == 1:
        chosen = texture_files[0]
    elif shape_index < len(texture_files):
        chosen = texture_files[shape_index]
    else:
        raise IndexError(
            "Texture index out of range after hidden-file filtering. "
            f"usable_shapes={len(shape_files)}, "
            f"usable_textures={len(texture_files)}, "
            f"shape_index={shape_index}, obj={obj_path.name}"
        )

    log(
        "Texture matched by natural-sort index: "
        f"shape[{shape_index}]={obj_path.name} -> {chosen.name}; "
        f"usable_shapes={len(shape_files)}, "
        f"usable_textures={len(texture_files)}"
    )
    return chosen


def set_node_input_if_exists(node, input_name, value):
    if input_name in node.inputs:
        node.inputs[input_name].default_value = value


def set_enum_attr_if_exists(node, attr_names, value):
    for attr in attr_names:
        if hasattr(node, attr):
            try:
                setattr(node, attr, value)
                return True
            except Exception:
                pass
    return False


def create_mesh_material(mesh_obj, texture_path: str, normal_path: str, roughness_path: str, material_name="MeshMaterial"):
    texture_path = Path(texture_path).resolve()
    normal_path = Path(normal_path).resolve() if normal_path else None
    roughness_path = Path(roughness_path).resolve() if roughness_path else None

    if not is_usable_file(texture_path):
        raise FileNotFoundError(
            f"Mesh texture is missing or hidden: {texture_path}"
        )

    mat = bpy.data.materials.get(material_name)
    if mat is None:
        mat = bpy.data.materials.new(material_name)
    mat.use_nodes = True

    nt = mat.node_tree
    nodes = nt.nodes
    links = nt.links
    nodes.clear()

    out = nodes.new("ShaderNodeOutputMaterial")
    out.location = (700, 0)

    bsdf = nodes.new("ShaderNodeBsdfPrincipled")
    bsdf.location = (350, 0)
    set_node_input_if_exists(bsdf, "IOR", 1.5)

    tex_color = nodes.new("ShaderNodeTexImage")
    tex_color.location = (-450, 150)
    tex_color.image = open_image_color(str(texture_path))
    tex_color.interpolation = 'Linear'
    tex_color.extension = 'REPEAT'

    links.new(tex_color.outputs["Color"], bsdf.inputs["Base Color"])
    if "Alpha" in tex_color.outputs and "Alpha" in bsdf.inputs:
        links.new(tex_color.outputs["Alpha"], bsdf.inputs["Alpha"])

    if roughness_path is not None and is_usable_file(roughness_path):
        tex_rough = nodes.new("ShaderNodeTexImage")
        tex_rough.location = (-450, -50)
        tex_rough.image = open_image_simple(str(roughness_path), non_color=True)
        tex_rough.interpolation = 'Linear'
        tex_rough.extension = 'REPEAT'
        links.new(tex_rough.outputs["Color"], bsdf.inputs["Roughness"])
    else:
        set_node_input_if_exists(bsdf, "Roughness", 0.5)
        log("Roughness map not found; using constant roughness=0.5")

    if normal_path is not None and is_usable_file(normal_path):
        tex_normal = nodes.new("ShaderNodeTexImage")
        tex_normal.location = (-450, -250)
        tex_normal.image = open_image_simple(str(normal_path), non_color=True)
        tex_normal.interpolation = 'Linear'
        tex_normal.extension = 'REPEAT'

        normal_map = nodes.new("ShaderNodeNormalMap")
        normal_map.location = (-100, -250)
        set_node_input_if_exists(normal_map, "Strength", 1.0)
        links.new(tex_normal.outputs["Color"], normal_map.inputs["Color"])
        links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"])
    else:
        log("Normal map not found; using mesh normals")

    links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])

    try:
        mat.blend_method = 'HASHED'
    except Exception:
        pass
    try:
        mat.shadow_method = 'HASHED'
    except Exception:
        pass

    assign_material(mesh_obj, mat)
    log(f"Assigned mesh material: {mat.name}")
    return mat


def create_hair_material(texture_path: str, material_name="HairMaterial"):
    texture_path = require_usable_file(
        texture_path,
        "Hair texture",
    )

    mat = bpy.data.materials.get(material_name)
    if mat is None:
        mat = bpy.data.materials.new(material_name)
    mat.use_nodes = True

    nt = mat.node_tree
    nodes = nt.nodes
    links = nt.links
    nodes.clear()

    tex_mesh = nodes.new("ShaderNodeTexImage")
    tex_mesh.location = (-900, 200)
    tex_mesh.image = open_image_color(str(texture_path))
    tex_mesh.interpolation = 'Linear'
    tex_mesh.extension = 'REPEAT'

    tex_hair = nodes.new("ShaderNodeTexImage")
    tex_hair.location = (-900, -200)
    tex_hair.image = open_image_color(str(texture_path))
    tex_hair.interpolation = 'Linear'
    tex_hair.extension = 'REPEAT'

    bsdf = nodes.new("ShaderNodeBsdfPrincipled")
    bsdf.location = (-500, 180)
    set_node_input_if_exists(bsdf, "IOR", 1.5)
    set_node_input_if_exists(bsdf, "Roughness", 0.5)
    set_node_input_if_exists(bsdf, "Alpha", 1.0)

    hair_bsdf = nodes.new("ShaderNodeBsdfHairPrincipled")
    hair_bsdf.location = (-500, -220)

    set_enum_attr_if_exists(hair_bsdf, ["model", "distribution"], 'CHIANG')
    set_enum_attr_if_exists(hair_bsdf, ["parametrization"], 'COLOR')

    set_node_input_if_exists(hair_bsdf, "Roughness", 0.4)
    set_node_input_if_exists(hair_bsdf, "Radial Roughness", 0.6)
    set_node_input_if_exists(hair_bsdf, "Coat", 0.0)
    set_node_input_if_exists(hair_bsdf, "IOR", 1.5)
    set_node_input_if_exists(hair_bsdf, "Offset", math.radians(3.0))
    set_node_input_if_exists(hair_bsdf, "Random Roughness", 0.25)

    mix_main = nodes.new("ShaderNodeMixShader")
    mix_main.location = (-120, 20)
    if "Fac" in mix_main.inputs:
        mix_main.inputs["Fac"].default_value = 0.6

    transparent = nodes.new("ShaderNodeBsdfTransparent")
    transparent.location = (-120, -260)

    light_path = nodes.new("ShaderNodeLightPath")
    light_path.location = (-360, 320)

    mix_shadow = nodes.new("ShaderNodeMixShader")
    mix_shadow.location = (180, 50)

    out = nodes.new("ShaderNodeOutputMaterial")
    out.location = (420, 50)

    links.new(tex_mesh.outputs["Color"], bsdf.inputs["Base Color"])
    links.new(tex_hair.outputs["Color"], hair_bsdf.inputs["Color"])
    links.new(bsdf.outputs["BSDF"], mix_main.inputs[1])
    links.new(hair_bsdf.outputs["BSDF"], mix_main.inputs[2])
    links.new(light_path.outputs["Is Shadow Ray"], mix_shadow.inputs["Fac"])
    links.new(mix_main.outputs["Shader"], mix_shadow.inputs[1])
    links.new(transparent.outputs["BSDF"], mix_shadow.inputs[2])
    links.new(mix_shadow.outputs["Shader"], out.inputs["Surface"])

    try:
        mat.blend_method = 'HASHED'
    except Exception:
        pass
    try:
        mat.shadow_method = 'HASHED'
    except Exception:
        pass
    try:
        mat.use_backface_culling = False
    except Exception:
        pass

    log(f"Created hair material: {mat.name}")
    return mat


def setup_cycles_render(scene):
    scene.render.engine = 'CYCLES'
    scene.cycles.samples = 64
    try:
        scene.cycles.device = 'GPU'
    except Exception:
        pass
    try:
        scene.render.film_transparent = True
    except Exception:
        pass

    try:
        scene.view_layers["ViewLayer"].cycles.use_denoising = False
    except Exception:
        pass

    log("Set render engine to Cycles")


def setup_world_hdr(hdr_path: str):
    hdr_path = require_usable_file(hdr_path, "HDR image")

    scene = bpy.context.scene
    world = scene.world
    if world is None:
        world = bpy.data.worlds.new("World")
        scene.world = world

    world.use_nodes = True
    nt = world.node_tree
    nodes = nt.nodes
    links = nt.links
    nodes.clear()

    tex_coord = nodes.new("ShaderNodeTexCoord")
    tex_coord.location = (-900, 0)

    mapping = nodes.new("ShaderNodeMapping")
    mapping.location = (-700, 0)

    env_tex = nodes.new("ShaderNodeTexEnvironment")
    env_tex.location = (-500, 0)
    env_tex.image = bpy.data.images.load(filepath=str(hdr_path), check_existing=True)

    background = nodes.new("ShaderNodeBackground")
    background.location = (-220, 0)
    background.inputs["Strength"].default_value = random.uniform(0.4, 0.6)

    world_out = nodes.new("ShaderNodeOutputWorld")
    world_out.location = (300, 0)

    links.new(tex_coord.outputs["Generated"], mapping.inputs["Vector"])
    links.new(mapping.outputs["Vector"], env_tex.inputs["Vector"])
    links.new(env_tex.outputs["Color"], background.inputs["Color"])
    links.new(background.outputs["Background"], world_out.inputs["Surface"])

    scene.render.film_transparent = True
    log(f"Set HDR world lighting: {hdr_path}")

def compute_mesh_bbox_center_and_radius(mesh_obj):
    """Compute the world-space bounding box center and enclosing sphere radius."""
    bbox_corners = [mesh_obj.matrix_world @ Vector(c) for c in mesh_obj.bound_box]
    bbox_min = Vector((
        min(c.x for c in bbox_corners),
        min(c.y for c in bbox_corners),
        min(c.z for c in bbox_corners),
    ))
    bbox_max = Vector((
        max(c.x for c in bbox_corners),
        max(c.y for c in bbox_corners),
        max(c.z for c in bbox_corners),
    ))
    center = (bbox_min + bbox_max) / 2.0
    radius = (bbox_max - bbox_min).length / 2.0
    return center, radius


def ensure_camera(mesh_obj=None, h_range=(-20, 20), v_range=(10, 30), render_size=1024, padding=0.9):
    """Create/reuse a camera with random orbit around the mesh.

    Args:
        mesh_obj: The target mesh. If None, falls back to a fixed position.
        h_range: (min_deg, max_deg) horizontal rotation range around the object.
                 0 = front (+X axis looking at center), negative = left, positive = right.
        v_range: (min_deg, max_deg) vertical elevation range.
                 0 = horizon level, 45 = looking down at 45 degrees.
        render_size: Output image resolution (square).
        padding: Multiplier on the camera distance to ensure the whole mesh
                 (including hair) fits in frame. >1.0 adds margin.
    """
    cam_obj = bpy.data.objects.get("RenderCamera")
    if cam_obj is None or cam_obj.type != 'CAMERA':
        cam_data = bpy.data.cameras.new("RenderCamera")
        cam_obj = bpy.data.objects.new("RenderCamera", cam_data)
        bpy.context.collection.objects.link(cam_obj)

    scene = bpy.context.scene
    scene.camera = cam_obj

    # Set render resolution to 512x512
    scene.render.resolution_x = render_size
    scene.render.resolution_y = render_size
    scene.render.resolution_percentage = 100

    if mesh_obj is None:
        # Fallback: fixed position
        cam_obj.location = (2.0, 0.0, 0.0)
        cam_obj.rotation_euler = (
            math.radians(90.0),
            math.radians(0.0),
            math.radians(90.0),
        )
        log("Set camera at fixed fallback position (no mesh provided)")
        return cam_obj

    # Compute mesh bounding sphere
    center, radius = compute_mesh_bbox_center_and_radius(mesh_obj)
    if radius < 1e-6:
        radius = 1.0

    # Random angles
    h_deg = random.uniform(h_range[0], h_range[1])
    v_deg = random.uniform(v_range[0], v_range[1])
    h_rad = math.radians(h_deg)
    v_rad = math.radians(v_deg)

    # Compute camera distance so the bounding sphere fits in the FOV
    cam_data = cam_obj.data
    cam_data.sensor_fit = 'AUTO'
    # cam_data.angle = 75
    # cam_data.fov = 75
    cam_data.lens = 75

    print(cam_data.angle)
    fov = cam_data.angle  # full horizontal FOV in radians
    half_fov = fov / 2.0

    # Distance from center so the sphere of size (radius * padding) fits
    distance = (radius * padding) / math.sin(half_fov)
    if distance < 0.01:
        distance = 2.0

    # Spherical coordinates -> cartesian offset from center
    # h_rad=0 means looking from +X toward center (front view)
    # v_rad=0 means at horizon level, v_rad>0 means elevated (looking down)
    cam_x = center.x + distance * math.cos(v_rad) * math.cos(h_rad)
    cam_y = center.y + distance * math.cos(v_rad) * math.sin(h_rad)
    cam_z = center.z + distance * math.sin(v_rad)

    cam_obj.location = (cam_x, cam_y, cam_z)

    # Point camera at center using a track-to constraint (most robust)
    # Remove any existing track-to constraint first
    for c in list(cam_obj.constraints):
        if c.type == 'TRACK_TO':
            cam_obj.constraints.remove(c)

    # Create an empty at the mesh center as the track target
    target_empty = bpy.data.objects.get("CameraTarget")
    if target_empty is None:
        target_empty = bpy.data.objects.new("CameraTarget", None)
        bpy.context.collection.objects.link(target_empty)
    target_empty.location = center
    target_empty.empty_display_size = 0.01
    target_empty.hide_viewport = True
    target_empty.hide_render = True

    constraint = cam_obj.constraints.new(type='TRACK_TO')
    constraint.target = target_empty
    constraint.track_axis = 'TRACK_NEGATIVE_Z'
    constraint.up_axis = 'UP_Y'

    # Force update so the constraint takes effect
    bpy.context.view_layer.update()

    log(
        f"Camera: h={h_deg:.1f}° v={v_deg:.1f}° dist={distance:.3f} "
        f"center=({center.x:.3f},{center.y:.3f},{center.z:.3f}) "
        f"render={render_size}x{render_size}"
    )
    return cam_obj


def sample_image_luminance_at_uv(img, uv, pixels_np=None):
    width, height = img.size

    if pixels_np is None:
        pixel_count = width * height * 4
        pixels_np = np.empty(pixel_count, dtype=np.float32)
        img.pixels.foreach_get(pixels_np)
        pixels_np = pixels_np.reshape((height, width, 4))

    u = float(np.clip(uv[0], 0.0, 1.0))
    v = float(np.clip(uv[1], 0.0, 1.0))
    xi = int(u * (width - 1))
    yi = int(v * (height - 1))

    rgba = pixels_np[yi, xi]
    lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]
    return float(lum)


def remove_curve_uv_attributes(curves_obj):
    curves = curves_obj.data

    try:
        curves.surface_uv_map = ""
    except Exception:
        pass

    for attr_name in ["surface_uv_coordinate", "uv_map", "UVMap", "UV", "map1"]:
        attr = curves.attributes.get(attr_name)
        if attr is not None:
            try:
                curves.attributes.remove(attr)
                log(f"  Removed curve attribute: {attr_name}")
            except Exception as e:
                log(f"  [WARN] Failed removing curve attribute '{attr_name}': {e}")


def create_underhair_guides_from_mesh(mesh_obj, mask_image_path, strand_length=0.01, threshold=0.05):
    """Create underhair guide strands using the evaluated (deformed) mesh."""
    mesh = mesh_obj.data
    if not mesh.uv_layers.active:
        raise RuntimeError("Mesh has no active UV layer; underhair mask sampling requires UVs.")

    mask_img = open_image_simple(str(mask_image_path), non_color=True)
    width, height = mask_img.size

    pixel_count = width * height * 4
    pixels_np = np.empty(pixel_count, dtype=np.float32)
    mask_img.pixels.foreach_get(pixels_np)
    pixels_np = pixels_np.reshape((height, width, 4))

    # Use evaluated mesh for vertex positions and normals
    eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)

    total_loops = len(eval_mesh.loops)
    loop_uvs = np.empty(total_loops * 2, dtype=np.float32)
    eval_mesh.uv_layers.active.data.foreach_get("uv", loop_uvs)
    loop_uvs = loop_uvs.reshape((total_loops, 2))

    loop_verts = np.empty(total_loops, dtype=np.int32)
    eval_mesh.loops.foreach_get("vertex_index", loop_verts)

    num_verts = len(eval_mesh.vertices)
    uv_sum = np.zeros((num_verts, 2), dtype=np.float64)
    uv_cnt = np.zeros(num_verts, dtype=np.int32)

    np.add.at(uv_sum[:, 0], loop_verts, loop_uvs[:, 0])
    np.add.at(uv_sum[:, 1], loop_verts, loop_uvs[:, 1])
    np.add.at(uv_cnt, loop_verts, 1)

    valid = uv_cnt > 0
    avg_uv = np.zeros((num_verts, 2), dtype=np.float64)
    avg_uv[valid] = uv_sum[valid] / uv_cnt[valid][:, None]

    strands = []
    weights = np.zeros(num_verts, dtype=np.float32)

    for vid in range(num_verts):
        if not valid[vid]:
            continue

        uv = avg_uv[vid]
        w = sample_image_luminance_at_uv(mask_img, uv, pixels_np=pixels_np)
        weights[vid] = w

        if w <= threshold:
            continue

        root = eval_mesh.vertices[vid].co.copy()
        normal = eval_mesh.vertices[vid].normal.normalized()
        tip = root + normal * float(strand_length)

        strand = np.stack([
            np.array((root.x, root.y, root.z), dtype=np.float32),
            np.array((tip.x, tip.y, tip.z), dtype=np.float32),
        ], axis=0)
        strands.append(strand)

    eval_obj.to_mesh_clear()

    old_vg = mesh_obj.vertex_groups.get(UNDERHAIR_MASK_GROUP)
    if old_vg is not None:
        mesh_obj.vertex_groups.remove(old_vg)
    vg = mesh_obj.vertex_groups.new(name=UNDERHAIR_MASK_GROUP)

    for vid, w in enumerate(weights):
        if w > 0.0:
            vg.add([vid], float(w), 'REPLACE')

    log(f"Created underhair guides: {len(strands)} strands")
    return strands, vg, mask_img


def setup_underhair_modifiers(curves_obj, mesh_obj, mask_img, trim_length=0.01):
    profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "UnderHair Profile")
    set_gn_input(profile_mod, "Radius", 0.0001)
    log("    + UnderHair Profile (radius=0.0001)")

    interp_mod = add_gn_modifier(curves_obj, "Interpolate Hair Curves", "UnderHair Interpolate")

    try:
        interp_mod["Input_2"] = mesh_obj
        log(f"    + UnderHair Interpolate Input_2 = {mesh_obj.name}")
    except Exception as e:
        log(f"    [WARN] Failed setting UnderHair Interpolate Input_2: {e}")

    set_gn_input(interp_mod, "Surface", mesh_obj)
    set_gn_input(interp_mod, "Surface Object", mesh_obj)
    set_gn_input(interp_mod, "Mesh", mesh_obj)

    density_set = False
    density_set |= set_gn_input(interp_mod, "Surface Density", UNDERHAIR_INTERP_DENSITY)
    density_set |= set_gn_input(interp_mod, "Density", UNDERHAIR_INTERP_DENSITY)
    density_set |= set_gn_input_by_keywords(interp_mod, ["density"], UNDERHAIR_INTERP_DENSITY)
    density_set |= set_gn_input_by_keywords(interp_mod, ["surface", "density"], UNDERHAIR_INTERP_DENSITY)

    if not density_set:
        log("    [WARN] Could not find interpolation density socket; value may remain default")

    set_gn_input(interp_mod, "Interpolation Quality", 6)
    set_gn_input(interp_mod, "Variation Level", 0.15)
    set_gn_input(interp_mod, "Guide Mask", 0.0)
    set_gn_input(interp_mod, "Use Guide Mask", False)

    interp_tex_id = get_node_input_identifier_by_name(interp_mod, "Mask Texture")
    if interp_tex_id is not None:
        try:
            interp_mod[interp_tex_id] = mask_img
            log("    + UnderHair Interpolate mask texture = merged.png")
        except Exception as e:
            log(f"    [WARN] Failed to assign interpolate mask texture: {e}")

    log("    + UnderHair Interpolate configured")

    noise_mod = add_gn_modifier(curves_obj, "Hair Curves Noise", "UnderHair Noise")
    set_gn_input(noise_mod, "Factor", 1.0)
    set_gn_input(noise_mod, "Distance", 0.0015)
    set_gn_input(noise_mod, "Shape", 0.5)
    set_gn_input(noise_mod, "Scale", 18.0)
    set_gn_input(noise_mod, "Scale Along Length", 1.0)
    set_gn_input(noise_mod, "Offset", 0.0)
    set_gn_input(noise_mod, "Cumulative Offset", False)
    set_gn_input(noise_mod, "Seed", 0)
    log("    + UnderHair Noise")

    frizz_mod = try_add_gn_modifier(
        curves_obj,
        ["Frizz Hair Curves", "Hair Curves Frizz"],
        "UnderHair Frizz"
    )
    if frizz_mod is not None:
        set_gn_input(frizz_mod, "Amount", 0.6)
        set_gn_input(frizz_mod, "Radius", 0.001)
        set_gn_input(frizz_mod, "Frequency", 12.0)
        set_gn_input(frizz_mod, "Seed", 0)
        set_gn_input(frizz_mod, "Mask", 1.0)

        frizz_tex_id = get_node_input_identifier_by_name(frizz_mod, "Mask Texture")
        if frizz_tex_id is not None:
            try:
                frizz_mod[frizz_tex_id] = mask_img
                log("    + UnderHair Frizz mask texture = merged.png")
            except Exception as e:
                log(f"    [WARN] Failed to assign frizz mask texture: {e}")

        log("    + UnderHair Frizz")

    trim_mod = add_gn_modifier(curves_obj, "Trim Hair Curves", "UnderHair Trim")
    set_gn_input(trim_mod, "Mask", 1.0)
    set_gn_input(trim_mod, "Random Offset", 0.0)
    set_gn_input(trim_mod, "Pin at Parameter", 0.0)
    set_gn_input(trim_mod, "Replace Length", True)
    set_gn_input(trim_mod, "Length", float(trim_length))

    trim_tex_id = get_node_input_identifier_by_name(trim_mod, "Mask Texture")
    if trim_tex_id is not None:
        try:
            trim_mod[trim_tex_id] = mask_img
            log("    + UnderHair Trim mask texture = merged.png")
        except Exception as e:
            log(f"    [WARN] Failed to assign trim mask texture: {e}")

    log(f"    + UnderHair Trim (length={trim_length})")


def create_underhair_if_available(mesh_obj, mesh_material, mask_image_path):
    mask_path = Path(mask_image_path).resolve()
    if not mask_path.exists():
        log(f"Underhair mask not found; skipping underhair: {mask_path}")
        return None
    return create_underhair_on_mesh(
        mesh_obj=mesh_obj,
        mesh_material=mesh_material,
        mask_image_path=str(mask_path),
    )


def create_underhair_on_mesh(mesh_obj, mesh_material, mask_image_path):
    log("Creating underhair from mesh surface...")

    strands, mask_vg, mask_img = create_underhair_guides_from_mesh(
        mesh_obj=mesh_obj,
        mask_image_path=str(mask_image_path),
        strand_length=UNDERHAIR_LENGTH,
        threshold=0.05,
    )

    if len(strands) == 0:
        log("  [WARN] No underhair strands created from mask.")
        return None

    underhair_obj = build_curve_object_from_strands_no_uv(
        obj_name="underhair",
        strands=strands,
        mesh_obj=mesh_obj,
    )
    if underhair_obj is None:
        return None

    remove_curve_uv_attributes(underhair_obj)
    assign_material(underhair_obj, mesh_material)

    setup_underhair_modifiers(
        curves_obj=underhair_obj,
        mesh_obj=mesh_obj,
        mask_img=mask_img,
        trim_length=UNDERHAIR_LENGTH,
    )

    log("Underhair object created successfully")
    return underhair_obj


def get_child_hair_objects(surface_obj):
    out = []
    for obj in bpy.data.objects:
        if obj.parent == surface_obj and obj.type in {'CURVES', 'MESH'}:
            out.append(obj)
    return out


def ensure_curve_bound_to_surface(curves_obj, surface_obj):
    if curves_obj.type != 'CURVES':
        return
    curves = curves_obj.data
    curves.surface = surface_obj
    if surface_obj.data.uv_layers.active is not None:
        try:
            curves.surface_uv_map = surface_obj.data.uv_layers.active.name
        except Exception:
            pass
    curves_obj.parent = surface_obj
    try:
        curves_obj.matrix_parent_inverse = surface_obj.matrix_world.inverted()
    except Exception:
        pass


def add_or_rebind_surface_deform(mesh_hair_obj, surface_obj, modifier_name="SurfaceDeformToBody"):
    mod = mesh_hair_obj.modifiers.get(modifier_name)
    if mod is None:
        mod = mesh_hair_obj.modifiers.new(name=modifier_name, type='SURFACE_DEFORM')

    mod.target = surface_obj
    mod.falloff = 4.0

    try:
        bpy.ops.object.mode_set(mode='OBJECT')
    except Exception:
        pass

    bpy.ops.object.select_all(action='DESELECT')
    mesh_hair_obj.select_set(True)
    bpy.context.view_layer.objects.active = mesh_hair_obj

    try:
        bpy.ops.object.surfacedeform_bind(modifier=mod.name)
        log(f"Bound Surface Deform on '{mesh_hair_obj.name}' -> '{surface_obj.name}'")
    except Exception as e:
        log(f"[WARN] Failed to bind Surface Deform on '{mesh_hair_obj.name}': {e}")

    return mod


def apply_surface_deform_or_surface_bind_to_all_hair(surface_obj, hair_objects=None):
    if hair_objects is None:
        hair_objects = get_child_hair_objects(surface_obj)

    for obj in hair_objects:
        if obj.type == 'CURVES':
            ensure_curve_bound_to_surface(obj, surface_obj)
            log(f"Rebound curves surface for '{obj.name}'")
        elif obj.type == 'MESH':
            add_or_rebind_surface_deform(obj, surface_obj)

    bpy.context.view_layer.update()
    return hair_objects


def refresh_hair_after_shape_change(surface_obj, hair_objects=None):
    if hair_objects is None:
        hair_objects = get_child_hair_objects(surface_obj)

    for obj in hair_objects:
        if obj.type == 'CURVES':
            ensure_curve_bound_to_surface(obj, surface_obj)

        for mod in obj.modifiers:
            try:
                mod.show_viewport = False
                mod.show_viewport = True
            except Exception:
                pass

        obj.update_tag()

    surface_obj.update_tag()

    # Force a full depsgraph evaluation so all curves re-snap
    depsgraph = bpy.context.evaluated_depsgraph_get()
    depsgraph.update()
    bpy.context.view_layer.update()

    log(f"Refreshed {len(hair_objects)} hair objects after shape change")


def load_hair_scene(
    obj_path: str,
    mesh_object_name: str = "DeformedMesh",
    save_blend_path: str = None,
    render_filename: str = None,
):
    """Load mesh + hair without any deformation applied.
    Hair is built on the base (undeformed) mesh geometry.
    """
    t_start = time.perf_counter()
    paths = resolve_paths_from_obj(obj_path)
    scene = bpy.context.scene

    delete_default_cube()
    setup_cycles_render(scene)
    log("Selecting random HDR...")
    hdr_path = pick_random_hdr_image(str(paths["hdr_dir"]))

    log("Setting up world HDR...")
    setup_world_hdr(str(hdr_path))

    log("Importing mesh...")
    mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name)

    if not mesh_obj.data.uv_layers:
        raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.")

    # # Set up camera after mesh is loaded so it can frame the object
    # ensure_camera(mesh_obj)

    log("Resolving dataset texture...")
    raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"]))
    texture_path = remove_green_screen_from_image(
        src_image_path=str(raw_texture_path),
        out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"),
        green_threshold=0.45,
        green_margin=0.08,
    )
    log(f"Using processed texture: {texture_path}")

    log("Creating mesh material...")
    mesh_mat = create_mesh_material(
        mesh_obj=mesh_obj,
        texture_path=str(texture_path),
        normal_path=str(paths["mesh_normal"]),
        roughness_path=str(paths["mesh_roughness"]),
        material_name=f"{mesh_object_name}_MeshMaterial",
    )

    log("Creating hair material...")
    hair_mat = create_hair_material(
        texture_path=str(texture_path),
        material_name=f"{mesh_object_name}_HairMaterial",
    )

    log("Creating underhair...")
    underhair_obj = create_underhair_if_available(
        mesh_obj=mesh_obj,
        mesh_material=mesh_mat,
        mask_image_path=str(UNDERHAIR_MASK_PATH),
    )

    # Density and length maps are optional for this visualization pipeline.
    # Strand positions and lengths are reconstructed directly from the hair map.
    hair_info = {}

    hair_map_path = str(paths["hair_map"])
    log(f"Loading UV-local 512 hair map: {hair_map_path}")
    log(f"Loading global hair meta: {paths['hair_meta']}")
    group_names, strands_by_group, samples = decode_hair_map(
        hair_map_path,
        str(paths["hair_meta"]),
        mesh_obj,
    )
    log(f"  Samples per strand: {samples}")

    created_objects = []

    for group_name in group_names:
        if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS):
            log(f"  [SKIP] Group '{group_name}' ignored by keyword")
            continue

        strands = strands_by_group.get(group_name)
        if strands is None or strands.shape[0] == 0:
            log(f"  [SKIP] Group '{group_name}' has 0 strands")
            continue

        log(f"  Processing group: {group_name} ({strands.shape[0]} strands)")

        roots = strands[:, 0, :]
        root_uvs = compute_root_uvs(roots, mesh_obj)

        curves_obj = build_curve_object_from_strands(
            sanitize_name(group_name),
            strands,
            root_uvs,
            mesh_obj,
        )
        if curves_obj is None:
            continue

        assign_material(curves_obj, hair_mat)

        log(f"  Setting up modifiers for: {curves_obj.name}")
        setup_modifiers(curves_obj, group_name, mesh_obj, hair_info)

        created_objects.append(curves_obj)

    if underhair_obj is not None:
        created_objects.append(underhair_obj)

    loaded_hair_map = str(paths["hair_map_curl_out"])
    log(f"Loaded hair map from: {loaded_hair_map}")

    if save_blend_path:
        save_blend_path = str(Path(save_blend_path).resolve())
        bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
        log(f"Saved blend file: {save_blend_path}")

    render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename)


    elapsed = time.perf_counter() - t_start
    log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s")
    for obj in created_objects:
        log(f"  {obj.name}")

    return mesh_obj, created_objects


def apply_deformed_shape_key_to_loaded_scene(
    source_obj_path: str,
    mesh_obj,
    hair_objects,
    deformed_obj_path: str = None,
    shape_key_name: str = "DeformedShape",
    shape_key_value: float = 1.0,
):
    """Legacy shape-key approach. Hair may not follow correctly for curves
    objects unless the curves were built on the already-deformed mesh.
    Prefer load_hair_scene_with_deformed_shape() which deforms first.
    """
    deformed_path = resolve_corresponding_deformed_shape_path(
        source_obj_path,
        deformed_obj_path=deformed_obj_path,
    )
    log(f"Using deformed shape OBJ: {deformed_path}")

    log("Applying surface deform / surface binding to all hair before shape key...")
    apply_surface_deform_or_surface_bind_to_all_hair(mesh_obj, hair_objects)

    log("Creating shape key from deformed mesh...")
    sk = import_obj_as_shape_key(mesh_obj, str(deformed_path), shape_key_name)
    sk.value = float(shape_key_value)

    log("Refreshing hair after shape key update...")
    refresh_hair_after_shape_change(mesh_obj, hair_objects)

    return sk


def load_hair_scene_with_deformed_shape(
    obj_path: str,
    mesh_object_name: str = "DeformedMesh",
    deformed_obj_path: str = None,
    shape_key_name: str = "DeformedShape",
    shape_key_value: float = 1.0,
    save_blend_path: str = None,
    use_shape_key: bool = False,
    render_filename: str = None,
):
    """Load mesh, apply deformation FIRST, then build all hair on the
    already-deformed geometry so that hair roots and strands match the
    deformed surface.

    Args:
        use_shape_key: If True, use the legacy shape-key approach (hair is
            built on the base mesh then shape key is applied afterward).
            If False (default), the deformed vertex positions are written
            directly into the base mesh before hair is created, so hair
            is naturally placed on the deformed surface.
    """
    if use_shape_key:
        # --- Legacy path: build hair on base mesh, then apply shape key ---
        mesh_obj, created_objects = load_hair_scene(
            obj_path=obj_path,
            mesh_object_name=mesh_object_name,
            save_blend_path=None,
            render_filename=render_filename,
        )

        sk = apply_deformed_shape_key_to_loaded_scene(
            source_obj_path=obj_path,
            mesh_obj=mesh_obj,
            hair_objects=created_objects,
            deformed_obj_path=deformed_obj_path,
            shape_key_name=shape_key_name,
            shape_key_value=shape_key_value,
        )

        if save_blend_path:
            save_blend_path = str(Path(save_blend_path).resolve())
            bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
            log(f"Saved blend file: {save_blend_path}")

        return mesh_obj, created_objects, sk

    # --- New path: deform mesh first, then build hair on deformed geometry ---
    t_start = time.perf_counter()
    paths = resolve_paths_from_obj(obj_path)
    scene = bpy.context.scene

    delete_default_cube()
    setup_cycles_render(scene)
    log("Selecting random HDR...")
    hdr_path = pick_random_hdr_image(str(paths["hdr_dir"]))

    log("Setting up world HDR...")
    setup_world_hdr(str(hdr_path))

    # Step 1: Import the base mesh
    log("Importing base mesh...")
    mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name)

    if not mesh_obj.data.uv_layers:
        raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.")

    # Step 2: Apply deformed vertex positions directly to the base mesh
    if deformed_obj_path:
        deformed_path = resolve_corresponding_deformed_shape_path(
            obj_path,
            deformed_obj_path=deformed_obj_path,
        )
        log(f"Applying deformed shape directly from: {deformed_path}")
        apply_deformed_shape_directly(mesh_obj, str(deformed_path))
        bpy.context.view_layer.update()
    else:
        log("No deformed OBJ supplied; using the original mesh geometry")

    # # Set up camera after deformation so it frames the deformed mesh correctly
    # ensure_camera(mesh_obj)

    # Step 3: Set up materials
    log("Resolving dataset texture...")
    raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"]))
    texture_path = remove_green_screen_from_image(
        src_image_path=str(raw_texture_path),
        out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"),
        green_threshold=0.45,
        green_margin=0.08,
    )
    log(f"Using processed texture: {texture_path}")

    log("Creating mesh material...")
    mesh_mat = create_mesh_material(
        mesh_obj=mesh_obj,
        texture_path=str(texture_path),
        normal_path=str(paths["mesh_normal"]),
        roughness_path=str(paths["mesh_roughness"]),
        material_name=f"{mesh_object_name}_MeshMaterial",
    )

    log("Creating hair material...")
    hair_mat = create_hair_material(
        texture_path=str(texture_path),
        material_name=f"{mesh_object_name}_HairMaterial",
    )

    # Step 4: Create underhair (now on deformed mesh)
    log("Creating underhair on deformed mesh...")
    underhair_obj = create_underhair_if_available(
        mesh_obj=mesh_obj,
        mesh_material=mesh_mat,
        mask_image_path=str(UNDERHAIR_MASK_PATH),
    )

    # Step 5: Load density/length maps
    # Density and length maps are optional for this visualization pipeline.
    # Strand positions and lengths are reconstructed directly from the hair map.
    hair_info = {}

    # Step 6: Decode hair map (reconstructs strand positions on deformed geometry)
    hair_map_path = str(paths["hair_map"])
    log(f"Loading UV-local 512 hair map: {hair_map_path}")
    log(f"Loading global hair meta: {paths['hair_meta']}")
    group_names, strands_by_group, samples = decode_hair_map(
        hair_map_path,
        str(paths["hair_meta"]),
        mesh_obj,
    )
    log(f"  Samples per strand: {samples}")

    # Step 7: Build hair curve objects on deformed mesh
    created_objects = []

    for group_name in group_names:
        if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS):
            log(f"  [SKIP] Group '{group_name}' ignored by keyword")
            continue

        strands = strands_by_group.get(group_name)
        if strands is None or strands.shape[0] == 0:
            log(f"  [SKIP] Group '{group_name}' has 0 strands")
            continue

        log(f"  Processing group: {group_name} ({strands.shape[0]} strands)")

        roots = strands[:, 0, :]
        root_uvs = compute_root_uvs(roots, mesh_obj)

        curves_obj = build_curve_object_from_strands(
            sanitize_name(group_name),
            strands,
            root_uvs,
            mesh_obj,
        )
        if curves_obj is None:
            continue

        assign_material(curves_obj, hair_mat)

        log(f"  Setting up modifiers for: {curves_obj.name}")
        setup_modifiers(curves_obj, group_name, mesh_obj, hair_info)

        created_objects.append(curves_obj)

    if underhair_obj is not None:
        created_objects.append(underhair_obj)

    loaded_hair_map = str(paths["hair_map_curl_out"])
    log(f"Loaded hair map from: {loaded_hair_map}")

    if save_blend_path:
        save_blend_path = str(Path(save_blend_path).resolve())
        bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
        log(f"Saved blend file: {save_blend_path}")

    render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename)
    # TODO
    # render_and_save_image(str(render_output_path))

    elapsed = time.perf_counter() - t_start
    log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s")
    for obj in created_objects:
        log(f"  {obj.name}")

    # No shape key was created in this path, return None for sk
    return mesh_obj, created_objects, None


if __name__ == "__main__":
    argv = sys.argv
    user_args = argv[argv.index("--") + 1:] if "--" in argv else []

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--obj_path",
        type=str,
        default=None,
        help=(
            "OBJ inside <root>/<species>/dataset/<group>/shapes. "
            "When omitted, a valid case is discovered automatically."
        ),
    )
    parser.add_argument("--species", type=str, default="small_cat")
    parser.add_argument(
        "--group_name",
        type=str,
        default="groupA_different_breeds_buoumao",
    )
    parser.add_argument("--sample_index", type=int, default=3)
    parser.add_argument("--mesh_object_name", type=str, default="DeformedMesh")
    parser.add_argument(
        "--deformed_obj_path",
        type=str,
        default=None,
        help="Optional deformed OBJ. The original mesh is used when omitted.",
    )
    parser.add_argument("--shape_key_name", type=str, default="DeformedShape")
    parser.add_argument("--shape_key_value", type=float, default=1.0)
    parser.add_argument("--save_blend_path", type=str, default=None)
    parser.add_argument("--render_filename", type=str, default=None)
    parser.add_argument(
        "--use_shape_key",
        action="store_true",
        default=False,
        help="Use legacy shape-key approach instead of direct vertex overwrite",
    )
    args = parser.parse_args(user_args)

    if args.obj_path is None:
        discovered_obj, discovered_deformed = discover_dataset_case(
            root=ANIMALLIFT_ROOT,
            species=args.species,
            group_name=args.group_name,
            sample_index=args.sample_index,
        )
        args.obj_path = str(discovered_obj)
        if args.deformed_obj_path is None and discovered_deformed is not None:
            args.deformed_obj_path = str(discovered_deformed)

    print(f"obj_path: {args.obj_path}")
    print(f"mesh_object_name: {args.mesh_object_name}")
    print(f"deformed_obj_path: {args.deformed_obj_path}")
    print(f"shape_key_name: {args.shape_key_name}")
    print(f"shape_key_value: {args.shape_key_value}")
    print(f"save_blend_path: {args.save_blend_path}")
    print(f"render_filename: {args.render_filename}")
    print(f"use_shape_key: {args.use_shape_key}")

    load_hair_scene_with_deformed_shape(
        obj_path=args.obj_path,
        mesh_object_name=args.mesh_object_name,
        deformed_obj_path=args.deformed_obj_path,
        shape_key_name=args.shape_key_name,
        shape_key_value=args.shape_key_value,
        save_blend_path=args.save_blend_path,
        use_shape_key=args.use_shape_key,
    )