import bpy import json import math import re import numpy as np import bmesh from pathlib import Path from mathutils import Vector from mathutils.bvhtree import BVHTree from mathutils.geometry import barycentric_transform import random import time import sys import argparse IMAGE_PREFIX = "dens_" VGROUP_PREFIX = "len_" ANIMALLIFT_ROOT = Path("path/to/AnimalLift") REGIONS = [ "face", "ear", "neck", "body", "leg", "tail" ] CURVE_REGION_MAP = { "face_fur": "face", "ear_fur": "ear", "body_fur": "body", "leg_fur": "leg", "neck_fur": "neck", "neck": "neck", "mouse_fur": "face", "tail_fur": "tail", } IGNORE_NAME_KEYWORDS = ["undercoat"] MOUSE_LENGTH_VALUE = 0.05 BASE_PART_RESOLUTION = 512 SAMPLES_PER_STRAND = 32 ATLAS_TILE_PADDING = 0.02 IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".exr"} META_ROOT = ANIMALLIFT_ROOT / "meta" HDR_DIR = META_ROOT / "render_elements" / "hdr" HDR_IMAGE_EXTS = {".hdr", ".exr"} UNDERHAIR_MASK_PATH = META_ROOT / "used_version_obj" / "part_masks" / "merged.png" UNDERHAIR_LENGTH = 0.005 UNDERHAIR_INTERP_DENSITY = 500000.0 UNDERHAIR_MASK_GROUP = "underhair_mask" def log(msg: str): print(f"[hair-load] {msg}") def natural_key(path: Path): parts = re.split(r"(\d+)", path.stem.lower()) key = [] for p in parts: if p.isdigit(): key.append(int(p)) else: key.append(p) key.append(path.suffix.lower()) return key def is_hidden_or_metadata_name(name: str) -> bool: """Return True for hidden files and common macOS metadata entries.""" return ( not name or name.startswith(".") or name.startswith("._") or name in {".DS_Store", "Thumbs.db"} ) def is_usable_file(path: Path) -> bool: """Accept only real, visible files.""" path = Path(path) return path.is_file() and not is_hidden_or_metadata_name(path.name) def is_usable_directory(path: Path) -> bool: """Accept only real, visible directories.""" path = Path(path) return path.is_dir() and not is_hidden_or_metadata_name(path.name) def require_usable_file(path, description: str = "File") -> Path: """Resolve and validate an explicitly supplied file path.""" path = Path(path).expanduser().resolve() if not is_usable_file(path): raise FileNotFoundError( f"{description} is missing, hidden, or a macOS metadata file: {path}" ) return path # Backward-compatible alias used by older helper functions. is_usable_dataset_file = is_usable_file def pick_random_hdr_image(hdr_dir: str, rng_seed: int = None): hdr_dir = Path(hdr_dir).resolve() if not is_usable_directory(hdr_dir): raise FileNotFoundError( f"HDR directory is missing or hidden: {hdr_dir}" ) hdr_files = sorted( [ path for path in hdr_dir.iterdir() if is_usable_file(path) and path.suffix.lower() in HDR_IMAGE_EXTS ], key=natural_key, ) rejected = sorted( [ path.name for path in hdr_dir.iterdir() if path.suffix.lower() in HDR_IMAGE_EXTS and not is_usable_file(path) ] ) if rejected: log(f"Ignored hidden HDR metadata files: {rejected}") if not hdr_files: raise FileNotFoundError( f"No usable HDR/EXR files found in: {hdr_dir}" ) rng = random.Random(rng_seed) chosen = rng.choice(hdr_files) log(f"Randomly selected HDR: {chosen.name}") return chosen def list_hair_files(hair_dir: Path): """Prefer .pt files exactly as the training dataset does.""" pt_files = sorted( [p for p in hair_dir.glob("*.pt") if is_usable_file(p)], key=natural_key, ) if pt_files: return pt_files return sorted( [p for p in hair_dir.glob("*.npz") if is_usable_file(p)], key=natural_key, ) def select_hair_map_for_obj(obj_path: Path, dataset_dir: Path): """ Match the training dataset's auxiliary-file rule. - Prefer hair_maps_single_512_uvlocal. - Prefer .pt over .npz. - If there is one hair file, reuse it for every shape. - Otherwise pair hair and shape files by natural-sort index. """ hair_dir_candidates = [ dataset_dir / "hair_maps_single_512_uvlocal", dataset_dir / "hair_maps_curl", dataset_dir / "hair_maps", ] shapes_dir = dataset_dir / "shapes" shape_files = sorted( [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)], key=natural_key, ) try: shape_index = next( index for index, path in enumerate(shape_files) if path.resolve() == obj_path.resolve() ) except StopIteration as exc: raise FileNotFoundError( f"OBJ file is not present in the dataset shapes directory: {obj_path}" ) from exc checked = [] for hair_dir in hair_dir_candidates: checked.append(str(hair_dir)) hair_files = list_hair_files(hair_dir) if not hair_files: continue same_stem = [ path for path in hair_files if path.stem == obj_path.stem ] if same_stem: return same_stem[0] if len(hair_files) == 1: return hair_files[0] if shape_index < len(hair_files): return hair_files[shape_index] raise IndexError( f"Hair index out of range for {obj_path.name}: " f"shapes={len(shape_files)}, hair_files={len(hair_files)}, " f"shape_index={shape_index}, hair_dir={hair_dir}" ) raise FileNotFoundError( "Could not find a compatible .pt or .npz hair map in:\n " + "\n ".join(checked) ) def resolve_paths_from_obj(obj_path: str): obj_path = Path(obj_path).expanduser().resolve() if not is_usable_file(obj_path): raise FileNotFoundError( f"OBJ file is missing or is a hidden/macOS metadata file: {obj_path}" ) if obj_path.parent.name != "shapes": raise ValueError( "Expected an OBJ inside a dataset group 'shapes' directory, for example:\n" " /path/to/animallift/cat/dataset//shapes/.obj" ) dataset_dir = obj_path.parent.parent hair_map_path = select_hair_map_for_obj(obj_path, dataset_dir) return { "dataset_dir": dataset_dir, "datasets_root": dataset_dir.parent, "sample_name": obj_path.stem, "textures_dir": dataset_dir / "textures", "hair_map": hair_map_path, "hair_meta": META_ROOT / "hair_map_meta_uvanchor.npz", "hair_map_curl_out": hair_map_path, "mesh_normal": META_ROOT / "render_elements" / "Normal.png", "mesh_roughness": META_ROOT / "render_elements" / "Roughness.png", "hdr_dir": HDR_DIR, } def discover_dataset_case( root: Path, species: str = "cat", group_name: str = None, sample_index: int = 0, ): """ Discover a real case from: //dataset//shapes/*.obj The group must also contain textures and a compatible hair-map directory. """ root = Path(root).expanduser().resolve() species_root = root / species / "dataset" if not species_root.is_dir(): raise FileNotFoundError(f"Species dataset directory not found: {species_root}") if group_name: explicit_group = species_root / group_name if not is_usable_directory(explicit_group): raise FileNotFoundError( f"Requested dataset group not found: {explicit_group}" ) group_dirs = [explicit_group] else: group_dirs = sorted( [ path for path in species_root.iterdir() if is_usable_directory(path) ], key=natural_key, ) failures = [] for group_dir in group_dirs: shapes_dir = group_dir / "shapes" textures_dir = group_dir / "textures" if not shapes_dir.is_dir() or not textures_dir.is_dir(): failures.append(f"{group_dir}: missing shapes or textures") continue shape_files = sorted( [p for p in shapes_dir.glob("*.obj") if is_usable_file(p)], key=natural_key, ) texture_files = sorted( [ p for p in textures_dir.iterdir() if is_usable_file(p) and p.suffix.lower() in IMAGE_EXTS ], key=natural_key, ) if not shape_files or not texture_files: failures.append(f"{group_dir}: empty shapes or textures") continue usable_count = min(len(shape_files), len(texture_files)) if sample_index < 0 or sample_index >= usable_count: failures.append( f"{group_dir}: sample_index={sample_index} outside 0..{usable_count - 1}" ) continue obj_path = shape_files[sample_index] try: hair_path = select_hair_map_for_obj(obj_path, group_dir) except Exception as exc: failures.append(f"{group_dir}: {exc}") continue deformed_candidate = group_dir / "deformed_shapes" / obj_path.name deformed_path = ( deformed_candidate if is_usable_file(deformed_candidate) else None ) log(f"Using dataset group: {group_dir.name}") log(f"Selected OBJ: {obj_path.name}") log(f"Selected hair map: {hair_path.name}") if deformed_path is None: log("No matching deformed shape found; using the original mesh") else: log(f"Selected deformed shape: {deformed_path.name}") return obj_path, deformed_path detail = "\n".join(f" - {item}" for item in failures[:20]) raise RuntimeError( f"No usable visualization case found under {species_root}.\n{detail}" ) def load_global_hair_meta(meta_path: str): meta_path = require_usable_file( meta_path, "Global hair metadata", ) data = np.load(str(meta_path), allow_pickle=True) required_keys = [ "group_names", "guide_group_id_map", "uv_face_index_map", "uv_bary_map", ] for key in required_keys: if key not in data: raise KeyError(f"Missing key '{key}' in global hair meta: {meta_path}") group_names = [str(n) for n in data["group_names"]] guide_group_id_map = data["guide_group_id_map"].astype(np.int32) uv_face_index_map = data["uv_face_index_map"].astype(np.int32) uv_bary_map = data["uv_bary_map"].astype(np.float32) log(f"Loaded global hair meta: {meta_path}") log(f" Groups: {group_names}") log(f" guide_group_id_map shape: {guide_group_id_map.shape}") log(f" uv_face_index_map shape: {uv_face_index_map.shape}") log(f" uv_bary_map shape: {uv_bary_map.shape}") return group_names, guide_group_id_map, uv_face_index_map, uv_bary_map def import_obj_as_mesh(obj_path: str, object_name: str = None): obj_path = str(require_usable_file(obj_path, "OBJ file")) bpy.ops.object.select_all(action='DESELECT') if hasattr(bpy.ops.wm, "obj_import"): bpy.ops.wm.obj_import(filepath=obj_path) else: bpy.ops.import_scene.obj(filepath=obj_path) imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH'] if not imported_meshes: raise Exception(f"No mesh imported from {obj_path}") mesh_obj = imported_meshes[0] if object_name: mesh_obj.name = object_name mesh_obj.data.name = object_name bpy.ops.object.select_all(action='DESELECT') mesh_obj.select_set(True) bpy.context.view_layer.objects.active = mesh_obj bpy.ops.object.shade_smooth() log(f"Imported mesh: {mesh_obj.name} ({len(mesh_obj.data.vertices)} verts, smooth shading)") return mesh_obj def apply_deformed_shape_directly(mesh_obj, deformed_obj_path: str): """Overwrite base mesh vertex positions with deformed OBJ vertex positions. This avoids shape keys entirely so the base mesh IS the deformed shape, and all curves bound to its surface will follow naturally. """ deformed_obj_path = str( require_usable_file(deformed_obj_path, "Deformed OBJ file") ) bpy.ops.object.select_all(action='DESELECT') if hasattr(bpy.ops.wm, "obj_import"): bpy.ops.wm.obj_import(filepath=deformed_obj_path) else: bpy.ops.import_scene.obj(filepath=deformed_obj_path) imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH'] if not imported_meshes: raise Exception(f"No mesh imported from {deformed_obj_path}") imported = imported_meshes[0] if len(mesh_obj.data.vertices) != len(imported.data.vertices): bpy.data.objects.remove(imported, do_unlink=True) raise Exception( f"Vertex count mismatch! Target: {len(mesh_obj.data.vertices)}, " f"Imported: {len(imported.data.vertices)}" ) for i, v in enumerate(imported.data.vertices): mesh_obj.data.vertices[i].co = v.co bpy.data.objects.remove(imported, do_unlink=True) mesh_obj.data.update() log(f"Applied deformed shape directly to '{mesh_obj.name}' from {deformed_obj_path}") def import_obj_as_shape_key(target, obj_path: str, shape_key_name: str): obj_path = str(require_usable_file(obj_path, "Shape-key OBJ file")) bpy.ops.object.select_all(action='DESELECT') if hasattr(bpy.ops.wm, "obj_import"): bpy.ops.wm.obj_import(filepath=obj_path) else: bpy.ops.import_scene.obj(filepath=obj_path) imported_meshes = [o for o in bpy.context.selected_objects if o.type == 'MESH'] if not imported_meshes: raise Exception(f"No imported mesh found from {obj_path}") imported = imported_meshes[0] try: if len(target.data.vertices) != len(imported.data.vertices): raise Exception( f"Vertex count mismatch! Target: {len(target.data.vertices)}, " f"Imported: {len(imported.data.vertices)}" ) if not target.data.shape_keys: target.shape_key_add(name="Basis") old = target.data.shape_keys.key_blocks.get(shape_key_name) if old is not None: bpy.context.view_layer.objects.active = target target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(old) bpy.ops.object.shape_key_remove(all=False) sk = target.shape_key_add(name=shape_key_name, from_mix=False) for i, v in enumerate(imported.data.vertices): sk.data[i].co = v.co sk.value = 1.0 target.active_shape_key_index = list(target.data.shape_keys.key_blocks).index(sk) log(f"Shape key created and enabled: {shape_key_name}") return sk finally: bpy.data.objects.remove(imported, do_unlink=True) def resolve_corresponding_deformed_shape_path(source_obj_path: str, deformed_obj_path: str = None): if deformed_obj_path is not None: p = Path(deformed_obj_path).resolve() else: source_obj_path = Path(source_obj_path).resolve() dataset_dir = source_obj_path.parent.parent p = dataset_dir / "deformed_shapes" / source_obj_path.name if not is_usable_file(p): raise FileNotFoundError( f"Deformed shape OBJ is missing or hidden: {p}" ) return p def open_image_simple(image_path: str, non_color: bool = True): image_path = str(require_usable_file(image_path, "Image file")) img = bpy.data.images.load(filepath=image_path, check_existing=True) img.colorspace_settings.name = 'Non-Color' if non_color else 'sRGB' img.pixels[:] return img def open_image_color(image_path: str): return open_image_simple(image_path, non_color=False) def is_green_rgb(rgb, green_threshold=0.45, green_margin=0.08): r, g, b = float(rgb[0]), float(rgb[1]), float(rgb[2]) return ( g >= green_threshold and g > r + green_margin and g > b + green_margin ) def remove_green_screen_from_image( src_image_path: str, out_image_path: str = None, green_threshold: float = 0.45, green_margin: float = 0.08, rng_seed: int = None, ): """ Replace green pixels with randomly sampled non-green colors from the same image. Returns the output image path. """ src_image_path = require_usable_file( src_image_path, "Texture image", ) img = bpy.data.images.load(filepath=str(src_image_path), check_existing=False) width, height = img.size pixel_count = width * height * 4 pixels = np.empty(pixel_count, dtype=np.float32) img.pixels.foreach_get(pixels) pixels = pixels.reshape((height, width, 4)) rgb = pixels[:, :, :3] alpha = pixels[:, :, 3:4] green_mask = ( (rgb[:, :, 1] >= green_threshold) & (rgb[:, :, 1] > rgb[:, :, 0] + green_margin) & (rgb[:, :, 1] > rgb[:, :, 2] + green_margin) ) non_green_coords = np.argwhere(~green_mask) green_coords = np.argwhere(green_mask) if len(green_coords) == 0: log(f"No green pixels detected in texture: {src_image_path.name}") return src_image_path if len(non_green_coords) == 0: log(f"[WARN] Texture has no non-green pixels to sample from: {src_image_path.name}") return src_image_path rng = np.random.default_rng(rng_seed) sampled_ids = rng.integers(0, len(non_green_coords), size=len(green_coords)) sampled_coords = non_green_coords[sampled_ids] replacement_colors = rgb[sampled_coords[:, 0], sampled_coords[:, 1]] rgb[green_coords[:, 0], green_coords[:, 1]] = replacement_colors out_pixels = np.concatenate([rgb, alpha], axis=2).astype(np.float32).reshape(-1) if out_image_path is None: out_image_path = src_image_path.parent / f"{src_image_path.stem}_nogreen.png" else: out_image_path = Path(out_image_path).resolve() out_image_path.parent.mkdir(parents=True, exist_ok=True) out_img = bpy.data.images.new( name=f"{src_image_path.stem}_nogreen", width=width, height=height, alpha=True, float_buffer=False, ) out_img.colorspace_settings.name = 'sRGB' out_img.filepath_raw = str(out_image_path) out_img.file_format = 'PNG' out_img.pixels.foreach_set(out_pixels.tolist()) out_img.save() try: bpy.data.images.remove(img) except Exception: pass log(f"Saved green-removed texture: {out_image_path}") return out_image_path def resolve_render_output_path(obj_path: str, render_filename: str = None): obj_path = Path(obj_path).resolve() dataset_dir = obj_path.parent.parent render_dir = dataset_dir / "render_images" render_dir.mkdir(parents=True, exist_ok=True) if render_filename is None: render_filename = f"{obj_path.stem}.png" return render_dir / render_filename def render_and_save_image(output_path: str): output_path = Path(output_path).resolve() output_path.parent.mkdir(parents=True, exist_ok=True) scene = bpy.context.scene scene.render.image_settings.file_format = 'PNG' scene.render.image_settings.color_mode = 'RGBA' scene.render.filepath = str(output_path) bpy.ops.render.render(write_still=True) log(f"Saved render image: {output_path}") def load_density_images(mesh_obj, density_dir: str): density_images = {} for region in REGIONS: image_path = Path(density_dir) / f"{region}.png" if not is_usable_file(image_path): log(f" [WARN] Density image not found: {image_path}") continue img = open_image_simple(str(image_path), non_color=True) img.name = f"{IMAGE_PREFIX}{region}_{mesh_obj.name}" density_images[region] = img return density_images def create_vertex_group_from_image(obj, image_path: str, group_name: str, scale: float = 1.0): mesh = obj.data if not mesh.uv_layers: raise Exception("Target mesh has no UVs") img = open_image_simple(image_path, non_color=True) width, height = img.size pixel_count = width * height * 4 pixels_np = np.empty(pixel_count, dtype=np.float32) img.pixels.foreach_get(pixels_np) pixels_np = pixels_np.reshape((height, width, 4)) lum = ( 0.2126 * pixels_np[:, :, 0] + 0.7152 * pixels_np[:, :, 1] + 0.0722 * pixels_np[:, :, 2] ) total_loops = len(mesh.loops) loop_uvs = np.empty(total_loops * 2, dtype=np.float32) mesh.uv_layers.active.data.foreach_get("uv", loop_uvs) loop_uvs = loop_uvs.reshape((total_loops, 2)) loop_verts = np.empty(total_loops, dtype=np.int32) mesh.loops.foreach_get("vertex_index", loop_verts) u = np.clip(loop_uvs[:, 0], 0.0, 1.0) v = np.clip(loop_uvs[:, 1], 0.0, 1.0) xi = (u * (width - 1)).astype(np.int32) yi = (v * (height - 1)).astype(np.int32) loop_weights = lum[yi, xi] * float(scale) num_verts = len(mesh.vertices) weight_sum = np.zeros(num_verts, dtype=np.float64) weight_cnt = np.zeros(num_verts, dtype=np.int32) np.add.at(weight_sum, loop_verts, loop_weights) np.add.at(weight_cnt, loop_verts, 1) mask = weight_cnt > 0 avg_weights = np.zeros(num_verts, dtype=np.float64) avg_weights[mask] = weight_sum[mask] / weight_cnt[mask] old_vg = obj.vertex_groups.get(group_name) if old_vg is not None: obj.vertex_groups.remove(old_vg) vg = obj.vertex_groups.new(name=group_name) indices = np.where(mask)[0] for vid in indices: vg.add([int(vid)], float(avg_weights[vid]), 'REPLACE') return vg, img def load_hair_info(json_path): json_path = Path(json_path).resolve() if not is_usable_file(json_path): raise FileNotFoundError( f"hair_info.json is missing or hidden: {json_path}" ) with open(json_path, "r", encoding="utf-8") as f: return json.load(f) def get_region_length_scale(hair_info: dict, region: str) -> float: params = hair_info.get("resolved_hair_params", {}) if region not in params: raise KeyError(f"Region '{region}' not found in resolved_hair_params") return float(params[region]["length"]) def create_length_vertex_groups(mesh_obj, length_dir: str, hair_info: dict): for region in REGIONS: image_path = Path(length_dir) / f"{region}.png" if not is_usable_file(image_path): log(f" [WARN] Length image not found: {image_path}") continue vg_name = f"{VGROUP_PREFIX}{region}" scale = get_region_length_scale(hair_info, region) vg, img = create_vertex_group_from_image(mesh_obj, str(image_path), vg_name, scale=scale) img.name = f"lenimg_{region}_{mesh_obj.name}" log(f" Created vertex group: {vg.name}, scale={scale:.4f}") def ensure_triangulated_bmesh(mesh): bm = bmesh.new() bm.from_mesh(mesh) bmesh.ops.triangulate(bm, faces=bm.faces[:]) bm.faces.ensure_lookup_table() bm.verts.ensure_lookup_table() return bm def get_evaluated_mesh(mesh_obj): """Return the evaluated (deformed) mesh data, accounting for shape keys and modifiers. Caller must call eval_obj.to_mesh_clear() when done if needed. """ depsgraph = bpy.context.evaluated_depsgraph_get() eval_obj = mesh_obj.evaluated_get(depsgraph) eval_mesh = eval_obj.to_mesh() return eval_obj, eval_mesh def compute_root_uvs(roots, mesh_obj): mesh = mesh_obj.data if not mesh.uv_layers.active: raise RuntimeError("Mesh has no active UV layer") # Use evaluated mesh so roots snap to deformed positions eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj) bm = bmesh.new() bm.from_mesh(eval_mesh) bmesh.ops.triangulate(bm, faces=bm.faces[:]) bm.faces.ensure_lookup_table() bm.verts.ensure_lookup_table() # UV layer name comes from the original mesh uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name) if uv_layer is None: bm.free() eval_obj.to_mesh_clear() raise RuntimeError("Could not access active UV layer") bvh = BVHTree.FromBMesh(bm) uvs = [] for root in roots: hit = bvh.find_nearest(Vector(root)) if hit is None or hit[2] is None: uvs.append((0.5, 0.5)) continue location, normal, face_index, dist = hit face = bm.faces[face_index] if len(face.verts) != 3: uvs.append((0.5, 0.5)) continue v0, v1, v2 = [f.co for f in face.verts] uv0 = face.loops[0][uv_layer].uv uv1 = face.loops[1][uv_layer].uv uv2 = face.loops[2][uv_layer].uv uv = barycentric_transform( location, v0, v1, v2, uv0.to_3d(), uv1.to_3d(), uv2.to_3d() ) uvs.append((float(uv.x), float(uv.y))) bm.free() eval_obj.to_mesh_clear() return uvs def build_face_geom(mesh_obj): """Build triangle face geometry from the evaluated (deformed) mesh.""" mesh = mesh_obj.data if not mesh.uv_layers.active: raise RuntimeError("Mesh has no active UV layer") # Use evaluated mesh to pick up shape key / modifier deformations eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj) bm = bmesh.new() bm.from_mesh(eval_mesh) bmesh.ops.triangulate(bm, faces=bm.faces[:]) bm.faces.ensure_lookup_table() bm.verts.ensure_lookup_table() uv_layer = bm.loops.layers.uv.get(mesh.uv_layers.active.name) if uv_layer is None: bm.free() eval_obj.to_mesh_clear() raise RuntimeError("Could not access active UV layer") num_faces = len(bm.faces) face_pos = np.empty((num_faces, 3, 3), dtype=np.float32) face_uvs = np.empty((num_faces, 3, 2), dtype=np.float32) for fi, face in enumerate(bm.faces): for vi in range(3): co = face.verts[vi].co uv = face.loops[vi][uv_layer].uv face_pos[fi, vi] = (co.x, co.y, co.z) face_uvs[fi, vi] = (uv.x, uv.y) bm.free() eval_obj.to_mesh_clear() return face_pos, face_uvs def reconstruct_surface_points_and_frames(mesh_obj, uv_face_index_map, uv_bary_map): face_pos, face_uvs = build_face_geom(mesh_obj) height, width = uv_face_index_map.shape roots = np.zeros((height, width, 3), dtype=np.float32) Tu = np.zeros((height, width, 3), dtype=np.float32) Tv = np.zeros((height, width, 3), dtype=np.float32) N = np.zeros((height, width, 3), dtype=np.float32) ys, xs = np.where(uv_face_index_map >= 0) fids = uv_face_index_map[ys, xs].astype(np.int32) bary = uv_bary_map[ys, xs].astype(np.float32) p0 = face_pos[fids, 0] p1 = face_pos[fids, 1] p2 = face_pos[fids, 2] uv0 = face_uvs[fids, 0] uv1 = face_uvs[fids, 1] uv2 = face_uvs[fids, 2] roots_pts = ( bary[:, 0:1] * p0 + bary[:, 1:2] * p1 + bary[:, 2:3] * p2 ) dp1 = p1 - p0 dp2 = p2 - p0 duv1 = uv1 - uv0 duv2 = uv2 - uv0 det = duv1[:, 0] * duv2[:, 1] - duv1[:, 1] * duv2[:, 0] safe = np.abs(det) > 1e-12 det_safe = det.copy() det_safe[~safe] = 1.0 Tu_pts = np.empty_like(dp1) Tv_pts = np.empty_like(dp1) Tu_pts[:, 0] = (dp1[:, 0] * duv2[:, 1] - dp2[:, 0] * duv1[:, 1]) / det_safe Tu_pts[:, 1] = (dp1[:, 1] * duv2[:, 1] - dp2[:, 1] * duv1[:, 1]) / det_safe Tu_pts[:, 2] = (dp1[:, 2] * duv2[:, 1] - dp2[:, 2] * duv1[:, 1]) / det_safe Tv_pts[:, 0] = (-dp1[:, 0] * duv2[:, 0] + dp2[:, 0] * duv1[:, 0]) / det_safe Tv_pts[:, 1] = (-dp1[:, 1] * duv2[:, 0] + dp2[:, 1] * duv1[:, 0]) / det_safe Tv_pts[:, 2] = (-dp1[:, 2] * duv2[:, 0] + dp2[:, 2] * duv1[:, 0]) / det_safe N_pts = np.cross(dp1, dp2) def normalize(v): lens = np.linalg.norm(v, axis=1, keepdims=True) lens[lens < 1e-12] = 1.0 return v / lens Tu_pts = normalize(Tu_pts) Tv_pts = normalize(Tv_pts) N_pts = normalize(N_pts) if np.any(~safe): Tu_pts[~safe] = normalize(dp1[~safe]) Tv_pts[~safe] = normalize(np.cross(N_pts[~safe], Tu_pts[~safe])) N_pts[~safe] = normalize(np.cross(Tu_pts[~safe], Tv_pts[~safe])) roots[ys, xs] = roots_pts Tu[ys, xs] = Tu_pts Tv[ys, xs] = Tv_pts N[ys, xs] = N_pts return roots, Tu, Tv, N def load_quantized_hair_map(hair_map_path: str): """ Load either the uploaded .pt cache format or the legacy .npz format. Returns: hair_q: [H, W, S-1, 3] float32 scale: [3] float32 samples: S hair_mask: [H, W] bool """ path = require_usable_file(hair_map_path, "Hair map") suffix = path.suffix.lower() if suffix == ".pt": try: import torch except ImportError as exc: raise ImportError( "Reading uploaded .pt hair maps requires PyTorch in Blender's " "Python environment. Install torch for the Blender Python version." ) from exc data = torch.load(str(path), map_location="cpu") required = ["hair_q", "scale", "hair_mask"] missing = [key for key in required if key not in data] if missing: raise KeyError(f"Missing keys {missing} in PT hair map: {path}") hair_q = data["hair_q"].detach().cpu().numpy().astype(np.float32) scale = data["scale"].detach().cpu().numpy().astype(np.float32) hair_mask = data["hair_mask"].detach().cpu().numpy().astype(bool) samples = int(hair_q.shape[2]) + 1 return hair_q, scale, samples, hair_mask if suffix == ".npz": data = np.load(str(path), allow_pickle=True) required = ["hair_offsets_local_q", "offset_scale"] missing = [key for key in required if key not in data] if missing: raise KeyError(f"Missing keys {missing} in NPZ hair map: {path}") hair_q = data["hair_offsets_local_q"].astype(np.float32) scale = data["offset_scale"].astype(np.float32) samples = ( int(data["samples"]) if "samples" in data else int(hair_q.shape[2]) + 1 ) hair_mask = np.abs(hair_q).sum(axis=(2, 3)) > 0 return hair_q, scale, samples, hair_mask raise ValueError(f"Unsupported hair map extension: {path.suffix}") def decode_hair_map(hair_map_path: str, meta_path: str, mesh_obj): hair_offsets_local_q, offset_scale, samples, hair_mask = ( load_quantized_hair_map(hair_map_path) ) group_names, guide_group_id_map, uv_face_index_map, uv_bary_map = ( load_global_hair_meta(meta_path) ) if samples < 1: raise ValueError(f"Invalid samples={samples} in hair map") height, width = guide_group_id_map.shape[:2] if hair_offsets_local_q.shape[:2] != (height, width): raise ValueError( "Shape mismatch between hair map and global metadata: " f"{hair_offsets_local_q.shape[:2]} vs {(height, width)}" ) if hair_mask.shape[:2] != (height, width): raise ValueError( f"Hair mask shape mismatch: {hair_mask.shape[:2]} vs {(height, width)}" ) if uv_face_index_map.shape[:2] != (height, width): raise ValueError( f"UV face map shape mismatch: {uv_face_index_map.shape[:2]} " f"vs {(height, width)}" ) if uv_bary_map.shape[:2] != (height, width): raise ValueError( f"UV barycentric map shape mismatch: {uv_bary_map.shape[:2]} " f"vs {(height, width)}" ) offsets_local = ( hair_offsets_local_q / 127.0 ) * offset_scale.reshape(1, 1, 1, 3) strands_by_group = {name: [] for name in group_names} roots_map, Tu_map, Tv_map, N_map = reconstruct_surface_points_and_frames( mesh_obj, uv_face_index_map, uv_bary_map, ) valid_map = ( (guide_group_id_map >= 0) & hair_mask & (uv_face_index_map >= 0) ) ys, xs = np.where(valid_map) gids = guide_group_id_map[ys, xs].astype(np.int32) for y, x, gid in zip(ys, xs, gids): gid = int(gid) if gid < 0 or gid >= len(group_names): continue root = roots_map[y, x] Tu = Tu_map[y, x] Tv = Tv_map[y, x] normal = N_map[y, x] local = offsets_local[y, x] world_offsets = ( local[:, 0:1] * Tu[None, :] + local[:, 1:2] * Tv[None, :] + local[:, 2:3] * normal[None, :] ) strand = np.empty((samples, 3), dtype=np.float32) strand[0] = root if samples > 1: strand[1:] = root[None, :] + world_offsets strands_by_group[group_names[gid]].append(strand) for group_name, strands in list(strands_by_group.items()): if strands: strands_by_group[group_name] = np.stack(strands, axis=0) else: strands_by_group[group_name] = np.zeros( (0, samples, 3), dtype=np.float32, ) total_strands = sum(value.shape[0] for value in strands_by_group.values()) log(f"Decoded hair map: {hair_map_path}") log(f" Samples per strand: {samples}") log(f" Total guide strands: {total_strands}") return group_names, strands_by_group, samples def sanitize_name(name): out = [] for ch in str(name): if ch.isalnum() or ch in "._-": out.append(ch) else: out.append("_") s = "".join(out).strip("_") return s if s else "HairPart" def build_curve_object_from_strands(obj_name, strands, root_uvs, mesh_obj): if len(strands) == 0: return None curve_data = bpy.data.curves.new(obj_name, type='CURVE') curve_data.dimensions = '3D' curve_obj = bpy.data.objects.new(obj_name, curve_data) bpy.context.collection.objects.link(curve_obj) curve_obj.parent = mesh_obj curve_obj.location = (0, 0, 0) curve_obj.rotation_euler = (0, 0, 0) curve_obj.scale = (1, 1, 1) for strand in strands: spline = curve_data.splines.new('POLY') spline.points.add(len(strand) - 1) for i, p in enumerate(strand): spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0) if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.select_all(action='DESELECT') curve_obj.select_set(True) bpy.context.view_layer.objects.active = curve_obj bpy.ops.object.convert(target='CURVES') curve_obj = bpy.context.view_layer.objects.active curves = curve_obj.data curves.surface = mesh_obj curves.surface_uv_map = mesh_obj.data.uv_layers.active.name if "surface_uv_coordinate" in curves.attributes: uv_attr = curves.attributes["surface_uv_coordinate"] else: uv_attr = curves.attributes.new( name="surface_uv_coordinate", type='FLOAT2', domain='CURVE' ) for i in range(len(root_uvs)): uv_attr.data[i].vector = (float(root_uvs[i][0]), float(root_uvs[i][1])) log(f" Created '{curve_obj.name}' with {len(strands)} guide strands") return curve_obj def build_curve_object_from_strands_no_uv(obj_name, strands, mesh_obj): if len(strands) == 0: return None curve_data = bpy.data.curves.new(obj_name, type='CURVE') curve_data.dimensions = '3D' curve_obj = bpy.data.objects.new(obj_name, curve_data) bpy.context.collection.objects.link(curve_obj) curve_obj.matrix_world = mesh_obj.matrix_world.copy() for strand in strands: spline = curve_data.splines.new('POLY') spline.points.add(len(strand) - 1) for i, p in enumerate(strand): spline.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0) if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.select_all(action='DESELECT') curve_obj.select_set(True) bpy.context.view_layer.objects.active = curve_obj bpy.ops.object.convert(target='CURVES') curve_obj = bpy.context.view_layer.objects.active curve_obj.matrix_world = mesh_obj.matrix_world.copy() curve_obj.parent = mesh_obj curve_obj.matrix_parent_inverse = mesh_obj.matrix_world.inverted() curves = curve_obj.data curves.surface = mesh_obj log(f" Created '{curve_obj.name}' with {len(strands)} guide strands (no UV attr)") return curve_obj def describe_node_group_inputs(mod): if getattr(mod, "node_group", None) is None: return [] items = [] try: for item in mod.node_group.interface.items_tree: if getattr(item, "in_out", None) == 'INPUT': items.append((item.name, item.identifier, getattr(item, "socket_type", ""))) except Exception: pass return items def get_node_input_identifier_by_name(mod, display_name): for name, identifier, socket_type in describe_node_group_inputs(mod): if name == display_name: return identifier return None def set_gn_input(mod, display_name, value): identifier = get_node_input_identifier_by_name(mod, display_name) if identifier is None: log(f" [WARN] GN input '{display_name}' not found on '{mod.name}'") return False try: mod[identifier] = value return True except Exception as e: log(f" [WARN] Failed to set '{display_name}' on '{mod.name}': {e}") return False def find_gn_input_identifier_contains(mod, keywords): keywords = [k.lower() for k in keywords] for name, identifier, socket_type in describe_node_group_inputs(mod): lname = (name or "").lower() if all(k in lname for k in keywords): return identifier, name return None, None def set_gn_input_by_keywords(mod, keywords, value): identifier, display_name = find_gn_input_identifier_contains(mod, keywords) if identifier is None: log(f" [WARN] No GN input matching keywords {keywords} on '{mod.name}'") return False try: mod[identifier] = value log(f" + {mod.name} '{display_name}' = {value}") return True except Exception as e: log(f" [WARN] Failed setting '{display_name}' on '{mod.name}': {e}") return False def debug_modifier_inputs(mod): log(f"--- Modifier inputs for {mod.name} ---") for name, identifier, socket_type in describe_node_group_inputs(mod): log(f" name='{name}' identifier='{identifier}' socket_type='{socket_type}'") def select_and_activate(obj): bpy.ops.object.select_all(action='DESELECT') obj.select_set(True) bpy.context.view_layer.objects.active = obj def get_essentials_blend_path(): candidates = [] try: local_root = Path(bpy.utils.resource_path('LOCAL')) candidates.append(local_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend") except Exception: pass try: system_root = Path(bpy.utils.resource_path('SYSTEM')) candidates.append(system_root / "datafiles" / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend") except Exception: pass try: user_datafiles = Path(bpy.utils.user_resource('DATAFILES')) candidates.append(user_datafiles / "assets" / "geometry_nodes" / "procedural_hair_node_assets.blend") except Exception: pass for p in candidates: if p.exists(): return p raise FileNotFoundError( "Could not locate procedural_hair_node_assets.blend in Blender datafiles." ) def ensure_node_group_loaded_from_blend(node_group_name, blend_path): ng = bpy.data.node_groups.get(node_group_name) if ng is not None: return ng blend_path = Path(blend_path) if not blend_path.exists(): raise FileNotFoundError(f"Blend library not found: {blend_path}") with bpy.data.libraries.load(str(blend_path), link=False) as (data_from, data_to): if node_group_name not in data_from.node_groups: raise RuntimeError(f"Node group '{node_group_name}' not found in {blend_path}") data_to.node_groups = [node_group_name] ng = bpy.data.node_groups.get(node_group_name) if ng is None: raise RuntimeError(f"Failed to append node group '{node_group_name}' from {blend_path}") return ng def add_gn_modifier(curves_obj, node_group_name, modifier_name): select_and_activate(curves_obj) blend_path = get_essentials_blend_path() node_group = ensure_node_group_loaded_from_blend(node_group_name, blend_path) mod = curves_obj.modifiers.new(name=modifier_name, type='NODES') mod.node_group = node_group return mod def try_add_gn_modifier(curves_obj, node_group_names, modifier_name): last_err = None for ng_name in node_group_names: try: mod = add_gn_modifier(curves_obj, ng_name, modifier_name) log(f" + Loaded node group '{ng_name}' as '{modifier_name}'") return mod except Exception as e: last_err = e log(f" [WARN] Could not load any of {node_group_names} for '{modifier_name}': {last_err}") return None def add_custom_post_duplicate_modifier(curves_obj): select_and_activate(curves_obj) blend_path = get_essentials_blend_path() noise_ng = ensure_node_group_loaded_from_blend("Hair Curves Noise", blend_path) trim_ng = ensure_node_group_loaded_from_blend("Trim Hair Curves", blend_path) bpy.ops.object.modifier_add(type='NODES') mod = curves_obj.modifiers[-1] mod.name = "Custom Post Duplicate Trim" bpy.ops.node.new_geometry_node_group_assign() ng = mod.node_group ng.name = f"{curves_obj.name}_CustomPostDuplicateTrim" nodes = ng.nodes links = ng.links group_in = None group_out = None for node in nodes: if node.bl_idname == "NodeGroupInput": group_in = node elif node.bl_idname == "NodeGroupOutput": group_out = node if group_in is None or group_out is None: raise RuntimeError("Failed to get default GN group input/output nodes") for node in list(nodes): if node not in {group_in, group_out}: nodes.remove(node) group_in.location = (-1000, 0) group_out.location = (500, 0) try: id_node = nodes.new("GeometryNodeInputID") except RuntimeError: id_node = nodes.new("GeometryNodeInputIndex") id_node.location = (-1000, -220) random_value = nodes.new("FunctionNodeRandomValue") random_value.location = (-760, -220) random_value.data_type = 'BOOLEAN' random_value.inputs["Probability"].default_value = 0.08 if "Seed" in random_value.inputs: random_value.inputs["Seed"].default_value = 0 separate = nodes.new("GeometryNodeSeparateGeometry") separate.location = (-520, 0) separate.domain = 'CURVE' noise = nodes.new("GeometryNodeGroup") noise.location = (-220, -40) noise.node_tree = noise_ng trim = nodes.new("GeometryNodeGroup") trim.location = (40, -40) trim.node_tree = trim_ng join = nodes.new("GeometryNodeJoinGeometry") join.location = (260, 20) if "Factor" in noise.inputs: noise.inputs["Factor"].default_value = 1.0 if "Distance" in noise.inputs: noise.inputs["Distance"].default_value = 0.002 if "Shape" in noise.inputs: noise.inputs["Shape"].default_value = 0.5 if "Scale" in noise.inputs: noise.inputs["Scale"].default_value = 1.0 if "Scale Along Length" in noise.inputs: noise.inputs["Scale Along Length"].default_value = 1.0 if "Offset" in noise.inputs: noise.inputs["Offset"].default_value = 0.0 if "Cumulative Offset" in noise.inputs: noise.inputs["Cumulative Offset"].default_value = False if "Seed" in noise.inputs: noise.inputs["Seed"].default_value = 0 if "Mask" in trim.inputs: trim.inputs["Mask"].default_value = 1.0 if "Random Offset" in trim.inputs: trim.inputs["Random Offset"].default_value = 0.03 if "Pin at Parameter" in trim.inputs: trim.inputs["Pin at Parameter"].default_value = 0.0 if "Seed" in trim.inputs: trim.inputs["Seed"].default_value = 0 if "Replace Length" in trim.inputs: trim.inputs["Replace Length"].default_value = False if "ID" in random_value.inputs: if "ID" in id_node.outputs: links.new(id_node.outputs["ID"], random_value.inputs["ID"]) else: links.new(id_node.outputs["Index"], random_value.inputs["ID"]) links.new(group_in.outputs["Geometry"], separate.inputs["Geometry"]) links.new(random_value.outputs["Value"], separate.inputs["Selection"]) links.new(separate.outputs["Selection"], noise.inputs["Geometry"]) links.new(noise.outputs["Geometry"], trim.inputs["Geometry"]) links.new(separate.outputs["Inverted"], join.inputs["Geometry"]) links.new(trim.outputs["Geometry"], join.inputs["Geometry"]) links.new(join.outputs["Geometry"], group_out.inputs["Geometry"]) log(f" + Custom Post Duplicate Trim on {curves_obj.name}") return mod def setup_modifiers(curves_obj, group_name, mesh_obj, hair_info): is_mouse = group_name == "mouse_fur" is_face = group_name == "face_fur" is_ear = group_name == "ear_fur" profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "Set Hair Curve Profile") set_gn_input(profile_mod, "Radius", 0.00012) log(" + Set Hair Curve Profile (radius=0.0001)") add_custom_post_duplicate_modifier(curves_obj) if (not is_mouse) and (not is_face): if(not is_ear): mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves") set_gn_input(mod, "Amount", 8) set_gn_input(mod, "Radius", 0.007) set_gn_input(mod, "Distribution Shape", 1.0) log(" + Duplicate Hair Curves (radius=0.005, distribution_shape=1.0)") frizz_mod = try_add_gn_modifier( curves_obj, ["Frizz Hair Curves", "Hair Curves Frizz"], "Frizz Hair Curves" ) if frizz_mod is not None: set_gn_input(frizz_mod, "Factor", 0.7) set_gn_input(frizz_mod, "Distance", 0.001) set_gn_input(frizz_mod, "Shape", 0.01) log(" + Frizz Hair Curves (factor=0.7, distance=0.001, shape=0.01)") else: log(" + Skip Duplicate Hair Curves for mouse_fur/face") if is_face or is_ear: mod = add_gn_modifier(curves_obj, "Duplicate Hair Curves", "Duplicate Hair Curves") set_gn_input(mod, "Amount", 3) set_gn_input(mod, "Radius", 0.005) set_gn_input(mod, "Distribution Shape", 1.0) def delete_default_cube(): cube = bpy.data.objects.get("Cube") if cube is None: return bpy.ops.object.select_all(action='DESELECT') cube.select_set(True) bpy.context.view_layer.objects.active = cube bpy.ops.object.delete() log("Deleted default Cube") def clear_material_slots(obj): if not hasattr(obj.data, "materials"): return obj.data.materials.clear() def assign_material(obj, material): if not hasattr(obj.data, "materials"): return obj.data.materials.clear() obj.data.materials.append(material) if hasattr(obj, "active_material"): obj.active_material = material def extract_numeric_suffix(name: str): m = re.search(r"(\d+)$", name) return int(m.group(1)) if m else None def natural_key(path: Path): parts = re.split(r"(\d+)", path.stem.lower()) key = [] for p in parts: if p.isdigit(): key.append(int(p)) else: key.append(p) key.append(path.suffix.lower()) return key def find_texture_for_obj(obj_path: str, textures_dir: str): """ Match a shape OBJ to a texture by natural-sort index. This mirrors the dataset auxiliary-file rule after excluding hidden and macOS resource-fork files. For a group with five real shapes and five textures, only those five files participate in pairing. """ obj_path = Path(obj_path).expanduser().resolve() textures_dir = Path(textures_dir).expanduser().resolve() shapes_dir = obj_path.parent.resolve() if not shapes_dir.is_dir(): raise FileNotFoundError(f"Shapes directory not found: {shapes_dir}") if not textures_dir.is_dir(): raise FileNotFoundError(f"Textures directory not found: {textures_dir}") if not is_usable_file(obj_path): raise FileNotFoundError( f"OBJ is missing or is a hidden/macOS metadata file: {obj_path}" ) shape_files = sorted( [ path for path in shapes_dir.iterdir() if is_usable_file(path) and path.suffix.lower() == ".obj" ], key=natural_key, ) texture_files = sorted( [ path for path in textures_dir.iterdir() if is_usable_file(path) and path.suffix.lower() in IMAGE_EXTS ], key=natural_key, ) if not shape_files: raise FileNotFoundError(f"No usable shape OBJ files found in: {shapes_dir}") if not texture_files: raise FileNotFoundError(f"No usable texture files found in: {textures_dir}") try: shape_index = next( index for index, path in enumerate(shape_files) if path.resolve() == obj_path ) except StopIteration as exc: raise FileNotFoundError( f"Could not find usable OBJ {obj_path.name} in: {shapes_dir}" ) from exc if len(texture_files) == 1: chosen = texture_files[0] elif shape_index < len(texture_files): chosen = texture_files[shape_index] else: raise IndexError( "Texture index out of range after hidden-file filtering. " f"usable_shapes={len(shape_files)}, " f"usable_textures={len(texture_files)}, " f"shape_index={shape_index}, obj={obj_path.name}" ) log( "Texture matched by natural-sort index: " f"shape[{shape_index}]={obj_path.name} -> {chosen.name}; " f"usable_shapes={len(shape_files)}, " f"usable_textures={len(texture_files)}" ) return chosen def set_node_input_if_exists(node, input_name, value): if input_name in node.inputs: node.inputs[input_name].default_value = value def set_enum_attr_if_exists(node, attr_names, value): for attr in attr_names: if hasattr(node, attr): try: setattr(node, attr, value) return True except Exception: pass return False def create_mesh_material(mesh_obj, texture_path: str, normal_path: str, roughness_path: str, material_name="MeshMaterial"): texture_path = Path(texture_path).resolve() normal_path = Path(normal_path).resolve() if normal_path else None roughness_path = Path(roughness_path).resolve() if roughness_path else None if not is_usable_file(texture_path): raise FileNotFoundError( f"Mesh texture is missing or hidden: {texture_path}" ) mat = bpy.data.materials.get(material_name) if mat is None: mat = bpy.data.materials.new(material_name) mat.use_nodes = True nt = mat.node_tree nodes = nt.nodes links = nt.links nodes.clear() out = nodes.new("ShaderNodeOutputMaterial") out.location = (700, 0) bsdf = nodes.new("ShaderNodeBsdfPrincipled") bsdf.location = (350, 0) set_node_input_if_exists(bsdf, "IOR", 1.5) tex_color = nodes.new("ShaderNodeTexImage") tex_color.location = (-450, 150) tex_color.image = open_image_color(str(texture_path)) tex_color.interpolation = 'Linear' tex_color.extension = 'REPEAT' links.new(tex_color.outputs["Color"], bsdf.inputs["Base Color"]) if "Alpha" in tex_color.outputs and "Alpha" in bsdf.inputs: links.new(tex_color.outputs["Alpha"], bsdf.inputs["Alpha"]) if roughness_path is not None and is_usable_file(roughness_path): tex_rough = nodes.new("ShaderNodeTexImage") tex_rough.location = (-450, -50) tex_rough.image = open_image_simple(str(roughness_path), non_color=True) tex_rough.interpolation = 'Linear' tex_rough.extension = 'REPEAT' links.new(tex_rough.outputs["Color"], bsdf.inputs["Roughness"]) else: set_node_input_if_exists(bsdf, "Roughness", 0.5) log("Roughness map not found; using constant roughness=0.5") if normal_path is not None and is_usable_file(normal_path): tex_normal = nodes.new("ShaderNodeTexImage") tex_normal.location = (-450, -250) tex_normal.image = open_image_simple(str(normal_path), non_color=True) tex_normal.interpolation = 'Linear' tex_normal.extension = 'REPEAT' normal_map = nodes.new("ShaderNodeNormalMap") normal_map.location = (-100, -250) set_node_input_if_exists(normal_map, "Strength", 1.0) links.new(tex_normal.outputs["Color"], normal_map.inputs["Color"]) links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"]) else: log("Normal map not found; using mesh normals") links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) try: mat.blend_method = 'HASHED' except Exception: pass try: mat.shadow_method = 'HASHED' except Exception: pass assign_material(mesh_obj, mat) log(f"Assigned mesh material: {mat.name}") return mat def create_hair_material(texture_path: str, material_name="HairMaterial"): texture_path = require_usable_file( texture_path, "Hair texture", ) mat = bpy.data.materials.get(material_name) if mat is None: mat = bpy.data.materials.new(material_name) mat.use_nodes = True nt = mat.node_tree nodes = nt.nodes links = nt.links nodes.clear() tex_mesh = nodes.new("ShaderNodeTexImage") tex_mesh.location = (-900, 200) tex_mesh.image = open_image_color(str(texture_path)) tex_mesh.interpolation = 'Linear' tex_mesh.extension = 'REPEAT' tex_hair = nodes.new("ShaderNodeTexImage") tex_hair.location = (-900, -200) tex_hair.image = open_image_color(str(texture_path)) tex_hair.interpolation = 'Linear' tex_hair.extension = 'REPEAT' bsdf = nodes.new("ShaderNodeBsdfPrincipled") bsdf.location = (-500, 180) set_node_input_if_exists(bsdf, "IOR", 1.5) set_node_input_if_exists(bsdf, "Roughness", 0.5) set_node_input_if_exists(bsdf, "Alpha", 1.0) hair_bsdf = nodes.new("ShaderNodeBsdfHairPrincipled") hair_bsdf.location = (-500, -220) set_enum_attr_if_exists(hair_bsdf, ["model", "distribution"], 'CHIANG') set_enum_attr_if_exists(hair_bsdf, ["parametrization"], 'COLOR') set_node_input_if_exists(hair_bsdf, "Roughness", 0.4) set_node_input_if_exists(hair_bsdf, "Radial Roughness", 0.6) set_node_input_if_exists(hair_bsdf, "Coat", 0.0) set_node_input_if_exists(hair_bsdf, "IOR", 1.5) set_node_input_if_exists(hair_bsdf, "Offset", math.radians(3.0)) set_node_input_if_exists(hair_bsdf, "Random Roughness", 0.25) mix_main = nodes.new("ShaderNodeMixShader") mix_main.location = (-120, 20) if "Fac" in mix_main.inputs: mix_main.inputs["Fac"].default_value = 0.6 transparent = nodes.new("ShaderNodeBsdfTransparent") transparent.location = (-120, -260) light_path = nodes.new("ShaderNodeLightPath") light_path.location = (-360, 320) mix_shadow = nodes.new("ShaderNodeMixShader") mix_shadow.location = (180, 50) out = nodes.new("ShaderNodeOutputMaterial") out.location = (420, 50) links.new(tex_mesh.outputs["Color"], bsdf.inputs["Base Color"]) links.new(tex_hair.outputs["Color"], hair_bsdf.inputs["Color"]) links.new(bsdf.outputs["BSDF"], mix_main.inputs[1]) links.new(hair_bsdf.outputs["BSDF"], mix_main.inputs[2]) links.new(light_path.outputs["Is Shadow Ray"], mix_shadow.inputs["Fac"]) links.new(mix_main.outputs["Shader"], mix_shadow.inputs[1]) links.new(transparent.outputs["BSDF"], mix_shadow.inputs[2]) links.new(mix_shadow.outputs["Shader"], out.inputs["Surface"]) try: mat.blend_method = 'HASHED' except Exception: pass try: mat.shadow_method = 'HASHED' except Exception: pass try: mat.use_backface_culling = False except Exception: pass log(f"Created hair material: {mat.name}") return mat def setup_cycles_render(scene): scene.render.engine = 'CYCLES' scene.cycles.samples = 64 try: scene.cycles.device = 'GPU' except Exception: pass try: scene.render.film_transparent = True except Exception: pass try: scene.view_layers["ViewLayer"].cycles.use_denoising = False except Exception: pass log("Set render engine to Cycles") def setup_world_hdr(hdr_path: str): hdr_path = require_usable_file(hdr_path, "HDR image") scene = bpy.context.scene world = scene.world if world is None: world = bpy.data.worlds.new("World") scene.world = world world.use_nodes = True nt = world.node_tree nodes = nt.nodes links = nt.links nodes.clear() tex_coord = nodes.new("ShaderNodeTexCoord") tex_coord.location = (-900, 0) mapping = nodes.new("ShaderNodeMapping") mapping.location = (-700, 0) env_tex = nodes.new("ShaderNodeTexEnvironment") env_tex.location = (-500, 0) env_tex.image = bpy.data.images.load(filepath=str(hdr_path), check_existing=True) background = nodes.new("ShaderNodeBackground") background.location = (-220, 0) background.inputs["Strength"].default_value = random.uniform(0.4, 0.6) world_out = nodes.new("ShaderNodeOutputWorld") world_out.location = (300, 0) links.new(tex_coord.outputs["Generated"], mapping.inputs["Vector"]) links.new(mapping.outputs["Vector"], env_tex.inputs["Vector"]) links.new(env_tex.outputs["Color"], background.inputs["Color"]) links.new(background.outputs["Background"], world_out.inputs["Surface"]) scene.render.film_transparent = True log(f"Set HDR world lighting: {hdr_path}") def compute_mesh_bbox_center_and_radius(mesh_obj): """Compute the world-space bounding box center and enclosing sphere radius.""" bbox_corners = [mesh_obj.matrix_world @ Vector(c) for c in mesh_obj.bound_box] bbox_min = Vector(( min(c.x for c in bbox_corners), min(c.y for c in bbox_corners), min(c.z for c in bbox_corners), )) bbox_max = Vector(( max(c.x for c in bbox_corners), max(c.y for c in bbox_corners), max(c.z for c in bbox_corners), )) center = (bbox_min + bbox_max) / 2.0 radius = (bbox_max - bbox_min).length / 2.0 return center, radius def ensure_camera(mesh_obj=None, h_range=(-20, 20), v_range=(10, 30), render_size=1024, padding=0.9): """Create/reuse a camera with random orbit around the mesh. Args: mesh_obj: The target mesh. If None, falls back to a fixed position. h_range: (min_deg, max_deg) horizontal rotation range around the object. 0 = front (+X axis looking at center), negative = left, positive = right. v_range: (min_deg, max_deg) vertical elevation range. 0 = horizon level, 45 = looking down at 45 degrees. render_size: Output image resolution (square). padding: Multiplier on the camera distance to ensure the whole mesh (including hair) fits in frame. >1.0 adds margin. """ cam_obj = bpy.data.objects.get("RenderCamera") if cam_obj is None or cam_obj.type != 'CAMERA': cam_data = bpy.data.cameras.new("RenderCamera") cam_obj = bpy.data.objects.new("RenderCamera", cam_data) bpy.context.collection.objects.link(cam_obj) scene = bpy.context.scene scene.camera = cam_obj # Set render resolution to 512x512 scene.render.resolution_x = render_size scene.render.resolution_y = render_size scene.render.resolution_percentage = 100 if mesh_obj is None: # Fallback: fixed position cam_obj.location = (2.0, 0.0, 0.0) cam_obj.rotation_euler = ( math.radians(90.0), math.radians(0.0), math.radians(90.0), ) log("Set camera at fixed fallback position (no mesh provided)") return cam_obj # Compute mesh bounding sphere center, radius = compute_mesh_bbox_center_and_radius(mesh_obj) if radius < 1e-6: radius = 1.0 # Random angles h_deg = random.uniform(h_range[0], h_range[1]) v_deg = random.uniform(v_range[0], v_range[1]) h_rad = math.radians(h_deg) v_rad = math.radians(v_deg) # Compute camera distance so the bounding sphere fits in the FOV cam_data = cam_obj.data cam_data.sensor_fit = 'AUTO' # cam_data.angle = 75 # cam_data.fov = 75 cam_data.lens = 75 print(cam_data.angle) fov = cam_data.angle # full horizontal FOV in radians half_fov = fov / 2.0 # Distance from center so the sphere of size (radius * padding) fits distance = (radius * padding) / math.sin(half_fov) if distance < 0.01: distance = 2.0 # Spherical coordinates -> cartesian offset from center # h_rad=0 means looking from +X toward center (front view) # v_rad=0 means at horizon level, v_rad>0 means elevated (looking down) cam_x = center.x + distance * math.cos(v_rad) * math.cos(h_rad) cam_y = center.y + distance * math.cos(v_rad) * math.sin(h_rad) cam_z = center.z + distance * math.sin(v_rad) cam_obj.location = (cam_x, cam_y, cam_z) # Point camera at center using a track-to constraint (most robust) # Remove any existing track-to constraint first for c in list(cam_obj.constraints): if c.type == 'TRACK_TO': cam_obj.constraints.remove(c) # Create an empty at the mesh center as the track target target_empty = bpy.data.objects.get("CameraTarget") if target_empty is None: target_empty = bpy.data.objects.new("CameraTarget", None) bpy.context.collection.objects.link(target_empty) target_empty.location = center target_empty.empty_display_size = 0.01 target_empty.hide_viewport = True target_empty.hide_render = True constraint = cam_obj.constraints.new(type='TRACK_TO') constraint.target = target_empty constraint.track_axis = 'TRACK_NEGATIVE_Z' constraint.up_axis = 'UP_Y' # Force update so the constraint takes effect bpy.context.view_layer.update() log( f"Camera: h={h_deg:.1f}° v={v_deg:.1f}° dist={distance:.3f} " f"center=({center.x:.3f},{center.y:.3f},{center.z:.3f}) " f"render={render_size}x{render_size}" ) return cam_obj def sample_image_luminance_at_uv(img, uv, pixels_np=None): width, height = img.size if pixels_np is None: pixel_count = width * height * 4 pixels_np = np.empty(pixel_count, dtype=np.float32) img.pixels.foreach_get(pixels_np) pixels_np = pixels_np.reshape((height, width, 4)) u = float(np.clip(uv[0], 0.0, 1.0)) v = float(np.clip(uv[1], 0.0, 1.0)) xi = int(u * (width - 1)) yi = int(v * (height - 1)) rgba = pixels_np[yi, xi] lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2] return float(lum) def remove_curve_uv_attributes(curves_obj): curves = curves_obj.data try: curves.surface_uv_map = "" except Exception: pass for attr_name in ["surface_uv_coordinate", "uv_map", "UVMap", "UV", "map1"]: attr = curves.attributes.get(attr_name) if attr is not None: try: curves.attributes.remove(attr) log(f" Removed curve attribute: {attr_name}") except Exception as e: log(f" [WARN] Failed removing curve attribute '{attr_name}': {e}") def create_underhair_guides_from_mesh(mesh_obj, mask_image_path, strand_length=0.01, threshold=0.05): """Create underhair guide strands using the evaluated (deformed) mesh.""" mesh = mesh_obj.data if not mesh.uv_layers.active: raise RuntimeError("Mesh has no active UV layer; underhair mask sampling requires UVs.") mask_img = open_image_simple(str(mask_image_path), non_color=True) width, height = mask_img.size pixel_count = width * height * 4 pixels_np = np.empty(pixel_count, dtype=np.float32) mask_img.pixels.foreach_get(pixels_np) pixels_np = pixels_np.reshape((height, width, 4)) # Use evaluated mesh for vertex positions and normals eval_obj, eval_mesh = get_evaluated_mesh(mesh_obj) total_loops = len(eval_mesh.loops) loop_uvs = np.empty(total_loops * 2, dtype=np.float32) eval_mesh.uv_layers.active.data.foreach_get("uv", loop_uvs) loop_uvs = loop_uvs.reshape((total_loops, 2)) loop_verts = np.empty(total_loops, dtype=np.int32) eval_mesh.loops.foreach_get("vertex_index", loop_verts) num_verts = len(eval_mesh.vertices) uv_sum = np.zeros((num_verts, 2), dtype=np.float64) uv_cnt = np.zeros(num_verts, dtype=np.int32) np.add.at(uv_sum[:, 0], loop_verts, loop_uvs[:, 0]) np.add.at(uv_sum[:, 1], loop_verts, loop_uvs[:, 1]) np.add.at(uv_cnt, loop_verts, 1) valid = uv_cnt > 0 avg_uv = np.zeros((num_verts, 2), dtype=np.float64) avg_uv[valid] = uv_sum[valid] / uv_cnt[valid][:, None] strands = [] weights = np.zeros(num_verts, dtype=np.float32) for vid in range(num_verts): if not valid[vid]: continue uv = avg_uv[vid] w = sample_image_luminance_at_uv(mask_img, uv, pixels_np=pixels_np) weights[vid] = w if w <= threshold: continue root = eval_mesh.vertices[vid].co.copy() normal = eval_mesh.vertices[vid].normal.normalized() tip = root + normal * float(strand_length) strand = np.stack([ np.array((root.x, root.y, root.z), dtype=np.float32), np.array((tip.x, tip.y, tip.z), dtype=np.float32), ], axis=0) strands.append(strand) eval_obj.to_mesh_clear() old_vg = mesh_obj.vertex_groups.get(UNDERHAIR_MASK_GROUP) if old_vg is not None: mesh_obj.vertex_groups.remove(old_vg) vg = mesh_obj.vertex_groups.new(name=UNDERHAIR_MASK_GROUP) for vid, w in enumerate(weights): if w > 0.0: vg.add([vid], float(w), 'REPLACE') log(f"Created underhair guides: {len(strands)} strands") return strands, vg, mask_img def setup_underhair_modifiers(curves_obj, mesh_obj, mask_img, trim_length=0.01): profile_mod = add_gn_modifier(curves_obj, "Set Hair Curve Profile", "UnderHair Profile") set_gn_input(profile_mod, "Radius", 0.0001) log(" + UnderHair Profile (radius=0.0001)") interp_mod = add_gn_modifier(curves_obj, "Interpolate Hair Curves", "UnderHair Interpolate") try: interp_mod["Input_2"] = mesh_obj log(f" + UnderHair Interpolate Input_2 = {mesh_obj.name}") except Exception as e: log(f" [WARN] Failed setting UnderHair Interpolate Input_2: {e}") set_gn_input(interp_mod, "Surface", mesh_obj) set_gn_input(interp_mod, "Surface Object", mesh_obj) set_gn_input(interp_mod, "Mesh", mesh_obj) density_set = False density_set |= set_gn_input(interp_mod, "Surface Density", UNDERHAIR_INTERP_DENSITY) density_set |= set_gn_input(interp_mod, "Density", UNDERHAIR_INTERP_DENSITY) density_set |= set_gn_input_by_keywords(interp_mod, ["density"], UNDERHAIR_INTERP_DENSITY) density_set |= set_gn_input_by_keywords(interp_mod, ["surface", "density"], UNDERHAIR_INTERP_DENSITY) if not density_set: log(" [WARN] Could not find interpolation density socket; value may remain default") set_gn_input(interp_mod, "Interpolation Quality", 6) set_gn_input(interp_mod, "Variation Level", 0.15) set_gn_input(interp_mod, "Guide Mask", 0.0) set_gn_input(interp_mod, "Use Guide Mask", False) interp_tex_id = get_node_input_identifier_by_name(interp_mod, "Mask Texture") if interp_tex_id is not None: try: interp_mod[interp_tex_id] = mask_img log(" + UnderHair Interpolate mask texture = merged.png") except Exception as e: log(f" [WARN] Failed to assign interpolate mask texture: {e}") log(" + UnderHair Interpolate configured") noise_mod = add_gn_modifier(curves_obj, "Hair Curves Noise", "UnderHair Noise") set_gn_input(noise_mod, "Factor", 1.0) set_gn_input(noise_mod, "Distance", 0.0015) set_gn_input(noise_mod, "Shape", 0.5) set_gn_input(noise_mod, "Scale", 18.0) set_gn_input(noise_mod, "Scale Along Length", 1.0) set_gn_input(noise_mod, "Offset", 0.0) set_gn_input(noise_mod, "Cumulative Offset", False) set_gn_input(noise_mod, "Seed", 0) log(" + UnderHair Noise") frizz_mod = try_add_gn_modifier( curves_obj, ["Frizz Hair Curves", "Hair Curves Frizz"], "UnderHair Frizz" ) if frizz_mod is not None: set_gn_input(frizz_mod, "Amount", 0.6) set_gn_input(frizz_mod, "Radius", 0.001) set_gn_input(frizz_mod, "Frequency", 12.0) set_gn_input(frizz_mod, "Seed", 0) set_gn_input(frizz_mod, "Mask", 1.0) frizz_tex_id = get_node_input_identifier_by_name(frizz_mod, "Mask Texture") if frizz_tex_id is not None: try: frizz_mod[frizz_tex_id] = mask_img log(" + UnderHair Frizz mask texture = merged.png") except Exception as e: log(f" [WARN] Failed to assign frizz mask texture: {e}") log(" + UnderHair Frizz") trim_mod = add_gn_modifier(curves_obj, "Trim Hair Curves", "UnderHair Trim") set_gn_input(trim_mod, "Mask", 1.0) set_gn_input(trim_mod, "Random Offset", 0.0) set_gn_input(trim_mod, "Pin at Parameter", 0.0) set_gn_input(trim_mod, "Replace Length", True) set_gn_input(trim_mod, "Length", float(trim_length)) trim_tex_id = get_node_input_identifier_by_name(trim_mod, "Mask Texture") if trim_tex_id is not None: try: trim_mod[trim_tex_id] = mask_img log(" + UnderHair Trim mask texture = merged.png") except Exception as e: log(f" [WARN] Failed to assign trim mask texture: {e}") log(f" + UnderHair Trim (length={trim_length})") def create_underhair_if_available(mesh_obj, mesh_material, mask_image_path): mask_path = Path(mask_image_path).resolve() if not mask_path.exists(): log(f"Underhair mask not found; skipping underhair: {mask_path}") return None return create_underhair_on_mesh( mesh_obj=mesh_obj, mesh_material=mesh_material, mask_image_path=str(mask_path), ) def create_underhair_on_mesh(mesh_obj, mesh_material, mask_image_path): log("Creating underhair from mesh surface...") strands, mask_vg, mask_img = create_underhair_guides_from_mesh( mesh_obj=mesh_obj, mask_image_path=str(mask_image_path), strand_length=UNDERHAIR_LENGTH, threshold=0.05, ) if len(strands) == 0: log(" [WARN] No underhair strands created from mask.") return None underhair_obj = build_curve_object_from_strands_no_uv( obj_name="underhair", strands=strands, mesh_obj=mesh_obj, ) if underhair_obj is None: return None remove_curve_uv_attributes(underhair_obj) assign_material(underhair_obj, mesh_material) setup_underhair_modifiers( curves_obj=underhair_obj, mesh_obj=mesh_obj, mask_img=mask_img, trim_length=UNDERHAIR_LENGTH, ) log("Underhair object created successfully") return underhair_obj def get_child_hair_objects(surface_obj): out = [] for obj in bpy.data.objects: if obj.parent == surface_obj and obj.type in {'CURVES', 'MESH'}: out.append(obj) return out def ensure_curve_bound_to_surface(curves_obj, surface_obj): if curves_obj.type != 'CURVES': return curves = curves_obj.data curves.surface = surface_obj if surface_obj.data.uv_layers.active is not None: try: curves.surface_uv_map = surface_obj.data.uv_layers.active.name except Exception: pass curves_obj.parent = surface_obj try: curves_obj.matrix_parent_inverse = surface_obj.matrix_world.inverted() except Exception: pass def add_or_rebind_surface_deform(mesh_hair_obj, surface_obj, modifier_name="SurfaceDeformToBody"): mod = mesh_hair_obj.modifiers.get(modifier_name) if mod is None: mod = mesh_hair_obj.modifiers.new(name=modifier_name, type='SURFACE_DEFORM') mod.target = surface_obj mod.falloff = 4.0 try: bpy.ops.object.mode_set(mode='OBJECT') except Exception: pass bpy.ops.object.select_all(action='DESELECT') mesh_hair_obj.select_set(True) bpy.context.view_layer.objects.active = mesh_hair_obj try: bpy.ops.object.surfacedeform_bind(modifier=mod.name) log(f"Bound Surface Deform on '{mesh_hair_obj.name}' -> '{surface_obj.name}'") except Exception as e: log(f"[WARN] Failed to bind Surface Deform on '{mesh_hair_obj.name}': {e}") return mod def apply_surface_deform_or_surface_bind_to_all_hair(surface_obj, hair_objects=None): if hair_objects is None: hair_objects = get_child_hair_objects(surface_obj) for obj in hair_objects: if obj.type == 'CURVES': ensure_curve_bound_to_surface(obj, surface_obj) log(f"Rebound curves surface for '{obj.name}'") elif obj.type == 'MESH': add_or_rebind_surface_deform(obj, surface_obj) bpy.context.view_layer.update() return hair_objects def refresh_hair_after_shape_change(surface_obj, hair_objects=None): if hair_objects is None: hair_objects = get_child_hair_objects(surface_obj) for obj in hair_objects: if obj.type == 'CURVES': ensure_curve_bound_to_surface(obj, surface_obj) for mod in obj.modifiers: try: mod.show_viewport = False mod.show_viewport = True except Exception: pass obj.update_tag() surface_obj.update_tag() # Force a full depsgraph evaluation so all curves re-snap depsgraph = bpy.context.evaluated_depsgraph_get() depsgraph.update() bpy.context.view_layer.update() log(f"Refreshed {len(hair_objects)} hair objects after shape change") def load_hair_scene( obj_path: str, mesh_object_name: str = "DeformedMesh", save_blend_path: str = None, render_filename: str = None, ): """Load mesh + hair without any deformation applied. Hair is built on the base (undeformed) mesh geometry. """ t_start = time.perf_counter() paths = resolve_paths_from_obj(obj_path) scene = bpy.context.scene delete_default_cube() setup_cycles_render(scene) log("Selecting random HDR...") hdr_path = pick_random_hdr_image(str(paths["hdr_dir"])) log("Setting up world HDR...") setup_world_hdr(str(hdr_path)) log("Importing mesh...") mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name) if not mesh_obj.data.uv_layers: raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.") # # Set up camera after mesh is loaded so it can frame the object # ensure_camera(mesh_obj) log("Resolving dataset texture...") raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"])) texture_path = remove_green_screen_from_image( src_image_path=str(raw_texture_path), out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"), green_threshold=0.45, green_margin=0.08, ) log(f"Using processed texture: {texture_path}") log("Creating mesh material...") mesh_mat = create_mesh_material( mesh_obj=mesh_obj, texture_path=str(texture_path), normal_path=str(paths["mesh_normal"]), roughness_path=str(paths["mesh_roughness"]), material_name=f"{mesh_object_name}_MeshMaterial", ) log("Creating hair material...") hair_mat = create_hair_material( texture_path=str(texture_path), material_name=f"{mesh_object_name}_HairMaterial", ) log("Creating underhair...") underhair_obj = create_underhair_if_available( mesh_obj=mesh_obj, mesh_material=mesh_mat, mask_image_path=str(UNDERHAIR_MASK_PATH), ) # Density and length maps are optional for this visualization pipeline. # Strand positions and lengths are reconstructed directly from the hair map. hair_info = {} hair_map_path = str(paths["hair_map"]) log(f"Loading UV-local 512 hair map: {hair_map_path}") log(f"Loading global hair meta: {paths['hair_meta']}") group_names, strands_by_group, samples = decode_hair_map( hair_map_path, str(paths["hair_meta"]), mesh_obj, ) log(f" Samples per strand: {samples}") created_objects = [] for group_name in group_names: if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS): log(f" [SKIP] Group '{group_name}' ignored by keyword") continue strands = strands_by_group.get(group_name) if strands is None or strands.shape[0] == 0: log(f" [SKIP] Group '{group_name}' has 0 strands") continue log(f" Processing group: {group_name} ({strands.shape[0]} strands)") roots = strands[:, 0, :] root_uvs = compute_root_uvs(roots, mesh_obj) curves_obj = build_curve_object_from_strands( sanitize_name(group_name), strands, root_uvs, mesh_obj, ) if curves_obj is None: continue assign_material(curves_obj, hair_mat) log(f" Setting up modifiers for: {curves_obj.name}") setup_modifiers(curves_obj, group_name, mesh_obj, hair_info) created_objects.append(curves_obj) if underhair_obj is not None: created_objects.append(underhair_obj) loaded_hair_map = str(paths["hair_map_curl_out"]) log(f"Loaded hair map from: {loaded_hair_map}") if save_blend_path: save_blend_path = str(Path(save_blend_path).resolve()) bpy.ops.wm.save_as_mainfile(filepath=save_blend_path) log(f"Saved blend file: {save_blend_path}") render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename) elapsed = time.perf_counter() - t_start log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s") for obj in created_objects: log(f" {obj.name}") return mesh_obj, created_objects def apply_deformed_shape_key_to_loaded_scene( source_obj_path: str, mesh_obj, hair_objects, deformed_obj_path: str = None, shape_key_name: str = "DeformedShape", shape_key_value: float = 1.0, ): """Legacy shape-key approach. Hair may not follow correctly for curves objects unless the curves were built on the already-deformed mesh. Prefer load_hair_scene_with_deformed_shape() which deforms first. """ deformed_path = resolve_corresponding_deformed_shape_path( source_obj_path, deformed_obj_path=deformed_obj_path, ) log(f"Using deformed shape OBJ: {deformed_path}") log("Applying surface deform / surface binding to all hair before shape key...") apply_surface_deform_or_surface_bind_to_all_hair(mesh_obj, hair_objects) log("Creating shape key from deformed mesh...") sk = import_obj_as_shape_key(mesh_obj, str(deformed_path), shape_key_name) sk.value = float(shape_key_value) log("Refreshing hair after shape key update...") refresh_hair_after_shape_change(mesh_obj, hair_objects) return sk def load_hair_scene_with_deformed_shape( obj_path: str, mesh_object_name: str = "DeformedMesh", deformed_obj_path: str = None, shape_key_name: str = "DeformedShape", shape_key_value: float = 1.0, save_blend_path: str = None, use_shape_key: bool = False, render_filename: str = None, ): """Load mesh, apply deformation FIRST, then build all hair on the already-deformed geometry so that hair roots and strands match the deformed surface. Args: use_shape_key: If True, use the legacy shape-key approach (hair is built on the base mesh then shape key is applied afterward). If False (default), the deformed vertex positions are written directly into the base mesh before hair is created, so hair is naturally placed on the deformed surface. """ if use_shape_key: # --- Legacy path: build hair on base mesh, then apply shape key --- mesh_obj, created_objects = load_hair_scene( obj_path=obj_path, mesh_object_name=mesh_object_name, save_blend_path=None, render_filename=render_filename, ) sk = apply_deformed_shape_key_to_loaded_scene( source_obj_path=obj_path, mesh_obj=mesh_obj, hair_objects=created_objects, deformed_obj_path=deformed_obj_path, shape_key_name=shape_key_name, shape_key_value=shape_key_value, ) if save_blend_path: save_blend_path = str(Path(save_blend_path).resolve()) bpy.ops.wm.save_as_mainfile(filepath=save_blend_path) log(f"Saved blend file: {save_blend_path}") return mesh_obj, created_objects, sk # --- New path: deform mesh first, then build hair on deformed geometry --- t_start = time.perf_counter() paths = resolve_paths_from_obj(obj_path) scene = bpy.context.scene delete_default_cube() setup_cycles_render(scene) log("Selecting random HDR...") hdr_path = pick_random_hdr_image(str(paths["hdr_dir"])) log("Setting up world HDR...") setup_world_hdr(str(hdr_path)) # Step 1: Import the base mesh log("Importing base mesh...") mesh_obj = import_obj_as_mesh(obj_path, mesh_object_name) if not mesh_obj.data.uv_layers: raise RuntimeError("Imported mesh has no UV map. Texture assignment requires UVs.") # Step 2: Apply deformed vertex positions directly to the base mesh if deformed_obj_path: deformed_path = resolve_corresponding_deformed_shape_path( obj_path, deformed_obj_path=deformed_obj_path, ) log(f"Applying deformed shape directly from: {deformed_path}") apply_deformed_shape_directly(mesh_obj, str(deformed_path)) bpy.context.view_layer.update() else: log("No deformed OBJ supplied; using the original mesh geometry") # # Set up camera after deformation so it frames the deformed mesh correctly # ensure_camera(mesh_obj) # Step 3: Set up materials log("Resolving dataset texture...") raw_texture_path = find_texture_for_obj(obj_path, str(paths["textures_dir"])) texture_path = remove_green_screen_from_image( src_image_path=str(raw_texture_path), out_image_path=str(Path(paths["dataset_dir"]) / "textures_processed" / f"{Path(raw_texture_path).stem}_nogreen.png"), green_threshold=0.45, green_margin=0.08, ) log(f"Using processed texture: {texture_path}") log("Creating mesh material...") mesh_mat = create_mesh_material( mesh_obj=mesh_obj, texture_path=str(texture_path), normal_path=str(paths["mesh_normal"]), roughness_path=str(paths["mesh_roughness"]), material_name=f"{mesh_object_name}_MeshMaterial", ) log("Creating hair material...") hair_mat = create_hair_material( texture_path=str(texture_path), material_name=f"{mesh_object_name}_HairMaterial", ) # Step 4: Create underhair (now on deformed mesh) log("Creating underhair on deformed mesh...") underhair_obj = create_underhair_if_available( mesh_obj=mesh_obj, mesh_material=mesh_mat, mask_image_path=str(UNDERHAIR_MASK_PATH), ) # Step 5: Load density/length maps # Density and length maps are optional for this visualization pipeline. # Strand positions and lengths are reconstructed directly from the hair map. hair_info = {} # Step 6: Decode hair map (reconstructs strand positions on deformed geometry) hair_map_path = str(paths["hair_map"]) log(f"Loading UV-local 512 hair map: {hair_map_path}") log(f"Loading global hair meta: {paths['hair_meta']}") group_names, strands_by_group, samples = decode_hair_map( hair_map_path, str(paths["hair_meta"]), mesh_obj, ) log(f" Samples per strand: {samples}") # Step 7: Build hair curve objects on deformed mesh created_objects = [] for group_name in group_names: if any(k in group_name.lower() for k in IGNORE_NAME_KEYWORDS): log(f" [SKIP] Group '{group_name}' ignored by keyword") continue strands = strands_by_group.get(group_name) if strands is None or strands.shape[0] == 0: log(f" [SKIP] Group '{group_name}' has 0 strands") continue log(f" Processing group: {group_name} ({strands.shape[0]} strands)") roots = strands[:, 0, :] root_uvs = compute_root_uvs(roots, mesh_obj) curves_obj = build_curve_object_from_strands( sanitize_name(group_name), strands, root_uvs, mesh_obj, ) if curves_obj is None: continue assign_material(curves_obj, hair_mat) log(f" Setting up modifiers for: {curves_obj.name}") setup_modifiers(curves_obj, group_name, mesh_obj, hair_info) created_objects.append(curves_obj) if underhair_obj is not None: created_objects.append(underhair_obj) loaded_hair_map = str(paths["hair_map_curl_out"]) log(f"Loaded hair map from: {loaded_hair_map}") if save_blend_path: save_blend_path = str(Path(save_blend_path).resolve()) bpy.ops.wm.save_as_mainfile(filepath=save_blend_path) log(f"Saved blend file: {save_blend_path}") render_output_path = resolve_render_output_path(obj_path, render_filename=render_filename) # TODO # render_and_save_image(str(render_output_path)) elapsed = time.perf_counter() - t_start log(f"Done. Created {len(created_objects)} curve objects in {elapsed:.2f}s") for obj in created_objects: log(f" {obj.name}") # No shape key was created in this path, return None for sk return mesh_obj, created_objects, None if __name__ == "__main__": argv = sys.argv user_args = argv[argv.index("--") + 1:] if "--" in argv else [] parser = argparse.ArgumentParser() parser.add_argument( "--obj_path", type=str, default=None, help=( "OBJ inside //dataset//shapes. " "When omitted, a valid case is discovered automatically." ), ) parser.add_argument("--species", type=str, default="small_cat") parser.add_argument( "--group_name", type=str, default="groupA_different_breeds_buoumao", ) parser.add_argument("--sample_index", type=int, default=3) parser.add_argument("--mesh_object_name", type=str, default="DeformedMesh") parser.add_argument( "--deformed_obj_path", type=str, default=None, help="Optional deformed OBJ. The original mesh is used when omitted.", ) parser.add_argument("--shape_key_name", type=str, default="DeformedShape") parser.add_argument("--shape_key_value", type=float, default=1.0) parser.add_argument("--save_blend_path", type=str, default=None) parser.add_argument("--render_filename", type=str, default=None) parser.add_argument( "--use_shape_key", action="store_true", default=False, help="Use legacy shape-key approach instead of direct vertex overwrite", ) args = parser.parse_args(user_args) if args.obj_path is None: discovered_obj, discovered_deformed = discover_dataset_case( root=ANIMALLIFT_ROOT, species=args.species, group_name=args.group_name, sample_index=args.sample_index, ) args.obj_path = str(discovered_obj) if args.deformed_obj_path is None and discovered_deformed is not None: args.deformed_obj_path = str(discovered_deformed) print(f"obj_path: {args.obj_path}") print(f"mesh_object_name: {args.mesh_object_name}") print(f"deformed_obj_path: {args.deformed_obj_path}") print(f"shape_key_name: {args.shape_key_name}") print(f"shape_key_value: {args.shape_key_value}") print(f"save_blend_path: {args.save_blend_path}") print(f"render_filename: {args.render_filename}") print(f"use_shape_key: {args.use_shape_key}") load_hair_scene_with_deformed_shape( obj_path=args.obj_path, mesh_object_name=args.mesh_object_name, deformed_obj_path=args.deformed_obj_path, shape_key_name=args.shape_key_name, shape_key_value=args.shape_key_value, save_blend_path=args.save_blend_path, use_shape_key=args.use_shape_key, )