Chunyi99 commited on
Commit
b546a02
·
verified ·
1 Parent(s): 845e119

upload script for load dataset sample into blender

Browse files
Files changed (1) hide show
  1. load_dataset_sample.py +2708 -0
load_dataset_sample.py ADDED
@@ -0,0 +1,2708 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bpy
2
+ import json
3
+ import math
4
+ import re
5
+ import numpy as np
6
+ import bmesh
7
+ from pathlib import Path
8
+ from mathutils import Vector
9
+ from mathutils.bvhtree import BVHTree
10
+ from mathutils.geometry import barycentric_transform
11
+ import random
12
+ import time
13
+ import sys
14
+ import argparse
15
+
16
+ IMAGE_PREFIX = "dens_"
17
+ VGROUP_PREFIX = "len_"
18
+
19
+ ANIMALLIFT_ROOT = Path("path/to/AnimalLift")
20
+
21
+ REGIONS = [
22
+ "face", "ear", "neck", "body", "leg", "tail"
23
+ ]
24
+
25
+ CURVE_REGION_MAP = {
26
+ "face_fur": "face",
27
+ "ear_fur": "ear",
28
+ "body_fur": "body",
29
+ "leg_fur": "leg",
30
+ "neck_fur": "neck",
31
+ "neck": "neck",
32
+ "mouse_fur": "face",
33
+ "tail_fur": "tail",
34
+ }
35
+
36
+ IGNORE_NAME_KEYWORDS = ["undercoat"]
37
+
38
+ MOUSE_LENGTH_VALUE = 0.05
39
+
40
+ BASE_PART_RESOLUTION = 512
41
+ SAMPLES_PER_STRAND = 32
42
+ ATLAS_TILE_PADDING = 0.02
43
+
44
+ IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".exr"}
45
+
46
+ META_ROOT = ANIMALLIFT_ROOT / "meta"
47
+ HDR_DIR = META_ROOT / "render_elements" / "hdr"
48
+ HDR_IMAGE_EXTS = {".hdr", ".exr"}
49
+
50
+ UNDERHAIR_MASK_PATH = META_ROOT / "used_version_obj" / "part_masks" / "merged.png"
51
+ UNDERHAIR_LENGTH = 0.005
52
+ UNDERHAIR_INTERP_DENSITY = 500000.0
53
+ UNDERHAIR_MASK_GROUP = "underhair_mask"
54
+
55
+
56
+ def log(msg: str):
57
+ print(f"[hair-load] {msg}")
58
+
59
+
60
+ def natural_key(path: Path):
61
+ parts = re.split(r"(\d+)", path.stem.lower())
62
+ key = []
63
+ for p in parts:
64
+ if p.isdigit():
65
+ key.append(int(p))
66
+ else:
67
+ key.append(p)
68
+ key.append(path.suffix.lower())
69
+ return key
70
+
71
+
72
+ def is_hidden_or_metadata_name(name: str) -> bool:
73
+ """Return True for hidden files and common macOS metadata entries."""
74
+ return (
75
+ not name
76
+ or name.startswith(".")
77
+ or name.startswith("._")
78
+ or name in {".DS_Store", "Thumbs.db"}
79
+ )
80
+
81
+
82
+ def is_usable_file(path: Path) -> bool:
83
+ """Accept only real, visible files."""
84
+ path = Path(path)
85
+ return path.is_file() and not is_hidden_or_metadata_name(path.name)
86
+
87
+
88
+ def is_usable_directory(path: Path) -> bool:
89
+ """Accept only real, visible directories."""
90
+ path = Path(path)
91
+ return path.is_dir() and not is_hidden_or_metadata_name(path.name)
92
+
93
+
94
+ def require_usable_file(path, description: str = "File") -> Path:
95
+ """Resolve and validate an explicitly supplied file path."""
96
+ path = Path(path).expanduser().resolve()
97
+ if not is_usable_file(path):
98
+ raise FileNotFoundError(
99
+ f"{description} is missing, hidden, or a macOS metadata file: {path}"
100
+ )
101
+ return path
102
+
103
+
104
+ # Backward-compatible alias used by older helper functions.
105
+ is_usable_dataset_file = is_usable_file
106
+
107
+
108
+
109
+ def pick_random_hdr_image(hdr_dir: str, rng_seed: int = None):
110
+ hdr_dir = Path(hdr_dir).resolve()
111
+ if not is_usable_directory(hdr_dir):
112
+ raise FileNotFoundError(
113
+ f"HDR directory is missing or hidden: {hdr_dir}"
114
+ )
115
+
116
+ hdr_files = sorted(
117
+ [
118
+ path
119
+ for path in hdr_dir.iterdir()
120
+ if is_usable_file(path)
121
+ and path.suffix.lower() in HDR_IMAGE_EXTS
122
+ ],
123
+ key=natural_key,
124
+ )
125
+
126
+ rejected = sorted(
127
+ [
128
+ path.name
129
+ for path in hdr_dir.iterdir()
130
+ if path.suffix.lower() in HDR_IMAGE_EXTS
131
+ and not is_usable_file(path)
132
+ ]
133
+ )
134
+ if rejected:
135
+ log(f"Ignored hidden HDR metadata files: {rejected}")
136
+
137
+ if not hdr_files:
138
+ raise FileNotFoundError(
139
+ f"No usable HDR/EXR files found in: {hdr_dir}"
140
+ )
141
+
142
+ rng = random.Random(rng_seed)
143
+ chosen = rng.choice(hdr_files)
144
+ log(f"Randomly selected HDR: {chosen.name}")
145
+ return chosen
146
+
147
+ def list_hair_files(hair_dir: Path):
148
+ """Prefer .pt files exactly as the training dataset does."""
149
+ pt_files = sorted(
150
+ [p for p in hair_dir.glob("*.pt") if is_usable_file(p)],
151
+ key=natural_key,
152
+ )
153
+ if pt_files:
154
+ return pt_files
155
+
156
+ return sorted(
157
+ [p for p in hair_dir.glob("*.npz") if is_usable_file(p)],
158
+ key=natural_key,
159
+ )
160
+
161
+
162
+ def select_hair_map_for_obj(obj_path: Path, dataset_dir: Path):
163
+ """
164
+ Match the training dataset's auxiliary-file rule.
165
+
166
+ - Prefer hair_maps_single_512_uvlocal.
167
+ - Prefer .pt over .npz.
168
+ - If there is one hair file, reuse it for every shape.
169
+ - Otherwise pair hair and shape files by natural-sort index.
170
+ """
171
+ hair_dir_candidates = [
172
+ dataset_dir / "hair_maps_single_512_uvlocal",
173
+ dataset_dir / "hair_maps_curl",
174
+ dataset_dir / "hair_maps",
175
+ ]
176
+
177
+ shapes_dir = dataset_dir / "shapes"
178
+ shape_files = sorted(
179
+ [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)],
180
+ key=natural_key,
181
+ )
182
+
183
+ try:
184
+ shape_index = next(
185
+ index
186
+ for index, path in enumerate(shape_files)
187
+ if path.resolve() == obj_path.resolve()
188
+ )
189
+ except StopIteration as exc:
190
+ raise FileNotFoundError(
191
+ f"OBJ file is not present in the dataset shapes directory: {obj_path}"
192
+ ) from exc
193
+
194
+ checked = []
195
+ for hair_dir in hair_dir_candidates:
196
+ checked.append(str(hair_dir))
197
+ hair_files = list_hair_files(hair_dir)
198
+ if not hair_files:
199
+ continue
200
+
201
+ same_stem = [
202
+ path for path in hair_files
203
+ if path.stem == obj_path.stem
204
+ ]
205
+ if same_stem:
206
+ return same_stem[0]
207
+
208
+ if len(hair_files) == 1:
209
+ return hair_files[0]
210
+
211
+ if shape_index < len(hair_files):
212
+ return hair_files[shape_index]
213
+
214
+ raise IndexError(
215
+ f"Hair index out of range for {obj_path.name}: "
216
+ f"shapes={len(shape_files)}, hair_files={len(hair_files)}, "
217
+ f"shape_index={shape_index}, hair_dir={hair_dir}"
218
+ )
219
+
220
+ raise FileNotFoundError(
221
+ "Could not find a compatible .pt or .npz hair map in:\n "
222
+ + "\n ".join(checked)
223
+ )
224
+
225
+
226
+ def resolve_paths_from_obj(obj_path: str):
227
+ obj_path = Path(obj_path).expanduser().resolve()
228
+ if not is_usable_file(obj_path):
229
+ raise FileNotFoundError(
230
+ f"OBJ file is missing or is a hidden/macOS metadata file: {obj_path}"
231
+ )
232
+ if obj_path.parent.name != "shapes":
233
+ raise ValueError(
234
+ "Expected an OBJ inside a dataset group 'shapes' directory, for example:\n"
235
+ " /path/to/animallift/cat/dataset/<group>/shapes/<sample>.obj"
236
+ )
237
+
238
+ dataset_dir = obj_path.parent.parent
239
+ hair_map_path = select_hair_map_for_obj(obj_path, dataset_dir)
240
+
241
+ return {
242
+ "dataset_dir": dataset_dir,
243
+ "datasets_root": dataset_dir.parent,
244
+ "sample_name": obj_path.stem,
245
+ "textures_dir": dataset_dir / "textures",
246
+ "hair_map": hair_map_path,
247
+ "hair_meta": META_ROOT / "hair_map_meta_uvanchor.npz",
248
+ "hair_map_curl_out": hair_map_path,
249
+ "mesh_normal": META_ROOT / "render_elements" / "Normal.png",
250
+ "mesh_roughness": META_ROOT / "render_elements" / "Roughness.png",
251
+ "hdr_dir": HDR_DIR,
252
+ }
253
+
254
+
255
+ def discover_dataset_case(
256
+ root: Path,
257
+ species: str = "cat",
258
+ group_name: str = None,
259
+ sample_index: int = 0,
260
+ ):
261
+ """
262
+ Discover a real case from:
263
+ <root>/<species>/dataset/<group>/shapes/*.obj
264
+
265
+ The group must also contain textures and a compatible hair-map directory.
266
+ """
267
+ root = Path(root).expanduser().resolve()
268
+ species_root = root / species / "dataset"
269
+ if not species_root.is_dir():
270
+ raise FileNotFoundError(f"Species dataset directory not found: {species_root}")
271
+
272
+ if group_name:
273
+ explicit_group = species_root / group_name
274
+ if not is_usable_directory(explicit_group):
275
+ raise FileNotFoundError(
276
+ f"Requested dataset group not found: {explicit_group}"
277
+ )
278
+ group_dirs = [explicit_group]
279
+ else:
280
+ group_dirs = sorted(
281
+ [
282
+ path
283
+ for path in species_root.iterdir()
284
+ if is_usable_directory(path)
285
+ ],
286
+ key=natural_key,
287
+ )
288
+
289
+ failures = []
290
+ for group_dir in group_dirs:
291
+ shapes_dir = group_dir / "shapes"
292
+ textures_dir = group_dir / "textures"
293
+ if not shapes_dir.is_dir() or not textures_dir.is_dir():
294
+ failures.append(f"{group_dir}: missing shapes or textures")
295
+ continue
296
+
297
+ shape_files = sorted(
298
+ [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)],
299
+ key=natural_key,
300
+ )
301
+ texture_files = sorted(
302
+ [
303
+ p for p in textures_dir.iterdir()
304
+ if is_usable_file(p) and p.suffix.lower() in IMAGE_EXTS
305
+ ],
306
+ key=natural_key,
307
+ )
308
+ if not shape_files or not texture_files:
309
+ failures.append(f"{group_dir}: empty shapes or textures")
310
+ continue
311
+
312
+ usable_count = min(len(shape_files), len(texture_files))
313
+ if sample_index < 0 or sample_index >= usable_count:
314
+ failures.append(
315
+ f"{group_dir}: sample_index={sample_index} outside 0..{usable_count - 1}"
316
+ )
317
+ continue
318
+
319
+ obj_path = shape_files[sample_index]
320
+ try:
321
+ hair_path = select_hair_map_for_obj(obj_path, group_dir)
322
+ except Exception as exc:
323
+ failures.append(f"{group_dir}: {exc}")
324
+ continue
325
+
326
+ deformed_candidate = group_dir / "deformed_shapes" / obj_path.name
327
+ deformed_path = (
328
+ deformed_candidate
329
+ if is_usable_file(deformed_candidate)
330
+ else None
331
+ )
332
+
333
+ log(f"Using dataset group: {group_dir.name}")
334
+ log(f"Selected OBJ: {obj_path.name}")
335
+ log(f"Selected hair map: {hair_path.name}")
336
+ if deformed_path is None:
337
+ log("No matching deformed shape found; using the original mesh")
338
+ else:
339
+ log(f"Selected deformed shape: {deformed_path.name}")
340
+
341
+ return obj_path, deformed_path
342
+
343
+ detail = "\n".join(f" - {item}" for item in failures[:20])
344
+ raise RuntimeError(
345
+ f"No usable visualization case found under {species_root}.\n{detail}"
346
+ )
347
+
348
+
349
+
350
+ def load_global_hair_meta(meta_path: str):
351
+ meta_path = require_usable_file(
352
+ meta_path,
353
+ "Global hair metadata",
354
+ )
355
+
356
+ data = np.load(str(meta_path), allow_pickle=True)
357
+
358
+ required_keys = [
359
+ "group_names",
360
+ "guide_group_id_map",
361
+ "uv_face_index_map",
362
+ "uv_bary_map",
363
+ ]
364
+ for key in required_keys:
365
+ if key not in data:
366
+ raise KeyError(f"Missing key '{key}' in global hair meta: {meta_path}")
367
+
368
+ group_names = [str(n) for n in data["group_names"]]
369
+ guide_group_id_map = data["guide_group_id_map"].astype(np.int32)
370
+ uv_face_index_map = data["uv_face_index_map"].astype(np.int32)
371
+ uv_bary_map = data["uv_bary_map"].astype(np.float32)
372
+
373
+ log(f"Loaded global hair meta: {meta_path}")
374
+ log(f" Groups: {group_names}")
375
+ log(f" guide_group_id_map shape: {guide_group_id_map.shape}")
376
+ log(f" uv_face_index_map shape: {uv_face_index_map.shape}")
377
+ log(f" uv_bary_map shape: {uv_bary_map.shape}")
378
+
379
+ return group_names, guide_group_id_map, uv_face_index_map, uv_bary_map
380
+
381
+
382
+ def import_obj_as_mesh(obj_path: str, object_name: str = None):
383
+ obj_path = str(require_usable_file(obj_path, "OBJ file"))
384
+
385
+ bpy.ops.object.select_all(action='DESELECT')
386
+ if hasattr(bpy.ops.wm, "obj_import"):
387
+ bpy.ops.wm.obj_import(filepath=obj_path)
388
+ else:
389
+ bpy.ops.import_scene.obj(filepath=obj_path)
390
+
391
+ imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
392
+ if not imported_meshes:
393
+ raise Exception(f"No mesh imported from {obj_path}")
394
+
395
+ mesh_obj = imported_meshes[0]
396
+ if object_name:
397
+ mesh_obj.name = object_name
398
+ mesh_obj.data.name = object_name
399
+
400
+ bpy.ops.object.select_all(action='DESELECT')
401
+ mesh_obj.select_set(True)
402
+ bpy.context.view_layer.objects.active = mesh_obj
403
+ bpy.ops.object.shade_smooth()
404
+
405
+ log(f"Imported mesh: {mesh_obj.name} ({len(mesh_obj.data.vertices)} verts, smooth shading)")
406
+ return mesh_obj
407
+
408
+
409
+ def apply_deformed_shape_directly(mesh_obj, deformed_obj_path: str):
410
+ """Overwrite base mesh vertex positions with deformed OBJ vertex positions.
411
+
412
+ This avoids shape keys entirely so the base mesh IS the deformed shape,
413
+ and all curves bound to its surface will follow naturally.
414
+ """
415
+ deformed_obj_path = str(
416
+ require_usable_file(deformed_obj_path, "Deformed OBJ file")
417
+ )
418
+
419
+ bpy.ops.object.select_all(action='DESELECT')
420
+ if hasattr(bpy.ops.wm, "obj_import"):
421
+ bpy.ops.wm.obj_import(filepath=deformed_obj_path)
422
+ else:
423
+ bpy.ops.import_scene.obj(filepath=deformed_obj_path)
424
+
425
+ imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
426
+ if not imported_meshes:
427
+ raise Exception(f"No mesh imported from {deformed_obj_path}")
428
+ imported = imported_meshes[0]
429
+
430
+ if len(mesh_obj.data.vertices) != len(imported.data.vertices):
431
+ bpy.data.objects.remove(imported, do_unlink=True)
432
+ raise Exception(
433
+ f"Vertex count mismatch! Target: {len(mesh_obj.data.vertices)}, "
434
+ f"Imported: {len(imported.data.vertices)}"
435
+ )
436
+
437
+ for i, v in enumerate(imported.data.vertices):
438
+ mesh_obj.data.vertices[i].co = v.co
439
+
440
+ bpy.data.objects.remove(imported, do_unlink=True)
441
+ mesh_obj.data.update()
442
+
443
+ log(f"Applied deformed shape directly to '{mesh_obj.name}' from {deformed_obj_path}")
444
+
445
+
446
+ def import_obj_as_shape_key(target, obj_path: str, shape_key_name: str):
447
+ obj_path = str(require_usable_file(obj_path, "Shape-key OBJ file"))
448
+
449
+ bpy.ops.object.select_all(action='DESELECT')
450
+ if hasattr(bpy.ops.wm, "obj_import"):
451
+ bpy.ops.wm.obj_import(filepath=obj_path)
452
+ else:
453
+ bpy.ops.import_scene.obj(filepath=obj_path)
454
+
455
+ imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH']
456
+ if not imported_meshes:
457
+ raise Exception(f"No imported mesh found from {obj_path}")
458
+ imported = imported_meshes[0]
459
+
460
+ try:
461
+ if len(target.data.vertices) != len(imported.data.vertices):
462
+ raise Exception(
463
+ f"Vertex count mismatch! Target: {len(target.data.vertices)}, "
464
+ f"Imported: {len(imported.data.vertices)}"
465
+ )
466
+
467
+ if not target.data.shape_keys:
468
+ target.shape_key_add(name="Basis")
469
+
470
+ old = target.data.shape_keys.key_blocks.get(shape_key_name)
471
+ if old is not None:
472
+ bpy.context.view_layer.objects.active = target
473
+ target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(old)
474
+ bpy.ops.object.shape_key_remove(all=False)
475
+
476
+ sk = target.shape_key_add(name=shape_key_name, from_mix=False)
477
+ for i, v in enumerate(imported.data.vertices):
478
+ sk.data[i].co = v.co
479
+
480
+ sk.value = 1.0
481
+ target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(sk)
482
+
483
+ log(f"Shape key created and enabled: {shape_key_name}")
484
+ return sk
485
+ finally:
486
+ bpy.data.objects.remove(imported, do_unlink=True)
487
+
488
+
489
+ def resolve_corresponding_deformed_shape_path(source_obj_path: str, deformed_obj_path: str = None):
490
+ if deformed_obj_path is not None:
491
+ p = Path(deformed_obj_path).resolve()
492
+ else:
493
+ source_obj_path = Path(source_obj_path).resolve()
494
+ dataset_dir = source_obj_path.parent.parent
495
+ p = dataset_dir / "deformed_shapes" / source_obj_path.name
496
+
497
+ if not is_usable_file(p):
498
+ raise FileNotFoundError(
499
+ f"Deformed shape OBJ is missing or hidden: {p}"
500
+ )
501
+ return p
502
+
503
+
504
+ def open_image_simple(image_path: str, non_color: bool = True):
505
+ image_path = str(require_usable_file(image_path, "Image file"))
506
+ img = bpy.data.images.load(filepath=image_path, check_existing=True)
507
+ img.colorspace_settings.name = 'Non-Color' if non_color else 'sRGB'
508
+ img.pixels[:]
509
+ return img
510
+
511
+
512
+ def open_image_color(image_path: str):
513
+ return open_image_simple(image_path, non_color=False)
514
+
515
+ def is_green_rgb(rgb, green_threshold=0.45, green_margin=0.08):
516
+ r, g, b = float(rgb[0]), float(rgb[1]), float(rgb[2])
517
+ return (
518
+ g >= green_threshold and
519
+ g > r + green_margin and
520
+ g > b + green_margin
521
+ )
522
+
523
+
524
+ def remove_green_screen_from_image(
525
+ src_image_path: str,
526
+ out_image_path: str = None,
527
+ green_threshold: float = 0.45,
528
+ green_margin: float = 0.08,
529
+ rng_seed: int = None,
530
+ ):
531
+ """
532
+ Replace green pixels with randomly sampled non-green colors from the same image.
533
+ Returns the output image path.
534
+ """
535
+ src_image_path = require_usable_file(
536
+ src_image_path,
537
+ "Texture image",
538
+ )
539
+
540
+ img = bpy.data.images.load(filepath=str(src_image_path), check_existing=False)
541
+ width, height = img.size
542
+
543
+ pixel_count = width * height * 4
544
+ pixels = np.empty(pixel_count, dtype=np.float32)
545
+ img.pixels.foreach_get(pixels)
546
+ pixels = pixels.reshape((height, width, 4))
547
+
548
+ rgb = pixels[:, :, :3]
549
+ alpha = pixels[:, :, 3:4]
550
+
551
+ green_mask = (
552
+ (rgb[:, :, 1] >= green_threshold) &
553
+ (rgb[:, :, 1] > rgb[:, :, 0] + green_margin) &
554
+ (rgb[:, :, 1] > rgb[:, :, 2] + green_margin)
555
+ )
556
+
557
+ non_green_coords = np.argwhere(~green_mask)
558
+ green_coords = np.argwhere(green_mask)
559
+
560
+ if len(green_coords) == 0:
561
+ log(f"No green pixels detected in texture: {src_image_path.name}")
562
+ return src_image_path
563
+
564
+ if len(non_green_coords) == 0:
565
+ log(f"[WARN] Texture has no non-green pixels to sample from: {src_image_path.name}")
566
+ return src_image_path
567
+
568
+ rng = np.random.default_rng(rng_seed)
569
+
570
+ sampled_ids = rng.integers(0, len(non_green_coords), size=len(green_coords))
571
+ sampled_coords = non_green_coords[sampled_ids]
572
+
573
+ replacement_colors = rgb[sampled_coords[:, 0], sampled_coords[:, 1]]
574
+ rgb[green_coords[:, 0], green_coords[:, 1]] = replacement_colors
575
+
576
+ out_pixels = np.concatenate([rgb, alpha], axis=2).astype(np.float32).reshape(-1)
577
+
578
+ if out_image_path is None:
579
+ out_image_path = src_image_path.parent / f"{src_image_path.stem}_nogreen.png"
580
+ else:
581
+ out_image_path = Path(out_image_path).resolve()
582
+
583
+ out_image_path.parent.mkdir(parents=True, exist_ok=True)
584
+
585
+ out_img = bpy.data.images.new(
586
+ name=f"{src_image_path.stem}_nogreen",
587
+ width=width,
588
+ height=height,
589
+ alpha=True,
590
+ float_buffer=False,
591
+ )
592
+ out_img.colorspace_settings.name = 'sRGB'
593
+ out_img.filepath_raw = str(out_image_path)
594
+ out_img.file_format = 'PNG'
595
+ out_img.pixels.foreach_set(out_pixels.tolist())
596
+ out_img.save()
597
+
598
+ try:
599
+ bpy.data.images.remove(img)
600
+ except Exception:
601
+ pass
602
+
603
+ log(f"Saved green-removed texture: {out_image_path}")
604
+ return out_image_path
605
+
606
+
607
+ def resolve_render_output_path(obj_path: str, render_filename: str = None):
608
+ obj_path = Path(obj_path).resolve()
609
+ dataset_dir = obj_path.parent.parent
610
+ render_dir = dataset_dir / "render_images"
611
+ render_dir.mkdir(parents=True, exist_ok=True)
612
+
613
+ if render_filename is None:
614
+ render_filename = f"{obj_path.stem}.png"
615
+
616
+ return render_dir / render_filename
617
+
618
+
619
+ def render_and_save_image(output_path: str):
620
+ output_path = Path(output_path).resolve()
621
+ output_path.parent.mkdir(parents=True, exist_ok=True)
622
+
623
+ scene = bpy.context.scene
624
+ scene.render.image_settings.file_format = 'PNG'
625
+ scene.render.image_settings.color_mode = 'RGBA'
626
+ scene.render.filepath = str(output_path)
627
+
628
+ bpy.ops.render.render(write_still=True)
629
+ log(f"Saved render image: {output_path}")
630
+
631
+
632
+ def load_density_images(mesh_obj, density_dir: str):
633
+ density_images = {}
634
+ for region in REGIONS:
635
+ image_path = Path(density_dir) / f"{region}.png"
636
+ if not is_usable_file(image_path):
637
+ log(f" [WARN] Density image not found: {image_path}")
638
+ continue
639
+ img = open_image_simple(str(image_path), non_color=True)
640
+ img.name = f"{IMAGE_PREFIX}{region}_{mesh_obj.name}"
641
+ density_images[region] = img
642
+ return density_images
643
+
644
+
645
+ def create_vertex_group_from_image(obj, image_path: str, group_name: str, scale: float = 1.0):
646
+ mesh = obj.data
647
+ if not mesh.uv_layers:
648
+ raise Exception("Target mesh has no UVs")
649
+
650
+ img = open_image_simple(image_path, non_color=True)
651
+ width, height = img.size
652
+
653
+ pixel_count = width * height * 4
654
+ pixels_np = np.empty(pixel_count, dtype=np.float32)
655
+ img.pixels.foreach_get(pixels_np)
656
+ pixels_np = pixels_np.reshape((height, width, 4))
657
+
658
+ lum = (
659
+ 0.2126 * pixels_np[:, :, 0]
660
+ + 0.7152 * pixels_np[:, :, 1]
661
+ + 0.0722 * pixels_np[:, :, 2]
662
+ )
663
+
664
+ total_loops = len(mesh.loops)
665
+ loop_uvs = np.empty(total_loops * 2, dtype=np.float32)
666
+ mesh.uv_layers.active.data.foreach_get("uv", loop_uvs)
667
+ loop_uvs = loop_uvs.reshape((total_loops, 2))
668
+
669
+ loop_verts = np.empty(total_loops, dtype=np.int32)
670
+ mesh.loops.foreach_get("vertex_index", loop_verts)
671
+
672
+ u = np.clip(loop_uvs[:, 0], 0.0, 1.0)
673
+ v = np.clip(loop_uvs[:, 1], 0.0, 1.0)
674
+ xi = (u * (width - 1)).astype(np.int32)
675
+ yi = (v * (height - 1)).astype(np.int32)
676
+ loop_weights = lum[yi, xi] * float(scale)
677
+
678
+ num_verts = len(mesh.vertices)
679
+ weight_sum = np.zeros(num_verts, dtype=np.float64)
680
+ weight_cnt = np.zeros(num_verts, dtype=np.int32)
681
+ np.add.at(weight_sum, loop_verts, loop_weights)
682
+ np.add.at(weight_cnt, loop_verts, 1)
683
+
684
+ mask = weight_cnt > 0
685
+ avg_weights = np.zeros(num_verts, dtype=np.float64)
686
+ avg_weights[mask] = weight_sum[mask] / weight_cnt[mask]
687
+
688
+ old_vg = obj.vertex_groups.get(group_name)
689
+ if old_vg is not None:
690
+ obj.vertex_groups.remove(old_vg)
691
+ vg = obj.vertex_groups.new(name=group_name)
692
+
693
+ indices = np.where(mask)[0]
694
+ for vid in indices:
695
+ vg.add([int(vid)], float(avg_weights[vid]), 'REPLACE')
696
+
697
+ return vg, img
698
+
699
+
700
+ def load_hair_info(json_path):
701
+ json_path = Path(json_path).resolve()
702
+ if not is_usable_file(json_path):
703
+ raise FileNotFoundError(
704
+ f"hair_info.json is missing or hidden: {json_path}"
705
+ )
706
+ with open(json_path, "r", encoding="utf-8") as f:
707
+ return json.load(f)
708
+
709
+
710
+ def get_region_length_scale(hair_info: dict, region: str) -> float:
711
+ params = hair_info.get("resolved_hair_params", {})
712
+ if region not in params:
713
+ raise KeyError(f"Region '{region}' not found in resolved_hair_params")
714
+ return float(params[region]["length"])
715
+
716
+
717
+ def create_length_vertex_groups(mesh_obj, length_dir: str, hair_info: dict):
718
+ for region in REGIONS:
719
+ image_path = Path(length_dir) / f"{region}.png"
720
+ if not is_usable_file(image_path):
721
+ log(f" [WARN] Length image not found: {image_path}")
722
+ continue
723
+ vg_name = f"{VGROUP_PREFIX}{region}"
724
+ scale = get_region_length_scale(hair_info, region)
725
+ vg, img = create_vertex_group_from_image(mesh_obj, str(image_path), vg_name, scale=scale)
726
+ img.name = f"lenimg_{region}_{mesh_obj.name}"
727
+ log(f" Created vertex group: {vg.name}, scale={scale:.4f}")
728
+
729
+
730
+ def ensure_triangulated_bmesh(mesh):
731
+ bm = bmesh.new()
732
+ bm.from_mesh(mesh)
733
+ bmesh.ops.triangulate(bm, faces=bm.faces[:])
734
+ bm.faces.ensure_lookup_table()
735
+ bm.verts.ensure_lookup_table()
736
+ return bm
737
+
738
+
739
+ def get_evaluated_mesh(mesh_obj):
740
+ """Return the evaluated (deformed) mesh data, accounting for shape keys
741
+ and modifiers. Caller must call eval_obj.to_mesh_clear() when done if needed.
742
+ """
743
+ depsgraph = bpy.context.evaluated_depsgraph_get()
744
+ eval_obj = mesh_obj.evaluated_get(depsgraph)
745
+ eval_mesh = eval_obj.to_mesh()
746
+ return eval_obj, eval_mesh
747
+
748
+
749
+ def compute_root_uvs(roots, mesh_obj):
750
+ mesh = mesh_obj.data
751
+ if not mesh.uv_layers.active:
752
+ raise RuntimeError("Mesh has no active UV layer")
753
+
754
+ # Use evaluated mesh so roots snap to deformed positions
755
+ eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)
756
+
757
+ bm = bmesh.new()
758
+ bm.from_mesh(eval_mesh)
759
+ bmesh.ops.triangulate(bm, faces=bm.faces[:])
760
+ bm.faces.ensure_lookup_table()
761
+ bm.verts.ensure_lookup_table()
762
+
763
+ # UV layer name comes from the original mesh
764
+ uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name)
765
+ if uv_layer is None:
766
+ bm.free()
767
+ eval_obj.to_mesh_clear()
768
+ raise RuntimeError("Could not access active UV layer")
769
+
770
+ bvh = BVHTree.FromBMesh(bm)
771
+ uvs = []
772
+
773
+ for root in roots:
774
+ hit = bvh.find_nearest(Vector(root))
775
+ if hit is None or hit[2] is None:
776
+ uvs.append((0.5, 0.5))
777
+ continue
778
+
779
+ location, normal, face_index, dist = hit
780
+ face = bm.faces[face_index]
781
+ if len(face.verts) != 3:
782
+ uvs.append((0.5, 0.5))
783
+ continue
784
+
785
+ v0, v1, v2 = [f.co for f in face.verts]
786
+ uv0 = face.loops[0][uv_layer].uv
787
+ uv1 = face.loops[1][uv_layer].uv
788
+ uv2 = face.loops[2][uv_layer].uv
789
+
790
+ uv = barycentric_transform(
791
+ location, v0, v1, v2,
792
+ uv0.to_3d(), uv1.to_3d(), uv2.to_3d()
793
+ )
794
+ uvs.append((float(uv.x), float(uv.y)))
795
+
796
+ bm.free()
797
+ eval_obj.to_mesh_clear()
798
+ return uvs
799
+
800
+
801
+ def build_face_geom(mesh_obj):
802
+ """Build triangle face geometry from the evaluated (deformed) mesh."""
803
+ mesh = mesh_obj.data
804
+ if not mesh.uv_layers.active:
805
+ raise RuntimeError("Mesh has no active UV layer")
806
+
807
+ # Use evaluated mesh to pick up shape key / modifier deformations
808
+ eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)
809
+
810
+ bm = bmesh.new()
811
+ bm.from_mesh(eval_mesh)
812
+ bmesh.ops.triangulate(bm, faces=bm.faces[:])
813
+ bm.faces.ensure_lookup_table()
814
+ bm.verts.ensure_lookup_table()
815
+
816
+ uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name)
817
+ if uv_layer is None:
818
+ bm.free()
819
+ eval_obj.to_mesh_clear()
820
+ raise RuntimeError("Could not access active UV layer")
821
+
822
+ num_faces = len(bm.faces)
823
+ face_pos = np.empty((num_faces, 3, 3), dtype=np.float32)
824
+ face_uvs = np.empty((num_faces, 3, 2), dtype=np.float32)
825
+
826
+ for fi, face in enumerate(bm.faces):
827
+ for vi in range(3):
828
+ co = face.verts[vi].co
829
+ uv = face.loops[vi][uv_layer].uv
830
+ face_pos[fi, vi] = (co.x, co.y, co.z)
831
+ face_uvs[fi, vi] = (uv.x, uv.y)
832
+
833
+ bm.free()
834
+ eval_obj.to_mesh_clear()
835
+ return face_pos, face_uvs
836
+
837
+
838
+ def reconstruct_surface_points_and_frames(mesh_obj, uv_face_index_map, uv_bary_map):
839
+ face_pos, face_uvs = build_face_geom(mesh_obj)
840
+
841
+ height, width = uv_face_index_map.shape
842
+ roots = np.zeros((height, width, 3), dtype=np.float32)
843
+ Tu = np.zeros((height, width, 3), dtype=np.float32)
844
+ Tv = np.zeros((height, width, 3), dtype=np.float32)
845
+ N = np.zeros((height, width, 3), dtype=np.float32)
846
+
847
+ ys, xs = np.where(uv_face_index_map >= 0)
848
+ fids = uv_face_index_map[ys, xs].astype(np.int32)
849
+ bary = uv_bary_map[ys, xs].astype(np.float32)
850
+
851
+ p0 = face_pos[fids, 0]
852
+ p1 = face_pos[fids, 1]
853
+ p2 = face_pos[fids, 2]
854
+
855
+ uv0 = face_uvs[fids, 0]
856
+ uv1 = face_uvs[fids, 1]
857
+ uv2 = face_uvs[fids, 2]
858
+
859
+ roots_pts = (
860
+ bary[:, 0:1] * p0 +
861
+ bary[:, 1:2] * p1 +
862
+ bary[:, 2:3] * p2
863
+ )
864
+
865
+ dp1 = p1 - p0
866
+ dp2 = p2 - p0
867
+ duv1 = uv1 - uv0
868
+ duv2 = uv2 - uv0
869
+
870
+ det = duv1[:, 0] * duv2[:, 1] - duv1[:, 1] * duv2[:, 0]
871
+ safe = np.abs(det) > 1e-12
872
+ det_safe = det.copy()
873
+ det_safe[~safe] = 1.0
874
+
875
+ Tu_pts = np.empty_like(dp1)
876
+ Tv_pts = np.empty_like(dp1)
877
+
878
+ Tu_pts[:, 0] = (dp1[:, 0] * duv2[:, 1] - dp2[:, 0] * duv1[:, 1]) / det_safe
879
+ Tu_pts[:, 1] = (dp1[:, 1] * duv2[:, 1] - dp2[:, 1] * duv1[:, 1]) / det_safe
880
+ Tu_pts[:, 2] = (dp1[:, 2] * duv2[:, 1] - dp2[:, 2] * duv1[:, 1]) / det_safe
881
+
882
+ Tv_pts[:, 0] = (-dp1[:, 0] * duv2[:, 0] + dp2[:, 0] * duv1[:, 0]) / det_safe
883
+ Tv_pts[:, 1] = (-dp1[:, 1] * duv2[:, 0] + dp2[:, 1] * duv1[:, 0]) / det_safe
884
+ Tv_pts[:, 2] = (-dp1[:, 2] * duv2[:, 0] + dp2[:, 2] * duv1[:, 0]) / det_safe
885
+
886
+ N_pts = np.cross(dp1, dp2)
887
+
888
+ def normalize(v):
889
+ lens = np.linalg.norm(v, axis=1, keepdims=True)
890
+ lens[lens < 1e-12] = 1.0
891
+ return v / lens
892
+
893
+ Tu_pts = normalize(Tu_pts)
894
+ Tv_pts = normalize(Tv_pts)
895
+ N_pts = normalize(N_pts)
896
+
897
+ if np.any(~safe):
898
+ Tu_pts[~safe] = normalize(dp1[~safe])
899
+ Tv_pts[~safe] = normalize(np.cross(N_pts[~safe], Tu_pts[~safe]))
900
+ N_pts[~safe] = normalize(np.cross(Tu_pts[~safe], Tv_pts[~safe]))
901
+
902
+ roots[ys, xs] = roots_pts
903
+ Tu[ys, xs] = Tu_pts
904
+ Tv[ys, xs] = Tv_pts
905
+ N[ys, xs] = N_pts
906
+
907
+ return roots, Tu, Tv, N
908
+
909
+
910
+ def load_quantized_hair_map(hair_map_path: str):
911
+ """
912
+ Load either the uploaded .pt cache format or the legacy .npz format.
913
+
914
+ Returns:
915
+ hair_q: [H, W, S-1, 3] float32
916
+ scale: [3] float32
917
+ samples: S
918
+ hair_mask: [H, W] bool
919
+ """
920
+ path = require_usable_file(hair_map_path, "Hair map")
921
+ suffix = path.suffix.lower()
922
+
923
+ if suffix == ".pt":
924
+ try:
925
+ import torch
926
+ except ImportError as exc:
927
+ raise ImportError(
928
+ "Reading uploaded .pt hair maps requires PyTorch in Blender's "
929
+ "Python environment. Install torch for the Blender Python version."
930
+ ) from exc
931
+
932
+ data = torch.load(str(path), map_location="cpu")
933
+ required = ["hair_q", "scale", "hair_mask"]
934
+ missing = [key for key in required if key not in data]
935
+ if missing:
936
+ raise KeyError(f"Missing keys {missing} in PT hair map: {path}")
937
+
938
+ hair_q = data["hair_q"].detach().cpu().numpy().astype(np.float32)
939
+ scale = data["scale"].detach().cpu().numpy().astype(np.float32)
940
+ hair_mask = data["hair_mask"].detach().cpu().numpy().astype(bool)
941
+ samples = int(hair_q.shape[2]) + 1
942
+ return hair_q, scale, samples, hair_mask
943
+
944
+ if suffix == ".npz":
945
+ data = np.load(str(path), allow_pickle=True)
946
+ required = ["hair_offsets_local_q", "offset_scale"]
947
+ missing = [key for key in required if key not in data]
948
+ if missing:
949
+ raise KeyError(f"Missing keys {missing} in NPZ hair map: {path}")
950
+
951
+ hair_q = data["hair_offsets_local_q"].astype(np.float32)
952
+ scale = data["offset_scale"].astype(np.float32)
953
+ samples = (
954
+ int(data["samples"])
955
+ if "samples" in data
956
+ else int(hair_q.shape[2]) + 1
957
+ )
958
+ hair_mask = np.abs(hair_q).sum(axis=(2, 3)) > 0
959
+ return hair_q, scale, samples, hair_mask
960
+
961
+ raise ValueError(f"Unsupported hair map extension: {path.suffix}")
962
+
963
+
964
+ def decode_hair_map(hair_map_path: str, meta_path: str, mesh_obj):
965
+ hair_offsets_local_q, offset_scale, samples, hair_mask = (
966
+ load_quantized_hair_map(hair_map_path)
967
+ )
968
+
969
+ group_names, guide_group_id_map, uv_face_index_map, uv_bary_map = (
970
+ load_global_hair_meta(meta_path)
971
+ )
972
+
973
+ if samples < 1:
974
+ raise ValueError(f"Invalid samples={samples} in hair map")
975
+
976
+ height, width = guide_group_id_map.shape[:2]
977
+ if hair_offsets_local_q.shape[:2] != (height, width):
978
+ raise ValueError(
979
+ "Shape mismatch between hair map and global metadata: "
980
+ f"{hair_offsets_local_q.shape[:2]} vs {(height, width)}"
981
+ )
982
+ if hair_mask.shape[:2] != (height, width):
983
+ raise ValueError(
984
+ f"Hair mask shape mismatch: {hair_mask.shape[:2]} vs {(height, width)}"
985
+ )
986
+ if uv_face_index_map.shape[:2] != (height, width):
987
+ raise ValueError(
988
+ f"UV face map shape mismatch: {uv_face_index_map.shape[:2]} "
989
+ f"vs {(height, width)}"
990
+ )
991
+ if uv_bary_map.shape[:2] != (height, width):
992
+ raise ValueError(
993
+ f"UV barycentric map shape mismatch: {uv_bary_map.shape[:2]} "
994
+ f"vs {(height, width)}"
995
+ )
996
+
997
+ offsets_local = (
998
+ hair_offsets_local_q / 127.0
999
+ ) * offset_scale.reshape(1, 1, 1, 3)
1000
+ strands_by_group = {name: [] for name in group_names}
1001
+
1002
+ roots_map, Tu_map, Tv_map, N_map = reconstruct_surface_points_and_frames(
1003
+ mesh_obj,
1004
+ uv_face_index_map,
1005
+ uv_bary_map,
1006
+ )
1007
+
1008
+ valid_map = (
1009
+ (guide_group_id_map >= 0)
1010
+ & hair_mask
1011
+ & (uv_face_index_map >= 0)
1012
+ )
1013
+ ys, xs = np.where(valid_map)
1014
+ gids = guide_group_id_map[ys, xs].astype(np.int32)
1015
+
1016
+ for y, x, gid in zip(ys, xs, gids):
1017
+ gid = int(gid)
1018
+ if gid < 0 or gid >= len(group_names):
1019
+ continue
1020
+
1021
+ root = roots_map[y, x]
1022
+ Tu = Tu_map[y, x]
1023
+ Tv = Tv_map[y, x]
1024
+ normal = N_map[y, x]
1025
+
1026
+ local = offsets_local[y, x]
1027
+ world_offsets = (
1028
+ local[:, 0:1] * Tu[None, :]
1029
+ + local[:, 1:2] * Tv[None, :]
1030
+ + local[:, 2:3] * normal[None, :]
1031
+ )
1032
+
1033
+ strand = np.empty((samples, 3), dtype=np.float32)
1034
+ strand[0] = root
1035
+ if samples > 1:
1036
+ strand[1:] = root[None, :] + world_offsets
1037
+
1038
+ strands_by_group[group_names[gid]].append(strand)
1039
+
1040
+ for group_name, strands in list(strands_by_group.items()):
1041
+ if strands:
1042
+ strands_by_group[group_name] = np.stack(strands, axis=0)
1043
+ else:
1044
+ strands_by_group[group_name] = np.zeros(
1045
+ (0, samples, 3),
1046
+ dtype=np.float32,
1047
+ )
1048
+
1049
+ total_strands = sum(value.shape[0] for value in strands_by_group.values())
1050
+ log(f"Decoded hair map: {hair_map_path}")
1051
+ log(f" Samples per strand: {samples}")
1052
+ log(f" Total guide strands: {total_strands}")
1053
+
1054
+ return group_names, strands_by_group, samples
1055
+
1056
+
1057
+
1058
+ def sanitize_name(name):
1059
+ out = []
1060
+ for ch in str(name):
1061
+ if ch.isalnum() or ch in "._-":
1062
+ out.append(ch)
1063
+ else:
1064
+ out.append("_")
1065
+ s = "".join(out).strip("_")
1066
+ return s if s else "HairPart"
1067
+
1068
+
1069
+ def build_curve_object_from_strands(obj_name, strands, root_uvs, mesh_obj):
1070
+ if len(strands) == 0:
1071
+ return None
1072
+
1073
+ curve_data = bpy.data.curves.new(obj_name, type='CURVE')
1074
+ curve_data.dimensions = '3D'
1075
+
1076
+ curve_obj = bpy.data.objects.new(obj_name, curve_data)
1077
+ bpy.context.collection.objects.link(curve_obj)
1078
+
1079
+ curve_obj.parent = mesh_obj
1080
+ curve_obj.location = (0, 0, 0)
1081
+ curve_obj.rotation_euler = (0, 0, 0)
1082
+ curve_obj.scale = (1, 1, 1)
1083
+
1084
+ for strand in strands:
1085
+ spline = curve_data.splines.new('POLY')
1086
+ spline.points.add(len(strand) - 1)
1087
+ for i, p in enumerate(strand):
1088
+ spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)
1089
+
1090
+ if bpy.ops.object.mode_set.poll():
1091
+ bpy.ops.object.mode_set(mode='OBJECT')
1092
+
1093
+ bpy.ops.object.select_all(action='DESELECT')
1094
+ curve_obj.select_set(True)
1095
+ bpy.context.view_layer.objects.active = curve_obj
1096
+ bpy.ops.object.convert(target='CURVES')
1097
+
1098
+ curve_obj = bpy.context.view_layer.objects.active
1099
+ curves = curve_obj.data
1100
+
1101
+ curves.surface = mesh_obj
1102
+ curves.surface_uv_map = mesh_obj.data.uv_layers.active.name
1103
+
1104
+ if "surface_uv_coordinate" in curves.attributes:
1105
+ uv_attr = curves.attributes["surface_uv_coordinate"]
1106
+ else:
1107
+ uv_attr = curves.attributes.new(
1108
+ name="surface_uv_coordinate",
1109
+ type='FLOAT2',
1110
+ domain='CURVE'
1111
+ )
1112
+
1113
+ for i in range(len(root_uvs)):
1114
+ uv_attr.data[i].vector = (float(root_uvs[i][0]), float(root_uvs[i][1]))
1115
+
1116
+ log(f" Created '{curve_obj.name}' with {len(strands)} guide strands")
1117
+ return curve_obj
1118
+
1119
+
1120
+ def build_curve_object_from_strands_no_uv(obj_name, strands, mesh_obj):
1121
+ if len(strands) == 0:
1122
+ return None
1123
+
1124
+ curve_data = bpy.data.curves.new(obj_name, type='CURVE')
1125
+ curve_data.dimensions = '3D'
1126
+
1127
+ curve_obj = bpy.data.objects.new(obj_name, curve_data)
1128
+ bpy.context.collection.objects.link(curve_obj)
1129
+
1130
+ curve_obj.matrix_world = mesh_obj.matrix_world.copy()
1131
+
1132
+ for strand in strands:
1133
+ spline = curve_data.splines.new('POLY')
1134
+ spline.points.add(len(strand) - 1)
1135
+ for i, p in enumerate(strand):
1136
+ spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)
1137
+
1138
+ if bpy.ops.object.mode_set.poll():
1139
+ bpy.ops.object.mode_set(mode='OBJECT')
1140
+
1141
+ bpy.ops.object.select_all(action='DESELECT')
1142
+ curve_obj.select_set(True)
1143
+ bpy.context.view_layer.objects.active = curve_obj
1144
+ bpy.ops.object.convert(target='CURVES')
1145
+
1146
+ curve_obj = bpy.context.view_layer.objects.active
1147
+ curve_obj.matrix_world = mesh_obj.matrix_world.copy()
1148
+ curve_obj.parent = mesh_obj
1149
+ curve_obj.matrix_parent_inverse = mesh_obj.matrix_world.inverted()
1150
+
1151
+ curves = curve_obj.data
1152
+ curves.surface = mesh_obj
1153
+
1154
+ log(f" Created '{curve_obj.name}' with {len(strands)} guide strands (no UV attr)")
1155
+ return curve_obj
1156
+
1157
+
1158
+ def describe_node_group_inputs(mod):
1159
+ if getattr(mod, "node_group", None) is None:
1160
+ return []
1161
+ items = []
1162
+ try:
1163
+ for item in mod.node_group.interface.items_tree:
1164
+ if getattr(item, "in_out", None) == 'INPUT':
1165
+ items.append((item.name, item.identifier, getattr(item, "socket_type", "")))
1166
+ except Exception:
1167
+ pass
1168
+ return items
1169
+
1170
+
1171
+ def get_node_input_identifier_by_name(mod, display_name):
1172
+ for name, identifier, socket_type in describe_node_group_inputs(mod):
1173
+ if name == display_name:
1174
+ return identifier
1175
+ return None
1176
+
1177
+
1178
+ def set_gn_input(mod, display_name, value):
1179
+ identifier = get_node_input_identifier_by_name(mod, display_name)
1180
+ if identifier is None:
1181
+ log(f" [WARN] GN input '{display_name}' not found on '{mod.name}'")
1182
+ return False
1183
+ try:
1184
+ mod[identifier] = value
1185
+ return True
1186
+ except Exception as e:
1187
+ log(f" [WARN] Failed to set '{display_name}' on '{mod.name}': {e}")
1188
+ return False
1189
+
1190
+
1191
+ def find_gn_input_identifier_contains(mod, keywords):
1192
+ keywords = [k.lower() for k in keywords]
1193
+ for name, identifier, socket_type in describe_node_group_inputs(mod):
1194
+ lname = (name or "").lower()
1195
+ if all(k in lname for k in keywords):
1196
+ return identifier, name
1197
+ return None, None
1198
+
1199
+
1200
+ def set_gn_input_by_keywords(mod, keywords, value):
1201
+ identifier, display_name = find_gn_input_identifier_contains(mod, keywords)
1202
+ if identifier is None:
1203
+ log(f" [WARN] No GN input matching keywords {keywords} on '{mod.name}'")
1204
+ return False
1205
+ try:
1206
+ mod[identifier] = value
1207
+ log(f" + {mod.name} '{display_name}' = {value}")
1208
+ return True
1209
+ except Exception as e:
1210
+ log(f" [WARN] Failed setting '{display_name}' on '{mod.name}': {e}")
1211
+ return False
1212
+
1213
+
1214
+ def debug_modifier_inputs(mod):
1215
+ log(f"--- Modifier inputs for {mod.name} ---")
1216
+ for name, identifier, socket_type in describe_node_group_inputs(mod):
1217
+ log(f" name='{name}' identifier='{identifier}' socket_type='{socket_type}'")
1218
+
1219
+
1220
+ def select_and_activate(obj):
1221
+ bpy.ops.object.select_all(action='DESELECT')
1222
+ obj.select_set(True)
1223
+ bpy.context.view_layer.objects.active = obj
1224
+
1225
+
1226
+ def get_essentials_blend_path():
1227
+ candidates = []
1228
+
1229
+ try:
1230
+ local_root = Path(bpy.utils.resource_path('LOCAL'))
1231
+ candidates.append(local_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
1232
+ except Exception:
1233
+ pass
1234
+
1235
+ try:
1236
+ system_root = Path(bpy.utils.resource_path('SYSTEM'))
1237
+ candidates.append(system_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
1238
+ except Exception:
1239
+ pass
1240
+
1241
+ try:
1242
+ user_datafiles = Path(bpy.utils.user_resource('DATAFILES'))
1243
+ candidates.append(user_datafiles / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend")
1244
+ except Exception:
1245
+ pass
1246
+
1247
+ for p in candidates:
1248
+ if p.exists():
1249
+ return p
1250
+
1251
+ raise FileNotFoundError(
1252
+ "Could not locate procedural_hair_node_assets.blend in Blender datafiles."
1253
+ )
1254
+
1255
+
1256
+ def ensure_node_group_loaded_from_blend(node_group_name, blend_path):
1257
+ ng = bpy.data.node_groups.get(node_group_name)
1258
+ if ng is not None:
1259
+ return ng
1260
+
1261
+ blend_path = Path(blend_path)
1262
+ if not blend_path.exists():
1263
+ raise FileNotFoundError(f"Blend library not found: {blend_path}")
1264
+
1265
+ with bpy.data.libraries.load(str(blend_path), link=False) as (data_from, data_to):
1266
+ if node_group_name not in data_from.node_groups:
1267
+ raise RuntimeError(f"Node group '{node_group_name}' not found in {blend_path}")
1268
+ data_to.node_groups = [node_group_name]
1269
+
1270
+ ng = bpy.data.node_groups.get(node_group_name)
1271
+ if ng is None:
1272
+ raise RuntimeError(f"Failed to append node group '{node_group_name}' from {blend_path}")
1273
+ return ng
1274
+
1275
+
1276
+ def add_gn_modifier(curves_obj, node_group_name, modifier_name):
1277
+ select_and_activate(curves_obj)
1278
+
1279
+ blend_path = get_essentials_blend_path()
1280
+ node_group = ensure_node_group_loaded_from_blend(node_group_name, blend_path)
1281
+
1282
+ mod = curves_obj.modifiers.new(name=modifier_name, type='NODES')
1283
+ mod.node_group = node_group
1284
+ return mod
1285
+
1286
+
1287
+ def try_add_gn_modifier(curves_obj, node_group_names, modifier_name):
1288
+ last_err = None
1289
+ for ng_name in node_group_names:
1290
+ try:
1291
+ mod = add_gn_modifier(curves_obj, ng_name, modifier_name)
1292
+ log(f" + Loaded node group '{ng_name}' as '{modifier_name}'")
1293
+ return mod
1294
+ except Exception as e:
1295
+ last_err = e
1296
+ log(f" [WARN] Could not load any of {node_group_names} for '{modifier_name}': {last_err}")
1297
+ return None
1298
+
1299
+
1300
+ def add_custom_post_duplicate_modifier(curves_obj):
1301
+ select_and_activate(curves_obj)
1302
+
1303
+ blend_path = get_essentials_blend_path()
1304
+ noise_ng = ensure_node_group_loaded_from_blend("Hair Curves Noise", blend_path)
1305
+ trim_ng = ensure_node_group_loaded_from_blend("Trim Hair Curves", blend_path)
1306
+
1307
+ bpy.ops.object.modifier_add(type='NODES')
1308
+ mod = curves_obj.modifiers[-1]
1309
+ mod.name = "Custom Post Duplicate Trim"
1310
+
1311
+ bpy.ops.node.new_geometry_node_group_assign()
1312
+ ng = mod.node_group
1313
+ ng.name = f"{curves_obj.name}_CustomPostDuplicateTrim"
1314
+
1315
+ nodes = ng.nodes
1316
+ links = ng.links
1317
+
1318
+ group_in = None
1319
+ group_out = None
1320
+ for node in nodes:
1321
+ if node.bl_idname == "NodeGroupInput":
1322
+ group_in = node
1323
+ elif node.bl_idname == "NodeGroupOutput":
1324
+ group_out = node
1325
+
1326
+ if group_in is None or group_out is None:
1327
+ raise RuntimeError("Failed to get default GN group input/output nodes")
1328
+
1329
+ for node in list(nodes):
1330
+ if node not in {group_in, group_out}:
1331
+ nodes.remove(node)
1332
+
1333
+ group_in.location = (-1000, 0)
1334
+ group_out.location = (500, 0)
1335
+
1336
+ try:
1337
+ id_node = nodes.new("GeometryNodeInputID")
1338
+ except RuntimeError:
1339
+ id_node = nodes.new("GeometryNodeInputIndex")
1340
+ id_node.location = (-1000, -220)
1341
+
1342
+ random_value = nodes.new("FunctionNodeRandomValue")
1343
+ random_value.location = (-760, -220)
1344
+ random_value.data_type = 'BOOLEAN'
1345
+ random_value.inputs["Probability"].default_value = 0.08
1346
+ if "Seed" in random_value.inputs:
1347
+ random_value.inputs["Seed"].default_value = 0
1348
+
1349
+ separate = nodes.new("GeometryNodeSeparateGeometry")
1350
+ separate.location = (-520, 0)
1351
+ separate.domain = 'CURVE'
1352
+
1353
+ noise = nodes.new("GeometryNodeGroup")
1354
+ noise.location = (-220, -40)
1355
+ noise.node_tree = noise_ng
1356
+
1357
+ trim = nodes.new("GeometryNodeGroup")
1358
+ trim.location = (40, -40)
1359
+ trim.node_tree = trim_ng
1360
+
1361
+ join = nodes.new("GeometryNodeJoinGeometry")
1362
+ join.location = (260, 20)
1363
+
1364
+ if "Factor" in noise.inputs:
1365
+ noise.inputs["Factor"].default_value = 1.0
1366
+ if "Distance" in noise.inputs:
1367
+ noise.inputs["Distance"].default_value = 0.002
1368
+ if "Shape" in noise.inputs:
1369
+ noise.inputs["Shape"].default_value = 0.5
1370
+ if "Scale" in noise.inputs:
1371
+ noise.inputs["Scale"].default_value = 1.0
1372
+ if "Scale Along Length" in noise.inputs:
1373
+ noise.inputs["Scale Along Length"].default_value = 1.0
1374
+ if "Offset" in noise.inputs:
1375
+ noise.inputs["Offset"].default_value = 0.0
1376
+ if "Cumulative Offset" in noise.inputs:
1377
+ noise.inputs["Cumulative Offset"].default_value = False
1378
+ if "Seed" in noise.inputs:
1379
+ noise.inputs["Seed"].default_value = 0
1380
+
1381
+ if "Mask" in trim.inputs:
1382
+ trim.inputs["Mask"].default_value = 1.0
1383
+ if "Random Offset" in trim.inputs:
1384
+ trim.inputs["Random Offset"].default_value = 0.03
1385
+ if "Pin at Parameter" in trim.inputs:
1386
+ trim.inputs["Pin at Parameter"].default_value = 0.0
1387
+ if "Seed" in trim.inputs:
1388
+ trim.inputs["Seed"].default_value = 0
1389
+ if "Replace Length" in trim.inputs:
1390
+ trim.inputs["Replace Length"].default_value = False
1391
+
1392
+ if "ID" in random_value.inputs:
1393
+ if "ID" in id_node.outputs:
1394
+ links.new(id_node.outputs["ID"], random_value.inputs["ID"])
1395
+ else:
1396
+ links.new(id_node.outputs["Index"], random_value.inputs["ID"])
1397
+
1398
+ links.new(group_in.outputs["Geometry"], separate.inputs["Geometry"])
1399
+ links.new(random_value.outputs["Value"], separate.inputs["Selection"])
1400
+
1401
+ links.new(separate.outputs["Selection"], noise.inputs["Geometry"])
1402
+ links.new(noise.outputs["Geometry"], trim.inputs["Geometry"])
1403
+
1404
+ links.new(separate.outputs["Inverted"], join.inputs["Geometry"])
1405
+ links.new(trim.outputs["Geometry"], join.inputs["Geometry"])
1406
+ links.new(join.outputs["Geometry"], group_out.inputs["Geometry"])
1407
+
1408
+ log(f" + Custom Post Duplicate Trim on {curves_obj.name}")
1409
+ return mod
1410
+
1411
+
1412
+ def setup_modifiers(curves_obj, group_name, mesh_obj, hair_info):
1413
+ is_mouse = group_name == "mouse_fur"
1414
+ is_face = group_name == "face_fur"
1415
+ is_ear = group_name == "ear_fur"
1416
+
1417
+ profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "Set Hair Curve Profile")
1418
+ set_gn_input(profile_mod, "Radius", 0.00012)
1419
+ log(" + Set Hair Curve Profile (radius=0.0001)")
1420
+
1421
+ add_custom_post_duplicate_modifier(curves_obj)
1422
+
1423
+ if (not is_mouse) and (not is_face):
1424
+ if(not is_ear):
1425
+ mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves")
1426
+ set_gn_input(mod, "Amount", 8)
1427
+ set_gn_input(mod, "Radius", 0.007)
1428
+ set_gn_input(mod, "Distribution Shape", 1.0)
1429
+ log(" + Duplicate Hair Curves (radius=0.005, distribution_shape=1.0)")
1430
+
1431
+ frizz_mod = try_add_gn_modifier(
1432
+ curves_obj,
1433
+ ["Frizz Hair Curves", "Hair Curves Frizz"],
1434
+ "Frizz Hair Curves"
1435
+ )
1436
+ if frizz_mod is not None:
1437
+ set_gn_input(frizz_mod, "Factor", 0.7)
1438
+ set_gn_input(frizz_mod, "Distance", 0.001)
1439
+ set_gn_input(frizz_mod, "Shape", 0.01)
1440
+ log(" + Frizz Hair Curves (factor=0.7, distance=0.001, shape=0.01)")
1441
+ else:
1442
+ log(" + Skip Duplicate Hair Curves for mouse_fur/face")
1443
+
1444
+ if is_face or is_ear:
1445
+ mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves")
1446
+ set_gn_input(mod, "Amount", 3)
1447
+ set_gn_input(mod, "Radius", 0.005)
1448
+ set_gn_input(mod, "Distribution Shape", 1.0)
1449
+
1450
+
1451
+
1452
+ def delete_default_cube():
1453
+ cube = bpy.data.objects.get("Cube")
1454
+ if cube is None:
1455
+ return
1456
+
1457
+ bpy.ops.object.select_all(action='DESELECT')
1458
+ cube.select_set(True)
1459
+ bpy.context.view_layer.objects.active = cube
1460
+ bpy.ops.object.delete()
1461
+
1462
+ log("Deleted default Cube")
1463
+
1464
+
1465
+ def clear_material_slots(obj):
1466
+ if not hasattr(obj.data, "materials"):
1467
+ return
1468
+ obj.data.materials.clear()
1469
+
1470
+
1471
+ def assign_material(obj, material):
1472
+ if not hasattr(obj.data, "materials"):
1473
+ return
1474
+ obj.data.materials.clear()
1475
+ obj.data.materials.append(material)
1476
+ if hasattr(obj, "active_material"):
1477
+ obj.active_material = material
1478
+
1479
+
1480
+ def extract_numeric_suffix(name: str):
1481
+ m = re.search(r"(\d+)$", name)
1482
+ return int(m.group(1)) if m else None
1483
+
1484
+
1485
+ def natural_key(path: Path):
1486
+ parts = re.split(r"(\d+)", path.stem.lower())
1487
+ key = []
1488
+ for p in parts:
1489
+ if p.isdigit():
1490
+ key.append(int(p))
1491
+ else:
1492
+ key.append(p)
1493
+ key.append(path.suffix.lower())
1494
+ return key
1495
+
1496
+
1497
+ def find_texture_for_obj(obj_path: str, textures_dir: str):
1498
+ """
1499
+ Match a shape OBJ to a texture by natural-sort index.
1500
+
1501
+ This mirrors the dataset auxiliary-file rule after excluding hidden and
1502
+ macOS resource-fork files. For a group with five real shapes and five
1503
+ textures, only those five files participate in pairing.
1504
+ """
1505
+ obj_path = Path(obj_path).expanduser().resolve()
1506
+ textures_dir = Path(textures_dir).expanduser().resolve()
1507
+ shapes_dir = obj_path.parent.resolve()
1508
+
1509
+ if not shapes_dir.is_dir():
1510
+ raise FileNotFoundError(f"Shapes directory not found: {shapes_dir}")
1511
+ if not textures_dir.is_dir():
1512
+ raise FileNotFoundError(f"Textures directory not found: {textures_dir}")
1513
+ if not is_usable_file(obj_path):
1514
+ raise FileNotFoundError(
1515
+ f"OBJ is missing or is a hidden/macOS metadata file: {obj_path}"
1516
+ )
1517
+
1518
+ shape_files = sorted(
1519
+ [
1520
+ path
1521
+ for path in shapes_dir.iterdir()
1522
+ if is_usable_file(path)
1523
+ and path.suffix.lower() == ".obj"
1524
+ ],
1525
+ key=natural_key,
1526
+ )
1527
+ texture_files = sorted(
1528
+ [
1529
+ path
1530
+ for path in textures_dir.iterdir()
1531
+ if is_usable_file(path)
1532
+ and path.suffix.lower() in IMAGE_EXTS
1533
+ ],
1534
+ key=natural_key,
1535
+ )
1536
+
1537
+ if not shape_files:
1538
+ raise FileNotFoundError(f"No usable shape OBJ files found in: {shapes_dir}")
1539
+ if not texture_files:
1540
+ raise FileNotFoundError(f"No usable texture files found in: {textures_dir}")
1541
+
1542
+ try:
1543
+ shape_index = next(
1544
+ index
1545
+ for index, path in enumerate(shape_files)
1546
+ if path.resolve() == obj_path
1547
+ )
1548
+ except StopIteration as exc:
1549
+ raise FileNotFoundError(
1550
+ f"Could not find usable OBJ {obj_path.name} in: {shapes_dir}"
1551
+ ) from exc
1552
+
1553
+ if len(texture_files) == 1:
1554
+ chosen = texture_files[0]
1555
+ elif shape_index < len(texture_files):
1556
+ chosen = texture_files[shape_index]
1557
+ else:
1558
+ raise IndexError(
1559
+ "Texture index out of range after hidden-file filtering. "
1560
+ f"usable_shapes={len(shape_files)}, "
1561
+ f"usable_textures={len(texture_files)}, "
1562
+ f"shape_index={shape_index}, obj={obj_path.name}"
1563
+ )
1564
+
1565
+ log(
1566
+ "Texture matched by natural-sort index: "
1567
+ f"shape[{shape_index}]={obj_path.name} -> {chosen.name}; "
1568
+ f"usable_shapes={len(shape_files)}, "
1569
+ f"usable_textures={len(texture_files)}"
1570
+ )
1571
+ return chosen
1572
+
1573
+
1574
+ def set_node_input_if_exists(node, input_name, value):
1575
+ if input_name in node.inputs:
1576
+ node.inputs[input_name].default_value = value
1577
+
1578
+
1579
+ def set_enum_attr_if_exists(node, attr_names, value):
1580
+ for attr in attr_names:
1581
+ if hasattr(node, attr):
1582
+ try:
1583
+ setattr(node, attr, value)
1584
+ return True
1585
+ except Exception:
1586
+ pass
1587
+ return False
1588
+
1589
+
1590
+ def create_mesh_material(mesh_obj, texture_path: str, normal_path: str, roughness_path: str, material_name="MeshMaterial"):
1591
+ texture_path = Path(texture_path).resolve()
1592
+ normal_path = Path(normal_path).resolve() if normal_path else None
1593
+ roughness_path = Path(roughness_path).resolve() if roughness_path else None
1594
+
1595
+ if not is_usable_file(texture_path):
1596
+ raise FileNotFoundError(
1597
+ f"Mesh texture is missing or hidden: {texture_path}"
1598
+ )
1599
+
1600
+ mat = bpy.data.materials.get(material_name)
1601
+ if mat is None:
1602
+ mat = bpy.data.materials.new(material_name)
1603
+ mat.use_nodes = True
1604
+
1605
+ nt = mat.node_tree
1606
+ nodes = nt.nodes
1607
+ links = nt.links
1608
+ nodes.clear()
1609
+
1610
+ out = nodes.new("ShaderNodeOutputMaterial")
1611
+ out.location = (700, 0)
1612
+
1613
+ bsdf = nodes.new("ShaderNodeBsdfPrincipled")
1614
+ bsdf.location = (350, 0)
1615
+ set_node_input_if_exists(bsdf, "IOR", 1.5)
1616
+
1617
+ tex_color = nodes.new("ShaderNodeTexImage")
1618
+ tex_color.location = (-450, 150)
1619
+ tex_color.image = open_image_color(str(texture_path))
1620
+ tex_color.interpolation = 'Linear'
1621
+ tex_color.extension = 'REPEAT'
1622
+
1623
+ links.new(tex_color.outputs["Color"], bsdf.inputs["Base Color"])
1624
+ if "Alpha" in tex_color.outputs and "Alpha" in bsdf.inputs:
1625
+ links.new(tex_color.outputs["Alpha"], bsdf.inputs["Alpha"])
1626
+
1627
+ if roughness_path is not None and is_usable_file(roughness_path):
1628
+ tex_rough = nodes.new("ShaderNodeTexImage")
1629
+ tex_rough.location = (-450, -50)
1630
+ tex_rough.image = open_image_simple(str(roughness_path), non_color=True)
1631
+ tex_rough.interpolation = 'Linear'
1632
+ tex_rough.extension = 'REPEAT'
1633
+ links.new(tex_rough.outputs["Color"], bsdf.inputs["Roughness"])
1634
+ else:
1635
+ set_node_input_if_exists(bsdf, "Roughness", 0.5)
1636
+ log("Roughness map not found; using constant roughness=0.5")
1637
+
1638
+ if normal_path is not None and is_usable_file(normal_path):
1639
+ tex_normal = nodes.new("ShaderNodeTexImage")
1640
+ tex_normal.location = (-450, -250)
1641
+ tex_normal.image = open_image_simple(str(normal_path), non_color=True)
1642
+ tex_normal.interpolation = 'Linear'
1643
+ tex_normal.extension = 'REPEAT'
1644
+
1645
+ normal_map = nodes.new("ShaderNodeNormalMap")
1646
+ normal_map.location = (-100, -250)
1647
+ set_node_input_if_exists(normal_map, "Strength", 1.0)
1648
+ links.new(tex_normal.outputs["Color"], normal_map.inputs["Color"])
1649
+ links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"])
1650
+ else:
1651
+ log("Normal map not found; using mesh normals")
1652
+
1653
+ links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])
1654
+
1655
+ try:
1656
+ mat.blend_method = 'HASHED'
1657
+ except Exception:
1658
+ pass
1659
+ try:
1660
+ mat.shadow_method = 'HASHED'
1661
+ except Exception:
1662
+ pass
1663
+
1664
+ assign_material(mesh_obj, mat)
1665
+ log(f"Assigned mesh material: {mat.name}")
1666
+ return mat
1667
+
1668
+
1669
+ def create_hair_material(texture_path: str, material_name="HairMaterial"):
1670
+ texture_path = require_usable_file(
1671
+ texture_path,
1672
+ "Hair texture",
1673
+ )
1674
+
1675
+ mat = bpy.data.materials.get(material_name)
1676
+ if mat is None:
1677
+ mat = bpy.data.materials.new(material_name)
1678
+ mat.use_nodes = True
1679
+
1680
+ nt = mat.node_tree
1681
+ nodes = nt.nodes
1682
+ links = nt.links
1683
+ nodes.clear()
1684
+
1685
+ tex_mesh = nodes.new("ShaderNodeTexImage")
1686
+ tex_mesh.location = (-900, 200)
1687
+ tex_mesh.image = open_image_color(str(texture_path))
1688
+ tex_mesh.interpolation = 'Linear'
1689
+ tex_mesh.extension = 'REPEAT'
1690
+
1691
+ tex_hair = nodes.new("ShaderNodeTexImage")
1692
+ tex_hair.location = (-900, -200)
1693
+ tex_hair.image = open_image_color(str(texture_path))
1694
+ tex_hair.interpolation = 'Linear'
1695
+ tex_hair.extension = 'REPEAT'
1696
+
1697
+ bsdf = nodes.new("ShaderNodeBsdfPrincipled")
1698
+ bsdf.location = (-500, 180)
1699
+ set_node_input_if_exists(bsdf, "IOR", 1.5)
1700
+ set_node_input_if_exists(bsdf, "Roughness", 0.5)
1701
+ set_node_input_if_exists(bsdf, "Alpha", 1.0)
1702
+
1703
+ hair_bsdf = nodes.new("ShaderNodeBsdfHairPrincipled")
1704
+ hair_bsdf.location = (-500, -220)
1705
+
1706
+ set_enum_attr_if_exists(hair_bsdf, ["model", "distribution"], 'CHIANG')
1707
+ set_enum_attr_if_exists(hair_bsdf, ["parametrization"], 'COLOR')
1708
+
1709
+ set_node_input_if_exists(hair_bsdf, "Roughness", 0.4)
1710
+ set_node_input_if_exists(hair_bsdf, "Radial Roughness", 0.6)
1711
+ set_node_input_if_exists(hair_bsdf, "Coat", 0.0)
1712
+ set_node_input_if_exists(hair_bsdf, "IOR", 1.5)
1713
+ set_node_input_if_exists(hair_bsdf, "Offset", math.radians(3.0))
1714
+ set_node_input_if_exists(hair_bsdf, "Random Roughness", 0.25)
1715
+
1716
+ mix_main = nodes.new("ShaderNodeMixShader")
1717
+ mix_main.location = (-120, 20)
1718
+ if "Fac" in mix_main.inputs:
1719
+ mix_main.inputs["Fac"].default_value = 0.6
1720
+
1721
+ transparent = nodes.new("ShaderNodeBsdfTransparent")
1722
+ transparent.location = (-120, -260)
1723
+
1724
+ light_path = nodes.new("ShaderNodeLightPath")
1725
+ light_path.location = (-360, 320)
1726
+
1727
+ mix_shadow = nodes.new("ShaderNodeMixShader")
1728
+ mix_shadow.location = (180, 50)
1729
+
1730
+ out = nodes.new("ShaderNodeOutputMaterial")
1731
+ out.location = (420, 50)
1732
+
1733
+ links.new(tex_mesh.outputs["Color"], bsdf.inputs["Base Color"])
1734
+ links.new(tex_hair.outputs["Color"], hair_bsdf.inputs["Color"])
1735
+ links.new(bsdf.outputs["BSDF"], mix_main.inputs[1])
1736
+ links.new(hair_bsdf.outputs["BSDF"], mix_main.inputs[2])
1737
+ links.new(light_path.outputs["Is Shadow Ray"], mix_shadow.inputs["Fac"])
1738
+ links.new(mix_main.outputs["Shader"], mix_shadow.inputs[1])
1739
+ links.new(transparent.outputs["BSDF"], mix_shadow.inputs[2])
1740
+ links.new(mix_shadow.outputs["Shader"], out.inputs["Surface"])
1741
+
1742
+ try:
1743
+ mat.blend_method = 'HASHED'
1744
+ except Exception:
1745
+ pass
1746
+ try:
1747
+ mat.shadow_method = 'HASHED'
1748
+ except Exception:
1749
+ pass
1750
+ try:
1751
+ mat.use_backface_culling = False
1752
+ except Exception:
1753
+ pass
1754
+
1755
+ log(f"Created hair material: {mat.name}")
1756
+ return mat
1757
+
1758
+
1759
+ def setup_cycles_render(scene):
1760
+ scene.render.engine = 'CYCLES'
1761
+ scene.cycles.samples = 64
1762
+ try:
1763
+ scene.cycles.device = 'GPU'
1764
+ except Exception:
1765
+ pass
1766
+ try:
1767
+ scene.render.film_transparent = True
1768
+ except Exception:
1769
+ pass
1770
+
1771
+ try:
1772
+ scene.view_layers["ViewLayer"].cycles.use_denoising = False
1773
+ except Exception:
1774
+ pass
1775
+
1776
+ log("Set render engine to Cycles")
1777
+
1778
+
1779
+ def setup_world_hdr(hdr_path: str):
1780
+ hdr_path = require_usable_file(hdr_path, "HDR image")
1781
+
1782
+ scene = bpy.context.scene
1783
+ world = scene.world
1784
+ if world is None:
1785
+ world = bpy.data.worlds.new("World")
1786
+ scene.world = world
1787
+
1788
+ world.use_nodes = True
1789
+ nt = world.node_tree
1790
+ nodes = nt.nodes
1791
+ links = nt.links
1792
+ nodes.clear()
1793
+
1794
+ tex_coord = nodes.new("ShaderNodeTexCoord")
1795
+ tex_coord.location = (-900, 0)
1796
+
1797
+ mapping = nodes.new("ShaderNodeMapping")
1798
+ mapping.location = (-700, 0)
1799
+
1800
+ env_tex = nodes.new("ShaderNodeTexEnvironment")
1801
+ env_tex.location = (-500, 0)
1802
+ env_tex.image = bpy.data.images.load(filepath=str(hdr_path), check_existing=True)
1803
+
1804
+ background = nodes.new("ShaderNodeBackground")
1805
+ background.location = (-220, 0)
1806
+ background.inputs["Strength"].default_value = random.uniform(0.4, 0.6)
1807
+
1808
+ world_out = nodes.new("ShaderNodeOutputWorld")
1809
+ world_out.location = (300, 0)
1810
+
1811
+ links.new(tex_coord.outputs["Generated"], mapping.inputs["Vector"])
1812
+ links.new(mapping.outputs["Vector"], env_tex.inputs["Vector"])
1813
+ links.new(env_tex.outputs["Color"], background.inputs["Color"])
1814
+ links.new(background.outputs["Background"], world_out.inputs["Surface"])
1815
+
1816
+ scene.render.film_transparent = True
1817
+ log(f"Set HDR world lighting: {hdr_path}")
1818
+
1819
+ def compute_mesh_bbox_center_and_radius(mesh_obj):
1820
+ """Compute the world-space bounding box center and enclosing sphere radius."""
1821
+ bbox_corners = [mesh_obj.matrix_world @ Vector(c) for c in mesh_obj.bound_box]
1822
+ bbox_min = Vector((
1823
+ min(c.x for c in bbox_corners),
1824
+ min(c.y for c in bbox_corners),
1825
+ min(c.z for c in bbox_corners),
1826
+ ))
1827
+ bbox_max = Vector((
1828
+ max(c.x for c in bbox_corners),
1829
+ max(c.y for c in bbox_corners),
1830
+ max(c.z for c in bbox_corners),
1831
+ ))
1832
+ center = (bbox_min + bbox_max) / 2.0
1833
+ radius = (bbox_max - bbox_min).length / 2.0
1834
+ return center, radius
1835
+
1836
+
1837
+ def ensure_camera(mesh_obj=None, h_range=(-20, 20), v_range=(10, 30), render_size=1024, padding=0.9):
1838
+ """Create/reuse a camera with random orbit around the mesh.
1839
+
1840
+ Args:
1841
+ mesh_obj: The target mesh. If None, falls back to a fixed position.
1842
+ h_range: (min_deg, max_deg) horizontal rotation range around the object.
1843
+ 0 = front (+X axis looking at center), negative = left, positive = right.
1844
+ v_range: (min_deg, max_deg) vertical elevation range.
1845
+ 0 = horizon level, 45 = looking down at 45 degrees.
1846
+ render_size: Output image resolution (square).
1847
+ padding: Multiplier on the camera distance to ensure the whole mesh
1848
+ (including hair) fits in frame. >1.0 adds margin.
1849
+ """
1850
+ cam_obj = bpy.data.objects.get("RenderCamera")
1851
+ if cam_obj is None or cam_obj.type != 'CAMERA':
1852
+ cam_data = bpy.data.cameras.new("RenderCamera")
1853
+ cam_obj = bpy.data.objects.new("RenderCamera", cam_data)
1854
+ bpy.context.collection.objects.link(cam_obj)
1855
+
1856
+ scene = bpy.context.scene
1857
+ scene.camera = cam_obj
1858
+
1859
+ # Set render resolution to 512x512
1860
+ scene.render.resolution_x = render_size
1861
+ scene.render.resolution_y = render_size
1862
+ scene.render.resolution_percentage = 100
1863
+
1864
+ if mesh_obj is None:
1865
+ # Fallback: fixed position
1866
+ cam_obj.location = (2.0, 0.0, 0.0)
1867
+ cam_obj.rotation_euler = (
1868
+ math.radians(90.0),
1869
+ math.radians(0.0),
1870
+ math.radians(90.0),
1871
+ )
1872
+ log("Set camera at fixed fallback position (no mesh provided)")
1873
+ return cam_obj
1874
+
1875
+ # Compute mesh bounding sphere
1876
+ center, radius = compute_mesh_bbox_center_and_radius(mesh_obj)
1877
+ if radius < 1e-6:
1878
+ radius = 1.0
1879
+
1880
+ # Random angles
1881
+ h_deg = random.uniform(h_range[0], h_range[1])
1882
+ v_deg = random.uniform(v_range[0], v_range[1])
1883
+ h_rad = math.radians(h_deg)
1884
+ v_rad = math.radians(v_deg)
1885
+
1886
+ # Compute camera distance so the bounding sphere fits in the FOV
1887
+ cam_data = cam_obj.data
1888
+ cam_data.sensor_fit = 'AUTO'
1889
+ # cam_data.angle = 75
1890
+ # cam_data.fov = 75
1891
+ cam_data.lens = 75
1892
+
1893
+ print(cam_data.angle)
1894
+ fov = cam_data.angle # full horizontal FOV in radians
1895
+ half_fov = fov / 2.0
1896
+
1897
+ # Distance from center so the sphere of size (radius * padding) fits
1898
+ distance = (radius * padding) / math.sin(half_fov)
1899
+ if distance < 0.01:
1900
+ distance = 2.0
1901
+
1902
+ # Spherical coordinates -> cartesian offset from center
1903
+ # h_rad=0 means looking from +X toward center (front view)
1904
+ # v_rad=0 means at horizon level, v_rad>0 means elevated (looking down)
1905
+ cam_x = center.x + distance * math.cos(v_rad) * math.cos(h_rad)
1906
+ cam_y = center.y + distance * math.cos(v_rad) * math.sin(h_rad)
1907
+ cam_z = center.z + distance * math.sin(v_rad)
1908
+
1909
+ cam_obj.location = (cam_x, cam_y, cam_z)
1910
+
1911
+ # Point camera at center using a track-to constraint (most robust)
1912
+ # Remove any existing track-to constraint first
1913
+ for c in list(cam_obj.constraints):
1914
+ if c.type == 'TRACK_TO':
1915
+ cam_obj.constraints.remove(c)
1916
+
1917
+ # Create an empty at the mesh center as the track target
1918
+ target_empty = bpy.data.objects.get("CameraTarget")
1919
+ if target_empty is None:
1920
+ target_empty = bpy.data.objects.new("CameraTarget", None)
1921
+ bpy.context.collection.objects.link(target_empty)
1922
+ target_empty.location = center
1923
+ target_empty.empty_display_size = 0.01
1924
+ target_empty.hide_viewport = True
1925
+ target_empty.hide_render = True
1926
+
1927
+ constraint = cam_obj.constraints.new(type='TRACK_TO')
1928
+ constraint.target = target_empty
1929
+ constraint.track_axis = 'TRACK_NEGATIVE_Z'
1930
+ constraint.up_axis = 'UP_Y'
1931
+
1932
+ # Force update so the constraint takes effect
1933
+ bpy.context.view_layer.update()
1934
+
1935
+ log(
1936
+ f"Camera: h={h_deg:.1f}° v={v_deg:.1f}° dist={distance:.3f} "
1937
+ f"center=({center.x:.3f},{center.y:.3f},{center.z:.3f}) "
1938
+ f"render={render_size}x{render_size}"
1939
+ )
1940
+ return cam_obj
1941
+
1942
+
1943
+ def sample_image_luminance_at_uv(img, uv, pixels_np=None):
1944
+ width, height = img.size
1945
+
1946
+ if pixels_np is None:
1947
+ pixel_count = width * height * 4
1948
+ pixels_np = np.empty(pixel_count, dtype=np.float32)
1949
+ img.pixels.foreach_get(pixels_np)
1950
+ pixels_np = pixels_np.reshape((height, width, 4))
1951
+
1952
+ u = float(np.clip(uv[0], 0.0, 1.0))
1953
+ v = float(np.clip(uv[1], 0.0, 1.0))
1954
+ xi = int(u * (width - 1))
1955
+ yi = int(v * (height - 1))
1956
+
1957
+ rgba = pixels_np[yi, xi]
1958
+ lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]
1959
+ return float(lum)
1960
+
1961
+
1962
+ def remove_curve_uv_attributes(curves_obj):
1963
+ curves = curves_obj.data
1964
+
1965
+ try:
1966
+ curves.surface_uv_map = ""
1967
+ except Exception:
1968
+ pass
1969
+
1970
+ for attr_name in ["surface_uv_coordinate", "uv_map", "UVMap", "UV", "map1"]:
1971
+ attr = curves.attributes.get(attr_name)
1972
+ if attr is not None:
1973
+ try:
1974
+ curves.attributes.remove(attr)
1975
+ log(f" Removed curve attribute: {attr_name}")
1976
+ except Exception as e:
1977
+ log(f" [WARN] Failed removing curve attribute '{attr_name}': {e}")
1978
+
1979
+
1980
+ def create_underhair_guides_from_mesh(mesh_obj, mask_image_path, strand_length=0.01, threshold=0.05):
1981
+ """Create underhair guide strands using the evaluated (deformed) mesh."""
1982
+ mesh = mesh_obj.data
1983
+ if not mesh.uv_layers.active:
1984
+ raise RuntimeError("Mesh has no active UV layer; underhair mask sampling requires UVs.")
1985
+
1986
+ mask_img = open_image_simple(str(mask_image_path), non_color=True)
1987
+ width, height = mask_img.size
1988
+
1989
+ pixel_count = width * height * 4
1990
+ pixels_np = np.empty(pixel_count, dtype=np.float32)
1991
+ mask_img.pixels.foreach_get(pixels_np)
1992
+ pixels_np = pixels_np.reshape((height, width, 4))
1993
+
1994
+ # Use evaluated mesh for vertex positions and normals
1995
+ eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj)
1996
+
1997
+ total_loops = len(eval_mesh.loops)
1998
+ loop_uvs = np.empty(total_loops * 2, dtype=np.float32)
1999
+ eval_mesh.uv_layers.active.data.foreach_get("uv", loop_uvs)
2000
+ loop_uvs = loop_uvs.reshape((total_loops, 2))
2001
+
2002
+ loop_verts = np.empty(total_loops, dtype=np.int32)
2003
+ eval_mesh.loops.foreach_get("vertex_index", loop_verts)
2004
+
2005
+ num_verts = len(eval_mesh.vertices)
2006
+ uv_sum = np.zeros((num_verts, 2), dtype=np.float64)
2007
+ uv_cnt = np.zeros(num_verts, dtype=np.int32)
2008
+
2009
+ np.add.at(uv_sum[:, 0], loop_verts, loop_uvs[:, 0])
2010
+ np.add.at(uv_sum[:, 1], loop_verts, loop_uvs[:, 1])
2011
+ np.add.at(uv_cnt, loop_verts, 1)
2012
+
2013
+ valid = uv_cnt > 0
2014
+ avg_uv = np.zeros((num_verts, 2), dtype=np.float64)
2015
+ avg_uv[valid] = uv_sum[valid] / uv_cnt[valid][:, None]
2016
+
2017
+ strands = []
2018
+ weights = np.zeros(num_verts, dtype=np.float32)
2019
+
2020
+ for vid in range(num_verts):
2021
+ if not valid[vid]:
2022
+ continue
2023
+
2024
+ uv = avg_uv[vid]
2025
+ w = sample_image_luminance_at_uv(mask_img, uv, pixels_np=pixels_np)
2026
+ weights[vid] = w
2027
+
2028
+ if w <= threshold:
2029
+ continue
2030
+
2031
+ root = eval_mesh.vertices[vid].co.copy()
2032
+ normal = eval_mesh.vertices[vid].normal.normalized()
2033
+ tip = root + normal * float(strand_length)
2034
+
2035
+ strand = np.stack([
2036
+ np.array((root.x, root.y, root.z), dtype=np.float32),
2037
+ np.array((tip.x, tip.y, tip.z), dtype=np.float32),
2038
+ ], axis=0)
2039
+ strands.append(strand)
2040
+
2041
+ eval_obj.to_mesh_clear()
2042
+
2043
+ old_vg = mesh_obj.vertex_groups.get(UNDERHAIR_MASK_GROUP)
2044
+ if old_vg is not None:
2045
+ mesh_obj.vertex_groups.remove(old_vg)
2046
+ vg = mesh_obj.vertex_groups.new(name=UNDERHAIR_MASK_GROUP)
2047
+
2048
+ for vid, w in enumerate(weights):
2049
+ if w > 0.0:
2050
+ vg.add([vid], float(w), 'REPLACE')
2051
+
2052
+ log(f"Created underhair guides: {len(strands)} strands")
2053
+ return strands, vg, mask_img
2054
+
2055
+
2056
+ def setup_underhair_modifiers(curves_obj, mesh_obj, mask_img, trim_length=0.01):
2057
+ profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "UnderHair Profile")
2058
+ set_gn_input(profile_mod, "Radius", 0.0001)
2059
+ log(" + UnderHair Profile (radius=0.0001)")
2060
+
2061
+ interp_mod = add_gn_modifier(curves_obj, "Interpolate Hair Curves", "UnderHair Interpolate")
2062
+
2063
+ try:
2064
+ interp_mod["Input_2"] = mesh_obj
2065
+ log(f" + UnderHair Interpolate Input_2 = {mesh_obj.name}")
2066
+ except Exception as e:
2067
+ log(f" [WARN] Failed setting UnderHair Interpolate Input_2: {e}")
2068
+
2069
+ set_gn_input(interp_mod, "Surface", mesh_obj)
2070
+ set_gn_input(interp_mod, "Surface Object", mesh_obj)
2071
+ set_gn_input(interp_mod, "Mesh", mesh_obj)
2072
+
2073
+ density_set = False
2074
+ density_set |= set_gn_input(interp_mod, "Surface Density", UNDERHAIR_INTERP_DENSITY)
2075
+ density_set |= set_gn_input(interp_mod, "Density", UNDERHAIR_INTERP_DENSITY)
2076
+ density_set |= set_gn_input_by_keywords(interp_mod, ["density"], UNDERHAIR_INTERP_DENSITY)
2077
+ density_set |= set_gn_input_by_keywords(interp_mod, ["surface", "density"], UNDERHAIR_INTERP_DENSITY)
2078
+
2079
+ if not density_set:
2080
+ log(" [WARN] Could not find interpolation density socket; value may remain default")
2081
+
2082
+ set_gn_input(interp_mod, "Interpolation Quality", 6)
2083
+ set_gn_input(interp_mod, "Variation Level", 0.15)
2084
+ set_gn_input(interp_mod, "Guide Mask", 0.0)
2085
+ set_gn_input(interp_mod, "Use Guide Mask", False)
2086
+
2087
+ interp_tex_id = get_node_input_identifier_by_name(interp_mod, "Mask Texture")
2088
+ if interp_tex_id is not None:
2089
+ try:
2090
+ interp_mod[interp_tex_id] = mask_img
2091
+ log(" + UnderHair Interpolate mask texture = merged.png")
2092
+ except Exception as e:
2093
+ log(f" [WARN] Failed to assign interpolate mask texture: {e}")
2094
+
2095
+ log(" + UnderHair Interpolate configured")
2096
+
2097
+ noise_mod = add_gn_modifier(curves_obj, "Hair Curves Noise", "UnderHair Noise")
2098
+ set_gn_input(noise_mod, "Factor", 1.0)
2099
+ set_gn_input(noise_mod, "Distance", 0.0015)
2100
+ set_gn_input(noise_mod, "Shape", 0.5)
2101
+ set_gn_input(noise_mod, "Scale", 18.0)
2102
+ set_gn_input(noise_mod, "Scale Along Length", 1.0)
2103
+ set_gn_input(noise_mod, "Offset", 0.0)
2104
+ set_gn_input(noise_mod, "Cumulative Offset", False)
2105
+ set_gn_input(noise_mod, "Seed", 0)
2106
+ log(" + UnderHair Noise")
2107
+
2108
+ frizz_mod = try_add_gn_modifier(
2109
+ curves_obj,
2110
+ ["Frizz Hair Curves", "Hair Curves Frizz"],
2111
+ "UnderHair Frizz"
2112
+ )
2113
+ if frizz_mod is not None:
2114
+ set_gn_input(frizz_mod, "Amount", 0.6)
2115
+ set_gn_input(frizz_mod, "Radius", 0.001)
2116
+ set_gn_input(frizz_mod, "Frequency", 12.0)
2117
+ set_gn_input(frizz_mod, "Seed", 0)
2118
+ set_gn_input(frizz_mod, "Mask", 1.0)
2119
+
2120
+ frizz_tex_id = get_node_input_identifier_by_name(frizz_mod, "Mask Texture")
2121
+ if frizz_tex_id is not None:
2122
+ try:
2123
+ frizz_mod[frizz_tex_id] = mask_img
2124
+ log(" + UnderHair Frizz mask texture = merged.png")
2125
+ except Exception as e:
2126
+ log(f" [WARN] Failed to assign frizz mask texture: {e}")
2127
+
2128
+ log(" + UnderHair Frizz")
2129
+
2130
+ trim_mod = add_gn_modifier(curves_obj, "Trim Hair Curves", "UnderHair Trim")
2131
+ set_gn_input(trim_mod, "Mask", 1.0)
2132
+ set_gn_input(trim_mod, "Random Offset", 0.0)
2133
+ set_gn_input(trim_mod, "Pin at Parameter", 0.0)
2134
+ set_gn_input(trim_mod, "Replace Length", True)
2135
+ set_gn_input(trim_mod, "Length", float(trim_length))
2136
+
2137
+ trim_tex_id = get_node_input_identifier_by_name(trim_mod, "Mask Texture")
2138
+ if trim_tex_id is not None:
2139
+ try:
2140
+ trim_mod[trim_tex_id] = mask_img
2141
+ log(" + UnderHair Trim mask texture = merged.png")
2142
+ except Exception as e:
2143
+ log(f" [WARN] Failed to assign trim mask texture: {e}")
2144
+
2145
+ log(f" + UnderHair Trim (length={trim_length})")
2146
+
2147
+
2148
+ def create_underhair_if_available(mesh_obj, mesh_material, mask_image_path):
2149
+ mask_path = Path(mask_image_path).resolve()
2150
+ if not mask_path.exists():
2151
+ log(f"Underhair mask not found; skipping underhair: {mask_path}")
2152
+ return None
2153
+ return create_underhair_on_mesh(
2154
+ mesh_obj=mesh_obj,
2155
+ mesh_material=mesh_material,
2156
+ mask_image_path=str(mask_path),
2157
+ )
2158
+
2159
+
2160
+ def create_underhair_on_mesh(mesh_obj, mesh_material, mask_image_path):
2161
+ log("Creating underhair from mesh surface...")
2162
+
2163
+ strands, mask_vg, mask_img = create_underhair_guides_from_mesh(
2164
+ mesh_obj=mesh_obj,
2165
+ mask_image_path=str(mask_image_path),
2166
+ strand_length=UNDERHAIR_LENGTH,
2167
+ threshold=0.05,
2168
+ )
2169
+
2170
+ if len(strands) == 0:
2171
+ log(" [WARN] No underhair strands created from mask.")
2172
+ return None
2173
+
2174
+ underhair_obj = build_curve_object_from_strands_no_uv(
2175
+ obj_name="underhair",
2176
+ strands=strands,
2177
+ mesh_obj=mesh_obj,
2178
+ )
2179
+ if underhair_obj is None:
2180
+ return None
2181
+
2182
+ remove_curve_uv_attributes(underhair_obj)
2183
+ assign_material(underhair_obj, mesh_material)
2184
+
2185
+ setup_underhair_modifiers(
2186
+ curves_obj=underhair_obj,
2187
+ mesh_obj=mesh_obj,
2188
+ mask_img=mask_img,
2189
+ trim_length=UNDERHAIR_LENGTH,
2190
+ )
2191
+
2192
+ log("Underhair object created successfully")
2193
+ return underhair_obj
2194
+
2195
+
2196
+ def get_child_hair_objects(surface_obj):
2197
+ out = []
2198
+ for obj in bpy.data.objects:
2199
+ if obj.parent == surface_obj and obj.type in {'CURVES', 'MESH'}:
2200
+ out.append(obj)
2201
+ return out
2202
+
2203
+
2204
+ def ensure_curve_bound_to_surface(curves_obj, surface_obj):
2205
+ if curves_obj.type != 'CURVES':
2206
+ return
2207
+ curves = curves_obj.data
2208
+ curves.surface = surface_obj
2209
+ if surface_obj.data.uv_layers.active is not None:
2210
+ try:
2211
+ curves.surface_uv_map = surface_obj.data.uv_layers.active.name
2212
+ except Exception:
2213
+ pass
2214
+ curves_obj.parent = surface_obj
2215
+ try:
2216
+ curves_obj.matrix_parent_inverse = surface_obj.matrix_world.inverted()
2217
+ except Exception:
2218
+ pass
2219
+
2220
+
2221
+ def add_or_rebind_surface_deform(mesh_hair_obj, surface_obj, modifier_name="SurfaceDeformToBody"):
2222
+ mod = mesh_hair_obj.modifiers.get(modifier_name)
2223
+ if mod is None:
2224
+ mod = mesh_hair_obj.modifiers.new(name=modifier_name, type='SURFACE_DEFORM')
2225
+
2226
+ mod.target = surface_obj
2227
+ mod.falloff = 4.0
2228
+
2229
+ try:
2230
+ bpy.ops.object.mode_set(mode='OBJECT')
2231
+ except Exception:
2232
+ pass
2233
+
2234
+ bpy.ops.object.select_all(action='DESELECT')
2235
+ mesh_hair_obj.select_set(True)
2236
+ bpy.context.view_layer.objects.active = mesh_hair_obj
2237
+
2238
+ try:
2239
+ bpy.ops.object.surfacedeform_bind(modifier=mod.name)
2240
+ log(f"Bound Surface Deform on '{mesh_hair_obj.name}' -> '{surface_obj.name}'")
2241
+ except Exception as e:
2242
+ log(f"[WARN] Failed to bind Surface Deform on '{mesh_hair_obj.name}': {e}")
2243
+
2244
+ return mod
2245
+
2246
+
2247
+ def apply_surface_deform_or_surface_bind_to_all_hair(surface_obj, hair_objects=None):
2248
+ if hair_objects is None:
2249
+ hair_objects = get_child_hair_objects(surface_obj)
2250
+
2251
+ for obj in hair_objects:
2252
+ if obj.type == 'CURVES':
2253
+ ensure_curve_bound_to_surface(obj, surface_obj)
2254
+ log(f"Rebound curves surface for '{obj.name}'")
2255
+ elif obj.type == 'MESH':
2256
+ add_or_rebind_surface_deform(obj, surface_obj)
2257
+
2258
+ bpy.context.view_layer.update()
2259
+ return hair_objects
2260
+
2261
+
2262
+ def refresh_hair_after_shape_change(surface_obj, hair_objects=None):
2263
+ if hair_objects is None:
2264
+ hair_objects = get_child_hair_objects(surface_obj)
2265
+
2266
+ for obj in hair_objects:
2267
+ if obj.type == 'CURVES':
2268
+ ensure_curve_bound_to_surface(obj, surface_obj)
2269
+
2270
+ for mod in obj.modifiers:
2271
+ try:
2272
+ mod.show_viewport = False
2273
+ mod.show_viewport = True
2274
+ except Exception:
2275
+ pass
2276
+
2277
+ obj.update_tag()
2278
+
2279
+ surface_obj.update_tag()
2280
+
2281
+ # Force a full depsgraph evaluation so all curves re-snap
2282
+ depsgraph = bpy.context.evaluated_depsgraph_get()
2283
+ depsgraph.update()
2284
+ bpy.context.view_layer.update()
2285
+
2286
+ log(f"Refreshed {len(hair_objects)} hair objects after shape change")
2287
+
2288
+
2289
+ def load_hair_scene(
2290
+ obj_path: str,
2291
+ mesh_object_name: str = "DeformedMesh",
2292
+ save_blend_path: str = None,
2293
+ render_filename: str = None,
2294
+ ):
2295
+ """Load mesh + hair without any deformation applied.
2296
+ Hair is built on the base (undeformed) mesh geometry.
2297
+ """
2298
+ t_start = time.perf_counter()
2299
+ paths = resolve_paths_from_obj(obj_path)
2300
+ scene = bpy.context.scene
2301
+
2302
+ delete_default_cube()
2303
+ setup_cycles_render(scene)
2304
+ log("Selecting random HDR...")
2305
+ hdr_path = pick_random_hdr_image(str(paths["hdr_dir"]))
2306
+
2307
+ log("Setting up world HDR...")
2308
+ setup_world_hdr(str(hdr_path))
2309
+
2310
+ log("Importing mesh...")
2311
+ mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name)
2312
+
2313
+ if not mesh_obj.data.uv_layers:
2314
+ raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.")
2315
+
2316
+ # # Set up camera after mesh is loaded so it can frame the object
2317
+ # ensure_camera(mesh_obj)
2318
+
2319
+ log("Resolving dataset texture...")
2320
+ raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"]))
2321
+ texture_path = remove_green_screen_from_image(
2322
+ src_image_path=str(raw_texture_path),
2323
+ out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"),
2324
+ green_threshold=0.45,
2325
+ green_margin=0.08,
2326
+ )
2327
+ log(f"Using processed texture: {texture_path}")
2328
+
2329
+ log("Creating mesh material...")
2330
+ mesh_mat = create_mesh_material(
2331
+ mesh_obj=mesh_obj,
2332
+ texture_path=str(texture_path),
2333
+ normal_path=str(paths["mesh_normal"]),
2334
+ roughness_path=str(paths["mesh_roughness"]),
2335
+ material_name=f"{mesh_object_name}_MeshMaterial",
2336
+ )
2337
+
2338
+ log("Creating hair material...")
2339
+ hair_mat = create_hair_material(
2340
+ texture_path=str(texture_path),
2341
+ material_name=f"{mesh_object_name}_HairMaterial",
2342
+ )
2343
+
2344
+ log("Creating underhair...")
2345
+ underhair_obj = create_underhair_if_available(
2346
+ mesh_obj=mesh_obj,
2347
+ mesh_material=mesh_mat,
2348
+ mask_image_path=str(UNDERHAIR_MASK_PATH),
2349
+ )
2350
+
2351
+ # Density and length maps are optional for this visualization pipeline.
2352
+ # Strand positions and lengths are reconstructed directly from the hair map.
2353
+ hair_info = {}
2354
+
2355
+ hair_map_path = str(paths["hair_map"])
2356
+ log(f"Loading UV-local 512 hair map: {hair_map_path}")
2357
+ log(f"Loading global hair meta: {paths['hair_meta']}")
2358
+ group_names, strands_by_group, samples = decode_hair_map(
2359
+ hair_map_path,
2360
+ str(paths["hair_meta"]),
2361
+ mesh_obj,
2362
+ )
2363
+ log(f" Samples per strand: {samples}")
2364
+
2365
+ created_objects = []
2366
+
2367
+ for group_name in group_names:
2368
+ if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS):
2369
+ log(f" [SKIP] Group '{group_name}' ignored by keyword")
2370
+ continue
2371
+
2372
+ strands = strands_by_group.get(group_name)
2373
+ if strands is None or strands.shape[0] == 0:
2374
+ log(f" [SKIP] Group '{group_name}' has 0 strands")
2375
+ continue
2376
+
2377
+ log(f" Processing group: {group_name} ({strands.shape[0]} strands)")
2378
+
2379
+ roots = strands[:, 0, :]
2380
+ root_uvs = compute_root_uvs(roots, mesh_obj)
2381
+
2382
+ curves_obj = build_curve_object_from_strands(
2383
+ sanitize_name(group_name),
2384
+ strands,
2385
+ root_uvs,
2386
+ mesh_obj,
2387
+ )
2388
+ if curves_obj is None:
2389
+ continue
2390
+
2391
+ assign_material(curves_obj, hair_mat)
2392
+
2393
+ log(f" Setting up modifiers for: {curves_obj.name}")
2394
+ setup_modifiers(curves_obj, group_name, mesh_obj, hair_info)
2395
+
2396
+ created_objects.append(curves_obj)
2397
+
2398
+ if underhair_obj is not None:
2399
+ created_objects.append(underhair_obj)
2400
+
2401
+ loaded_hair_map = str(paths["hair_map_curl_out"])
2402
+ log(f"Loaded hair map from: {loaded_hair_map}")
2403
+
2404
+ if save_blend_path:
2405
+ save_blend_path = str(Path(save_blend_path).resolve())
2406
+ bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
2407
+ log(f"Saved blend file: {save_blend_path}")
2408
+
2409
+ render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename)
2410
+
2411
+
2412
+ elapsed = time.perf_counter() - t_start
2413
+ log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s")
2414
+ for obj in created_objects:
2415
+ log(f" {obj.name}")
2416
+
2417
+ return mesh_obj, created_objects
2418
+
2419
+
2420
+ def apply_deformed_shape_key_to_loaded_scene(
2421
+ source_obj_path: str,
2422
+ mesh_obj,
2423
+ hair_objects,
2424
+ deformed_obj_path: str = None,
2425
+ shape_key_name: str = "DeformedShape",
2426
+ shape_key_value: float = 1.0,
2427
+ ):
2428
+ """Legacy shape-key approach. Hair may not follow correctly for curves
2429
+ objects unless the curves were built on the already-deformed mesh.
2430
+ Prefer load_hair_scene_with_deformed_shape() which deforms first.
2431
+ """
2432
+ deformed_path = resolve_corresponding_deformed_shape_path(
2433
+ source_obj_path,
2434
+ deformed_obj_path=deformed_obj_path,
2435
+ )
2436
+ log(f"Using deformed shape OBJ: {deformed_path}")
2437
+
2438
+ log("Applying surface deform / surface binding to all hair before shape key...")
2439
+ apply_surface_deform_or_surface_bind_to_all_hair(mesh_obj, hair_objects)
2440
+
2441
+ log("Creating shape key from deformed mesh...")
2442
+ sk = import_obj_as_shape_key(mesh_obj, str(deformed_path), shape_key_name)
2443
+ sk.value = float(shape_key_value)
2444
+
2445
+ log("Refreshing hair after shape key update...")
2446
+ refresh_hair_after_shape_change(mesh_obj, hair_objects)
2447
+
2448
+ return sk
2449
+
2450
+
2451
+ def load_hair_scene_with_deformed_shape(
2452
+ obj_path: str,
2453
+ mesh_object_name: str = "DeformedMesh",
2454
+ deformed_obj_path: str = None,
2455
+ shape_key_name: str = "DeformedShape",
2456
+ shape_key_value: float = 1.0,
2457
+ save_blend_path: str = None,
2458
+ use_shape_key: bool = False,
2459
+ render_filename: str = None,
2460
+ ):
2461
+ """Load mesh, apply deformation FIRST, then build all hair on the
2462
+ already-deformed geometry so that hair roots and strands match the
2463
+ deformed surface.
2464
+
2465
+ Args:
2466
+ use_shape_key: If True, use the legacy shape-key approach (hair is
2467
+ built on the base mesh then shape key is applied afterward).
2468
+ If False (default), the deformed vertex positions are written
2469
+ directly into the base mesh before hair is created, so hair
2470
+ is naturally placed on the deformed surface.
2471
+ """
2472
+ if use_shape_key:
2473
+ # --- Legacy path: build hair on base mesh, then apply shape key ---
2474
+ mesh_obj, created_objects = load_hair_scene(
2475
+ obj_path=obj_path,
2476
+ mesh_object_name=mesh_object_name,
2477
+ save_blend_path=None,
2478
+ render_filename=render_filename,
2479
+ )
2480
+
2481
+ sk = apply_deformed_shape_key_to_loaded_scene(
2482
+ source_obj_path=obj_path,
2483
+ mesh_obj=mesh_obj,
2484
+ hair_objects=created_objects,
2485
+ deformed_obj_path=deformed_obj_path,
2486
+ shape_key_name=shape_key_name,
2487
+ shape_key_value=shape_key_value,
2488
+ )
2489
+
2490
+ if save_blend_path:
2491
+ save_blend_path = str(Path(save_blend_path).resolve())
2492
+ bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
2493
+ log(f"Saved blend file: {save_blend_path}")
2494
+
2495
+ return mesh_obj, created_objects, sk
2496
+
2497
+ # --- New path: deform mesh first, then build hair on deformed geometry ---
2498
+ t_start = time.perf_counter()
2499
+ paths = resolve_paths_from_obj(obj_path)
2500
+ scene = bpy.context.scene
2501
+
2502
+ delete_default_cube()
2503
+ setup_cycles_render(scene)
2504
+ log("Selecting random HDR...")
2505
+ hdr_path = pick_random_hdr_image(str(paths["hdr_dir"]))
2506
+
2507
+ log("Setting up world HDR...")
2508
+ setup_world_hdr(str(hdr_path))
2509
+
2510
+ # Step 1: Import the base mesh
2511
+ log("Importing base mesh...")
2512
+ mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name)
2513
+
2514
+ if not mesh_obj.data.uv_layers:
2515
+ raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.")
2516
+
2517
+ # Step 2: Apply deformed vertex positions directly to the base mesh
2518
+ if deformed_obj_path:
2519
+ deformed_path = resolve_corresponding_deformed_shape_path(
2520
+ obj_path,
2521
+ deformed_obj_path=deformed_obj_path,
2522
+ )
2523
+ log(f"Applying deformed shape directly from: {deformed_path}")
2524
+ apply_deformed_shape_directly(mesh_obj, str(deformed_path))
2525
+ bpy.context.view_layer.update()
2526
+ else:
2527
+ log("No deformed OBJ supplied; using the original mesh geometry")
2528
+
2529
+ # # Set up camera after deformation so it frames the deformed mesh correctly
2530
+ # ensure_camera(mesh_obj)
2531
+
2532
+ # Step 3: Set up materials
2533
+ log("Resolving dataset texture...")
2534
+ raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"]))
2535
+ texture_path = remove_green_screen_from_image(
2536
+ src_image_path=str(raw_texture_path),
2537
+ out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"),
2538
+ green_threshold=0.45,
2539
+ green_margin=0.08,
2540
+ )
2541
+ log(f"Using processed texture: {texture_path}")
2542
+
2543
+ log("Creating mesh material...")
2544
+ mesh_mat = create_mesh_material(
2545
+ mesh_obj=mesh_obj,
2546
+ texture_path=str(texture_path),
2547
+ normal_path=str(paths["mesh_normal"]),
2548
+ roughness_path=str(paths["mesh_roughness"]),
2549
+ material_name=f"{mesh_object_name}_MeshMaterial",
2550
+ )
2551
+
2552
+ log("Creating hair material...")
2553
+ hair_mat = create_hair_material(
2554
+ texture_path=str(texture_path),
2555
+ material_name=f"{mesh_object_name}_HairMaterial",
2556
+ )
2557
+
2558
+ # Step 4: Create underhair (now on deformed mesh)
2559
+ log("Creating underhair on deformed mesh...")
2560
+ underhair_obj = create_underhair_if_available(
2561
+ mesh_obj=mesh_obj,
2562
+ mesh_material=mesh_mat,
2563
+ mask_image_path=str(UNDERHAIR_MASK_PATH),
2564
+ )
2565
+
2566
+ # Step 5: Load density/length maps
2567
+ # Density and length maps are optional for this visualization pipeline.
2568
+ # Strand positions and lengths are reconstructed directly from the hair map.
2569
+ hair_info = {}
2570
+
2571
+ # Step 6: Decode hair map (reconstructs strand positions on deformed geometry)
2572
+ hair_map_path = str(paths["hair_map"])
2573
+ log(f"Loading UV-local 512 hair map: {hair_map_path}")
2574
+ log(f"Loading global hair meta: {paths['hair_meta']}")
2575
+ group_names, strands_by_group, samples = decode_hair_map(
2576
+ hair_map_path,
2577
+ str(paths["hair_meta"]),
2578
+ mesh_obj,
2579
+ )
2580
+ log(f" Samples per strand: {samples}")
2581
+
2582
+ # Step 7: Build hair curve objects on deformed mesh
2583
+ created_objects = []
2584
+
2585
+ for group_name in group_names:
2586
+ if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS):
2587
+ log(f" [SKIP] Group '{group_name}' ignored by keyword")
2588
+ continue
2589
+
2590
+ strands = strands_by_group.get(group_name)
2591
+ if strands is None or strands.shape[0] == 0:
2592
+ log(f" [SKIP] Group '{group_name}' has 0 strands")
2593
+ continue
2594
+
2595
+ log(f" Processing group: {group_name} ({strands.shape[0]} strands)")
2596
+
2597
+ roots = strands[:, 0, :]
2598
+ root_uvs = compute_root_uvs(roots, mesh_obj)
2599
+
2600
+ curves_obj = build_curve_object_from_strands(
2601
+ sanitize_name(group_name),
2602
+ strands,
2603
+ root_uvs,
2604
+ mesh_obj,
2605
+ )
2606
+ if curves_obj is None:
2607
+ continue
2608
+
2609
+ assign_material(curves_obj, hair_mat)
2610
+
2611
+ log(f" Setting up modifiers for: {curves_obj.name}")
2612
+ setup_modifiers(curves_obj, group_name, mesh_obj, hair_info)
2613
+
2614
+ created_objects.append(curves_obj)
2615
+
2616
+ if underhair_obj is not None:
2617
+ created_objects.append(underhair_obj)
2618
+
2619
+ loaded_hair_map = str(paths["hair_map_curl_out"])
2620
+ log(f"Loaded hair map from: {loaded_hair_map}")
2621
+
2622
+ if save_blend_path:
2623
+ save_blend_path = str(Path(save_blend_path).resolve())
2624
+ bpy.ops.wm.save_as_mainfile(filepath=save_blend_path)
2625
+ log(f"Saved blend file: {save_blend_path}")
2626
+
2627
+ render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename)
2628
+ # TODO
2629
+ # render_and_save_image(str(render_output_path))
2630
+
2631
+ elapsed = time.perf_counter() - t_start
2632
+ log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s")
2633
+ for obj in created_objects:
2634
+ log(f" {obj.name}")
2635
+
2636
+ # No shape key was created in this path, return None for sk
2637
+ return mesh_obj, created_objects, None
2638
+
2639
+
2640
+ if __name__ == "__main__":
2641
+ argv = sys.argv
2642
+ user_args = argv[argv.index("--") + 1:] if "--" in argv else []
2643
+
2644
+ parser = argparse.ArgumentParser()
2645
+ parser.add_argument(
2646
+ "--obj_path",
2647
+ type=str,
2648
+ default=None,
2649
+ help=(
2650
+ "OBJ inside <root>/<species>/dataset/<group>/shapes. "
2651
+ "When omitted, a valid case is discovered automatically."
2652
+ ),
2653
+ )
2654
+ parser.add_argument("--species", type=str, default="small_cat")
2655
+ parser.add_argument(
2656
+ "--group_name",
2657
+ type=str,
2658
+ default="groupA_different_breeds_buoumao",
2659
+ )
2660
+ parser.add_argument("--sample_index", type=int, default=3)
2661
+ parser.add_argument("--mesh_object_name", type=str, default="DeformedMesh")
2662
+ parser.add_argument(
2663
+ "--deformed_obj_path",
2664
+ type=str,
2665
+ default=None,
2666
+ help="Optional deformed OBJ. The original mesh is used when omitted.",
2667
+ )
2668
+ parser.add_argument("--shape_key_name", type=str, default="DeformedShape")
2669
+ parser.add_argument("--shape_key_value", type=float, default=1.0)
2670
+ parser.add_argument("--save_blend_path", type=str, default=None)
2671
+ parser.add_argument("--render_filename", type=str, default=None)
2672
+ parser.add_argument(
2673
+ "--use_shape_key",
2674
+ action="store_true",
2675
+ default=False,
2676
+ help="Use legacy shape-key approach instead of direct vertex overwrite",
2677
+ )
2678
+ args = parser.parse_args(user_args)
2679
+
2680
+ if args.obj_path is None:
2681
+ discovered_obj, discovered_deformed = discover_dataset_case(
2682
+ root=ANIMALLIFT_ROOT,
2683
+ species=args.species,
2684
+ group_name=args.group_name,
2685
+ sample_index=args.sample_index,
2686
+ )
2687
+ args.obj_path = str(discovered_obj)
2688
+ if args.deformed_obj_path is None and discovered_deformed is not None:
2689
+ args.deformed_obj_path = str(discovered_deformed)
2690
+
2691
+ print(f"obj_path: {args.obj_path}")
2692
+ print(f"mesh_object_name: {args.mesh_object_name}")
2693
+ print(f"deformed_obj_path: {args.deformed_obj_path}")
2694
+ print(f"shape_key_name: {args.shape_key_name}")
2695
+ print(f"shape_key_value: {args.shape_key_value}")
2696
+ print(f"save_blend_path: {args.save_blend_path}")
2697
+ print(f"render_filename: {args.render_filename}")
2698
+ print(f"use_shape_key: {args.use_shape_key}")
2699
+
2700
+ load_hair_scene_with_deformed_shape(
2701
+ obj_path=args.obj_path,
2702
+ mesh_object_name=args.mesh_object_name,
2703
+ deformed_obj_path=args.deformed_obj_path,
2704
+ shape_key_name=args.shape_key_name,
2705
+ shape_key_value=args.shape_key_value,
2706
+ save_blend_path=args.save_blend_path,
2707
+ use_shape_key=args.use_shape_key,
2708
+ )