diff --git a/figure/README.md b/figure/README.md index 91756a0b..c64ee7e9 100644 --- a/figure/README.md +++ b/figure/README.md @@ -28,13 +28,16 @@ The modules: `mixamorig` and common Blender names). Each pose solves the limbs with the model's own segment lengths to reach the solver's wrists and ankles, keeping its proportions. It scales the model to the solver's leg length and stands - its measured slipper support on the solver's heel/ball contacts. The + its measured barefoot support on the solver's heel/ball contacts. The clavicles lift and move forward with the upper arms. The wrist follows the solver's palm frame and shares part of its axial turn with the forearm. The fingers curl gently unless the technique calls for a fist or hook. Eyes follow cued head turns gently. `FigureModelToon` gives it a cel-shaded look on its own textures. +- `figure_stage` retains the model and renders it to a transparent pixel + buffer with a fixed orthographic camera. It accepts the bundled VRM + bytes and shares the same camera geometry with the preview. The practices' backdrops are in `shared/figure/backdrops/`. The owner's references for the render quality are in `design/reference/`. @@ -48,7 +51,6 @@ for suite in figure_parts_test figure_model_pose_test figure_model_sole_test fig ziran build --project --target=c --exe --entry "$suite:main" -o "build/$suite" "tests/$suite.zi" && "build/$suite/$suite" || exit done -python3 tests/slippers_test.py python3 tests/attire_test.py --source-dir backup/figure-source ``` @@ -59,17 +61,16 @@ missing model file is refused cleanly. `figure_model_pose_test` loads both selected VRM skeletons and checks the rendered hand direction, wrist alignment and planted ankles as the pelvis moves over fixed foot targets. It also checks clavicle motion on a high -reach and sweeps the palm through a full turn at a fixed wrist and elbow. +reach, sweeps the palm through a full turn at a fixed wrist and elbow, +and measures skirt clearance as the forearm sweeps across a low reach. `figure_model_sole_test` measures actual skinned underside vertices for both models during flat stances and heel/ball pivots, with a 1 mm floor, -flatness and pivot limit. `slippers_test.py` validates the shipped CC0 -models, rigid foot weights, matte cloth materials and flat soles; with -`--source-dir` it also proves every original bitmap/accessor byte and every -non-shoe primitive is retained. See `shared/figure/MODELS.md` for the -reproducible footwear pipeline. +flatness and pivot limit. `attire_test.py` checks the soles against the +original CC0 skin mesh and verifies the reconstructed figures' textures, +skeleton and clothing. See `shared/figure/MODELS.md` for reproduction. -`figure_cloth` drapes the skirt hem, resolves leg-capsule contacts and +`figure_cloth` drapes the skirt hem, resolves leg and sleeve contacts and shares displacement across nearby fabric edges. `figure_model` applies those constraints to the named skirt after skinning. The attire generator grades sleeve weights across the elbow and fits the man's shoulder and diff --git a/figure/figure_model.zi b/figure/figure_model.zi index 3877c249..e9c66e8a 100644 --- a/figure/figure_model.zi +++ b/figure/figure_model.zi @@ -106,10 +106,33 @@ FigureFingerRole :: (side: s32, finger: s32, segment: s32) -> s32 { // The model's own animations are not used. False when the file is not a // valid model or has no hips, legs and arms. FigureModelLoad :: (figure: *FigureModel, scene: *Scene, path: string) -> bool { - FigureModelRelease(figure) loaded := GltfReadFile(path) - FigureTakeModel(*figure.model, *loaded) - GltfModelRelease(*loaded) + defer GltfModelRelease(*loaded) + if !FigureModelUse(figure, scene, *loaded) { + return false + } + if VrmReadFile(*figure.avatar, path) { + unused VrmSpringsReset(*figure.avatar, *figure.model, *figure.instance) + } + return true +} + +// Package assets are already in memory on desktop, Android and Web. +FigureModelLoadBytes :: (figure: *FigureModel, scene: *Scene, bytes: []u8) -> bool { + loaded := GltfReadBytes(bytes) + defer GltfModelRelease(*loaded) + if !FigureModelUse(figure, scene, *loaded) { + return false + } + if VrmReadBytes(*figure.avatar, bytes) { + unused VrmSpringsReset(*figure.avatar, *figure.model, *figure.instance) + } + return true +} + +FigureModelUse :: (figure: *FigureModel, scene: *Scene, loaded: *GltfModel) -> bool { + FigureModelRelease(figure) + FigureTakeModel(*figure.model, loaded) if !figure.model.valid || !GltfSceneCreate(scene, *figure.model, *figure.instance) { return false } @@ -201,10 +224,6 @@ FigureModelLoad :: (figure: *FigureModel, scene: *Scene, path: string) -> bool { figure.hand_rest[side] = FigureModelHandRest(figure, side) } FigureModelReadSoles(figure) - // A VRM model's springs start from its rest pose. - if VrmReadFile(*figure.avatar, path) { - unused VrmSpringsReset(*figure.avatar, *figure.model, *figure.instance) - } figure.clock = -1.0 figure.ready = true return true @@ -248,8 +267,8 @@ FigureModelPose :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoints, shin := FigureModelAim(figure, thigh, FigureSideRole(side, FIGURE_LOWER_LEG), FigureSideRole(side, FIGURE_FOOT), FigureSub(joints.ankles[side], joints.knees[side])) turns[FigureSideRole(side, FIGURE_LOWER_LEG)] = shin - // The prepared slipper sole is level at rest. Toe-bone direction - // is anatomical, not the sole plane; aiming it tilted planted shoes. + // The calibrated foot sole is level at rest. Toe-bone direction + // is anatomical, not the sole plane; aiming it tilted planted feet. foot := FigureQuatNormalize(joints.feet[side]) turns[FigureSideRole(side, FIGURE_FOOT)] = foot turns[FigureSideRole(side, FIGURE_TOES)] = foot @@ -295,12 +314,12 @@ FigureModelPose :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoints, } feet_targets[side] = FigureModelSoleTarget(figure, joints, side, scale) } - offset: Vector3 - for side: cast(s32)0..1 { - ankle := FigureScale(FigureRotate(figure.facing, FigureModelPosed(figure, figure.bones[FigureSideRole(side, FIGURE_FOOT)])), - scale) - offset = FigureAdd(offset, FigureScale(FigureSub(feet_targets[side], ankle), 0.5)) - } + // Keep authored pelvis translation. Averaging the ankles inferred from + // rotating model bones shifts the whole root during a weight transfer, + // even when both feet stay planted in the solver. + model_pelvis := FigureScale(FigureRotate(figure.facing, + FigureModelPosed(figure, figure.bones[FIGURE_HIPS])), scale) + offset := FigureSub(joints.pelvis, model_pelvis) // A measured sole changes the ankle target. Keep the pelvis inside // both legs' reach before solving them, including nearly straight // stances where the two avatars' thigh/shin ratios differ. @@ -358,12 +377,57 @@ FigureModelPose :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoints, if !GltfUpdateScene(*figure.model, *figure.instance, scene) { return false } + FigureModelToeContact(figure, scene, joints) FigureModelCloth(figure, scene, joints) return true } +// Let the toes flex along the floor as the heel rises. The surface beyond +// the ball follows the forefoot correction across its whole thickness. +FigureModelToeContact :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoints) { + root := scene.nodes[figure.instance.root_node] + for index: 0..figure.instance.meshes.count - 1 { + inst := *figure.instance.meshes[index] + source := *figure.model.meshes[inst.mesh_index] + if TextView(source.name[:]) != "PracticeBareFeet" { + continue + } + side := inst.primitive_index + turn := FigureQuatNormalize(joints.feet[side]) + up := FigureRotate(turn, .{0.0, 1.0, 0.0}) + if up.y < 0.1 || FigureDistance(joints.heels[side], joints.balls[side]) < 0.01 { + continue + } + heel_down := joints.heels[side].y <= joints.balls[side].y + anchor := ifx heel_down then joints.heels[side] else joints.balls[side] + rest := ifx heel_down then figure.sole_heel[side] else figure.sole_ball[side] + // A lifted leg needs no contact adjustment once its toes clear. + ankle := FigureModelRest(figure, FigureSideRole(side, FIGURE_FOOT), -1) + matrix := figure.instance.node_world[inst.gltf_node] + mesh := scene.meshes[scene.nodes[inst.scene_node].mesh] + local_up := FigureV3(matrix.m[4], matrix.m[5], matrix.m[6]) + slope := FigureDot(local_up, local_up) * root.scale.x + if slope <= 0.000001 { continue } + changed := false + for vertex: 0..inst.skin.positions.count - 1 { + from_ankle := FigureRotate(figure.facing, FigureSub(inst.skin.positions[vertex], ankle)) + from_pivot := FigureV3(from_ankle.x - rest.x, 0.0, + (from_ankle.z - rest.z) * figure.foot_stretch[side]) + level := anchor.y + FigureRotate(turn, FigureScale(from_pivot, root.scale.x)).y + point := *scene.positions[mesh.first_vertex + vertex] + height := root.position.y + (FigureDot(local_up, < 0.0000001 { + < 0.000001 then Atan2(-lateral.z, lateral.x) else Atan2(forward.x, forward.z) cloth_turn := FigureMultiply(FigureAxisAngle(.{0.0, 1.0, 0.0}, yaw), figure.facing) legs: [6]Vector3 + arms: [6]Vector3 + sleeves: [2]bool thighs: [2]Vector3 for side: cast(s32)0..1 { legs[side * 3] = FigureModelWorld(figure, scene, FigureSideRole(side, FIGURE_UPPER_LEG)) legs[side * 3 + 1] = FigureModelWorld(figure, scene, FigureSideRole(side, FIGURE_LOWER_LEG)) legs[side * 3 + 2] = FigureModelWorld(figure, scene, FigureSideRole(side, FIGURE_FOOT)) thighs[side] = FigureNormalize(FigureSub(legs[side * 3 + 1], legs[side * 3])) + upper := FigureSideRole(side, FIGURE_UPPER_ARM) + lower := FigureSideRole(side, FIGURE_LOWER_ARM) + hand := FigureSideRole(side, FIGURE_HAND) + sleeves[side] = figure.bones[upper] >= 0 && figure.bones[lower] >= 0 && figure.bones[hand] >= 0 + if sleeves[side] { + arms[side * 3] = FigureModelWorld(figure, scene, upper) + arms[side * 3 + 1] = FigureModelWorld(figure, scene, lower) + arms[side * 3 + 2] = FigureModelWorld(figure, scene, hand) + } } for index: 0..figure.instance.meshes.count - 1 { inst := *figure.instance.meshes[index] @@ -410,6 +485,15 @@ FigureModelCloth :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoints) point = FigureLerp(point, outside, loose) outside = FigureClothOutside(point, legs[side * 3 + 1], legs[side * 3 + 2], 0.054 * scale, outward) point = FigureLerp(point, outside, loose) + // Loose cloth can reach the forearm in low reaches + // and the upper sleeve during a fold. Resolve both + // against the skinned rig, keeping the waist pinned. + if sleeves[side] { + outside = FigureClothOutside(point, arms[side * 3], arms[side * 3 + 1], 0.071 * scale, outward) + point = FigureLerp(point, outside, loose) + outside = FigureClothOutside(point, arms[side * 3 + 1], arms[side * 3 + 2], 0.062 * scale, outward) + point = FigureLerp(point, outside, loose) + } } } } @@ -492,7 +576,7 @@ FigureGaze :: (joints: *FigureJoints) -> Vector3 { return .{FigureClamp(yaw * 0.2, -8.0, 8.0), FigureClamp(pitch * 0.2, -5.0, 5.0), 0.0} } -// Place the measured shoe support on the solver's actual contact, rather +// Place the measured foot support on the solver's actual contact, rather // than assuming two avatars have the solver's ankle-to-sole dimensions. FigureModelSoleTarget :: (figure: *FigureModel, joints: *FigureJoints, side: s32, scale: float64) -> Vector3 { if figure.sole_count[side] == 0 || FigureDistance(joints.heels[side], joints.balls[side]) < 0.01 { @@ -515,7 +599,7 @@ FigureModelSoleTarget :: (figure: *FigureModel, joints: *FigureJoints, side: s32 return target } -// Measurements from the actual skinned slipper vertices in the scene. +// Measurements from the actual skinned plantar vertices in the scene. // Only contacts on the floor with the sole facing upward are planted. FigureContactMeasure :: struct { vertices: s64 @@ -530,7 +614,7 @@ FigureModelContacts :: (figure: *FigureModel, scene: *Scene, joints: *FigureJoin for index: 0..figure.instance.meshes.count - 1 { inst := *figure.instance.meshes[index] source := *figure.model.meshes[inst.mesh_index] - if TextView(source.name[:]) != "PracticeClothSlippers" { + if !FigureSoleMesh(TextView(source.name[:])) { continue } side := inst.primitive_index @@ -756,14 +840,18 @@ FigureModelRest :: (figure: *FigureModel, role: s32, fallback: s32) -> Vector3 { return ifx node >= 0 then figure.rest_at[node] else Vector3.{} } -// The generated slippers are separate primitives with one rigid foot -// weight. Measure the actual underside vertices; no guessed ankle height. +// The plantars use a rigid foot weight. Measure the actual underside +// vertices to establish the heel and forefoot pivots. +FigureSoleMesh :: (name: string) -> bool { + return name == "PracticeBareFeet" || name == "PracticeClothSlippers" +} + FigureModelReadSoles :: (figure: *FigureModel) { figure.sole_count[0] = 0 figure.sole_count[1] = 0 for mesh_index: 0..figure.model.meshes.count - 1 { mesh := *figure.model.meshes[mesh_index] - if TextView(mesh.name[:]) != "PracticeClothSlippers" || mesh.primitives.count != 2 { + if !FigureSoleMesh(TextView(mesh.name[:])) || mesh.primitives.count != 2 { continue } for side: cast(s32)0..1 { diff --git a/figure/figure_stage.zi b/figure/figure_stage.zi new file mode 100644 index 00000000..e21fa929 --- /dev/null +++ b/figure/figure_stage.zi @@ -0,0 +1,98 @@ +// Retained render-thread scene for presenting a practice figure. +#import "figure_math" +#import "figure_joints" +#import "figure_model" +#import "kryon/scene" +#import "kryon/scene_render" +#import "kryon/drawing_props" +#import "std/math" +#import "std/vec" +Raster :: #import "std/image"; +#if OS == .LINUX || OS == .ANDROID || OS == .WEB { + GPU :: #import "kryon/scene_gpu"; +} + +FigureStage :: struct { + scene: Scene + model: FigureModel + pixels: Raster.Image + #if OS == .LINUX || OS == .ANDROID || OS == .WEB { + gpu: GPU.SceneGpuContext + } +} + +FigureCamera :: (center: Vector3, yaw: float64, pitch: float64, + span: float64, aspect: float64) -> SceneCamera { + half_height := span / 2.0 + half_width := half_height * aspect + toward := FigureV3(Sin(yaw) * Cos(pitch), Sin(pitch), Cos(yaw) * Cos(pitch)) + camera := OrthographicCamera(-half_width, half_width, half_height, -half_height, 0.05, 30.0) + camera.target = center + camera.position = FigureAddScaled(center, toward, 8.0) + camera.up = .{0.0, 1.0, 0.0} + return camera +} + +// Transform the camera inversely so the posed character moves as one body. +FigureCameraPlaced :: (camera: SceneCamera, offset: Vector3, pivot: Vector3, roll: float64) -> SceneCamera { + result := camera + inverse := FigureAxisAngle(.{0.0, 0.0, 1.0}, -roll) + result.target = FigureAdd(pivot, FigureRotate(inverse, FigureSub(FigureSub(camera.target, offset), pivot))) + result.position = FigureAdd(pivot, FigureRotate(inverse, FigureSub(FigureSub(camera.position, offset), pivot))) + result.up = FigureRotate(inverse, camera.up) + return result +} + +FigureStageInit :: (stage: *FigureStage) { + SceneInit(*stage.scene) + stage.scene.background = .{0, 0, 0, 0} + AddHemisphereLight(*stage.scene, .{255, 249, 236, 255}, .{109, 115, 99, 255}, 0.7) + unused AddDirectionalLight(*stage.scene, .{255, 248, 235, 255}, 0.6, .{-3.0, 6.0, 4.0}) +} + +FigureStageFree :: (stage: *FigureStage) { + #if OS == .LINUX || OS == .ANDROID || OS == .WEB { + GPU.SceneGpuRelease(*stage.gpu) + } + FigureModelRelease(*stage.model) + SceneFree(*stage.scene) + VecFree(stage.pixels.pixels) + stage.pixels.width = 0 + stage.pixels.height = 0 +} + +FigureStageRender :: (stage: *FigureStage, joints: *FigureJoints, + camera: SceneCamera, width: s32, height: s32, seconds: float64) -> bool { + if !FigureModelPose(*stage.model, *stage.scene, joints, seconds) { + return false + } + toward := FigureNormalize(FigureSub(camera.position, camera.target)) + yaw := Atan2(toward.x, toward.z) + light := FigureRotate(FigureAxisAngle(.{0.0, 1.0, 0.0}, yaw), .{-0.45, 0.75, 0.55}) + FigureModelLight(*stage.model, light, toward) + if stage.pixels.width != width || stage.pixels.height != height { + if !VecResize(stage.pixels.pixels, cast(s64)width * height * 4) { + return false + } + stage.pixels.width = width + stage.pixels.height = height + } + #if OS == .LINUX || OS == .ANDROID || OS == .WEB { + return GPU.SceneGpuRenderOrCPU(*stage.gpu, *stage.scene, camera, *stage.pixels).ok + } else { + return RenderScene(*stage.scene, camera, *stage.pixels) + } +} + +FigureStageLoadBytes :: (stage: *FigureStage, bytes: []u8) -> bool { + FigureStageInit(stage) + return FigureModelLoadBytes(*stage.model, *stage.scene, bytes) && FigureModelToon(*stage.model, *stage.scene) +} + +FigureStagePaint :: (stage: *FigureStage, joints: *FigureJoints, center: Vector3, + yaw: float64, pitch: float64, span: float64, width: s32, height: s32, seconds: float64, + offset: Vector3, pivot: Vector3, roll: float64) -> bool { + camera := FigureCamera(center, yaw, pitch, span, cast(float64)width / cast(float64)height) + placed := FigureCameraPlaced(camera, offset, pivot, roll) + return FigureStageRender(stage, joints, placed, width, height, seconds) +} diff --git a/figure/tools/prepare_attire.py b/figure/tools/prepare_attire.py index 2ceb8dcc..c8579767 100644 --- a/figure/tools/prepare_attire.py +++ b/figure/tools/prepare_attire.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """Build calm cross-collar meditation clothes on the owner's CC0 VRoid figures. -Starts with prepare_slippers' checksummed originals. Keeps identity, original -texture bytes, skeleton, hair, body and slippers. Reuses the fitted garment +Starts with the checksummed CC0 originals. Keeps identity, original +texture bytes, skeleton, hair and the original skin beneath the shoes. Reuses the fitted garment surface and bind weights, removes the man's hood/cords, relaxes his trousers, and adds real crossed lapel/sash geometry. The woman's flared skirt remains separate so the runtime can drape it under gravity during folds. @@ -15,7 +15,13 @@ from pathlib import Path import struct import numpy as np -from prepare_slippers import prepare, ORIGINAL, COMPONENT, WIDTH +ORIGINAL = { + 'woman': 'adfd242317aaabc773f31f7fff7b013979fbb5baa47e97427a78913d9cb4e979', + 'man': '7aeca142dabbc26ba0f5b9c998c8f3cb6df341287d67788427ac837223785a3f', +} +COMPONENT = {5121: ' 0, axis=1)] + used = np.unique(triangles) + # The source models stand inside slightly elevated shoes. Measure the + # bare heel and forefoot on both sides and remove that ramp below the ankle. + rear = used[(xyz[used, 2] > .016) & (xyz[used, 2] < .063)] + fore = used[(xyz[used, 2] > -.112) & (xyz[used, 2] < -.078)] + heel = rear[xyz[rear, 1].argmin()] + ball = fore[xyz[fore, 1].argmin()] + plane = np.interp(xyz[used, 2], [xyz[ball, 2], xyz[heel, 2]], [xyz[ball, 1], xyz[heel, 1]]) + blend = np.clip((xyz[used, 1] - .086) / .048, 0, 1) + drop = (plane + .0013) * (1 - blend * blend * (3 - 2 * blend)) + xyz[used, 1] = np.maximum(0, xyz[used, 1] - drop) + # Skin on the plantar surface follows the sole affine, while skin at + # the ankle still blends through the original lower-leg weights. + foot_node = next(i for i, node in enumerate(doc['nodes']) if node.get('name') == f'J_Bip_{side}_Foot') + foot = skin['joints'].index(foot_node) + sole = used[xyz[used, 1] < .002] + attrs['JOINTS_0'][sole] = [foot, 0, 0, 0] + attrs['WEIGHTS_0'][sole] = [1, 0, 0, 0] + normals = np.zeros_like(attrs['NORMAL']) + cross = np.cross(xyz[triangles[:, 1]] - xyz[triangles[:, 0]], xyz[triangles[:, 2]] - xyz[triangles[:, 0]]) + for corner in range(3): + np.add.at(normals, triangles[:, corner], cross) + length = np.linalg.norm(normals, axis=1) + # Some UV seams have coincident vertices and zero-area bridge triangles. + valid = used[length[used] > 1e-8] + attrs['NORMAL'][valid] = normals[valid] / length[valid, None] + feet.append(asset.primitive(attrs, triangles, primitive['material'])) + contact = xyz[used][xyz[used, 1] == 0] + if len(contact) < 8 or np.ptp(contact[:, 2]) < .12: + raise ValueError(f'{person} {side}: heel and forefoot do not share the contact plane') + measurements.append({'side': side, 'vertices': len(used), 'triangles': len(triangles), + 'support_vertices': len(contact), 'heel_to_ball': float(np.ptp(contact[:, 2]))}) + if sum(m['triangles'] for m in measurements) != len(src_triangles): + raise ValueError(f'{person}: foot extraction dropped original triangles') + asset.mesh(body_node, 'PracticeBareFeet', feet) + return measurements + + def dress(source, target, person): - slippers = prepare(source, target, person) - asset = Asset(target) + if sha(source) != ORIGINAL[person]: + raise ValueError(f'{source}: expected the original CC0 sample') + asset = Asset(source) d = asset.doc body_node = next(i for i, n in enumerate(d['nodes']) if n.get('name') == 'Body') body = d['meshes'][d['nodes'][body_node]['mesh']] skin = d['skins'][d['nodes'][body_node]['skin']] - skin_parts = [p for p in body['primitives'] if 'SKIN' in d['materials'][p['material']]['name']] + foot_skin = next(p for p in body['primitives'] if is_foot_skin(asset, p)) + measurements = barefoot(asset, body_node, foot_skin, person) + skin_parts = [p for p in body['primitives'] if p is not foot_skin and + 'SKIN' in d['materials'][p['material']]['name']] # The skin and clothes share accessors. Only vertices indexed by skin # primitives belong to the surface we want to fit against. skin_vertices = np.unique(np.concatenate([asset.read(p['indices']) for p in skin_parts])) @@ -253,6 +322,8 @@ def dress(source, target, person): kept, changed, skirt, trims, cloth = [], [], [], [], [] for primitive_index, primitive in enumerate(body['primitives']): name = d['materials'][primitive['material']]['name'] + if primitive is foot_skin or 'Shoes' in name: + continue if 'CLOTH' not in name: kept.append(primitive) continue @@ -336,10 +407,10 @@ def dress(source, target, person): asset.mesh(body_node, 'PracticeWrapFacings', trims) # Removed hood springs have no visible geometry; keep skeleton compatibility. asset.save(target) - slippers['output_sha256'] = sha(target) - return slippers, {'source_sha256': ORIGINAL[person], 'output_sha256': sha(target), + return {'source_sha256': ORIGINAL[person], 'output_sha256': sha(target), + 'bare_feet': measurements, 'changed_body_primitives': changed, 'skirt_preserved': person == 'woman', - 'identity': 'Original face, hair, body, skeleton and flat slippers retained', + 'identity': 'Original face, hair, body, skeleton and bare feet retained', 'style': 'Matte linen cross-collar wrap, plain sash and flared skirt' if person == 'woman' else 'Matte linen cross-collar tunic and relaxed trousers; hood/cord meshes removed'} @@ -349,12 +420,11 @@ def main(): parser.add_argument('--source-dir', required=True, type=Path) parser.add_argument('--output-dir', default=Path('shared/figure'), type=Path) args = parser.parse_args() - slippers, attire = {}, {} + attire = {} for person in ORIGINAL: - slippers[person], attire[person] = dress(args.source_dir / f'{person}.vrm', args.output_dir / f'{person}.vrm', person) - (args.output_dir / 'slippers.json').write_text(json.dumps(slippers, indent=2) + '\n') + attire[person] = dress(args.source_dir / f'{person}.vrm', args.output_dir / f'{person}.vrm', person) (args.output_dir / 'attire.json').write_text(json.dumps(attire, indent=2) + '\n') - print('Prepared both traditional-inspired meditation outfits; original CC0 identities and flat slippers retained') + print('Prepared both traditional-inspired meditation outfits; original CC0 identities and bare feet retained') if __name__ == '__main__': diff --git a/figure/tools/prepare_slippers.py b/figure/tools/prepare_slippers.py deleted file mode 100644 index c35ab4a0..00000000 --- a/figure/tools/prepare_slippers.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Replace only the CC0 samples' shoe primitives with simple cloth slippers. - -Inputs must be the unmodified, checksummed VRoid samples (see MODELS.md). -Textures, body/clothing/hair geometry, skeleton, expressions and springs -are retained byte for byte. New slippers have one flat sole plane, no heel, -and rigid foot weights so heel/ball pivots preserve that measured plane. -""" -import argparse -import hashlib -import json -import math -from pathlib import Path -import struct - -import numpy as np - -ORIGINAL = { - 'woman': 'adfd242317aaabc773f31f7fff7b013979fbb5baa47e97427a78913d9cb4e979', - 'man': '7aeca142dabbc26ba0f5b9c998c8f3cb6df341287d67788427ac837223785a3f', -} -COMPONENT = {5121: ' 0 else -1 - points = original_points[original_points[:, 0] * sign > 0] - lower, upper = points.min(axis=0), points.max(axis=0) - center_x = float((lower[0] + upper[0]) / 2) - center_z = float((lower[2] + upper[2]) / 2) - half_width = float((upper[0] - lower[0]) / 2) * .94 - half_length = float((upper[2] - lower[2]) / 2) * .96 - positions, indices = [], [] - # Thin flat underside, rounded cloth upper. No platform or heel block. - for ring in range(7): - angle = (ring - 1) / 5 * math.pi / 2 if ring > 0 else 0 - radius = math.cos(angle) if ring > 0 else 1 - height = .003 + .054 * math.sin(angle) if ring > 0 else 0 - for segment in range(segments): - theta = 2 * math.pi * segment / segments - # Toe is slightly broader than the heel, without a pointed tip. - width = half_width * (1 - .12 * math.cos(theta)) - positions.append([center_x + math.sin(theta) * width * radius, - height, center_z + math.cos(theta) * half_length * radius]) - positions.append([center_x, 0, center_z]) - center = len(positions) - 1 - for segment in range(segments): - after = (segment + 1) % segments - indices.extend([center, after, segment]) - for ring in range(6): - a, b = ring * segments + segment, ring * segments + after - c, d = a + segments, b + segments - indices.extend([a, b, c, b, d, c]) - positions = np.array(positions) - # Derive smooth normals from the generated triangles. - normals = np.zeros_like(positions) - for a, b, c in np.array(indices).reshape(-1, 3): - normal = np.cross(positions[b] - positions[a], positions[c] - positions[a]) - normals[[a, b, c]] += normal - lengths = np.linalg.norm(normals, axis=1) - normals[lengths > 0] /= lengths[lengths > 0, None] - joints = [[joint, 0, 0, 0]] * len(positions) - weights = [[1, 0, 0, 0]] * len(positions) - slippers['primitives'].append({'attributes': { - 'POSITION': append(positions, 5126, 'VEC3'), 'NORMAL': append(normals, 5126, 'VEC3'), - 'JOINTS_0': append(joints, 5123, 'VEC4'), 'WEIGHTS_0': append(weights, 5126, 'VEC4')}, - 'indices': append(np.array(indices).reshape(-1, 1), 5123, 'SCALAR'), 'material': material, 'mode': 4}) - measurements.append({'side': side, 'vertices': len(positions), 'sole_height': 0, - 'sole_flatness': 0, 'heel': [center_x, 0, center_z + half_length], - 'ball': [center_x, 0, center_z - half_length], - 'original_shoe_height': float(upper[1] - lower[1]), 'upper_height': .057}) - mesh_index = len(doc['meshes']) - doc['meshes'].append(slippers) - new_node = len(doc['nodes']) - # Preserve the source mesh-node transform and skin binding exactly. - doc['nodes'].append({**node, 'name': 'PracticeClothSlippers', 'mesh': mesh_index}) - parent = next((n for n in doc['nodes'][:new_node] if body_node in n.get('children', [])), None) - if parent is not None: - parent['children'].append(new_node) - else: - for scene in doc['scenes']: - if body_node in scene['nodes']: - scene['nodes'].append(new_node) - binary.extend(b'\0' * (-len(binary) % 4)) - doc['buffers'][0]['byteLength'] = len(binary) - encoded = json.dumps(doc, separators=(',', ':'), ensure_ascii=False).encode() - encoded += b' ' * (-len(encoded) % 4) - target.parent.mkdir(parents=True, exist_ok=True) - with target.open('wb') as stream: - stream.write(struct.pack(' 0, axis=1)] + indices = new.read(primitive['indices']).reshape(-1, 3) + assert len(indices) == len(expected) == receipt['triangles'] + assert len(np.unique(indices)) == receipt['vertices'] + attrs = {name: new.read(accessor) for name, accessor in primitive['attributes'].items()} + position = attrs['POSITION'] + assert np.array_equal(position[indices][..., [0, 2]], source['POSITION'][expected][..., [0, 2]]) + assert np.array_equal(attrs['TEXCOORD_0'][indices], source['TEXCOORD_0'][expected]) + assert np.isfinite(position).all() and np.isfinite(attrs['NORMAL']).all() + assert np.allclose(np.linalg.norm(attrs['NORMAL'], axis=1), 1, atol=1e-5) + assert np.allclose(attrs['WEIGHTS_0'].sum(1), 1, atol=1e-5) + used = np.unique(indices) + assert position[used, 1].min() == 0 + contact = used[position[used, 1] == 0] + assert len(contact) == receipt['support_vertices'] >= 8 + assert .12 < np.ptp(position[contact, 2]) == receipt['heel_to_ball'] + assert np.all(attrs['WEIGHTS_0'][contact] == [1, 0, 0, 0]) def main(): @@ -33,9 +60,11 @@ def main(): assert {k: v for k, v in node.items() if k != 'children'} == {k: v for k, v in d['nodes'][i].items() if k != 'children'} assert d['nodes'][i].get('children', [])[:len(node.get('children', []))] == node.get('children', []) for i, mesh in enumerate(o['meshes']): - expected = [p for p in mesh['primitives'] if 'CLOTH' not in o['materials'][p['material']]['name']] + expected = [p for p in mesh['primitives'] + if 'CLOTH' not in o['materials'][p['material']]['name'] and not is_foot_skin(old, p)] actual = [p for p in d['meshes'][i]['primitives'] if not d['materials'][p['material']]['name'].startswith('Practice_')] assert actual == expected, (person, mesh.get('name')) + verify_feet(old, new, receipts[person]['bare_feet']) garments = [] for mesh in d['meshes']: for primitive in mesh['primitives']: @@ -66,7 +95,7 @@ def main(): a = primitive['attributes'] joints, weights = new.read(a['JOINTS_0']), new.read(a['WEIGHTS_0']) assert np.max(np.where(np.isin(joints, hood), weights, 0)) < .01 - print(f'{person}: real linen wrap geometry, identity/CC0/texture/skeleton preserved; skirt retained or hood removed') + print(f'{person}: real linen wrap geometry, original barefoot topology, textures and level soles; CC0 and skeleton preserved') if __name__ == '__main__': diff --git a/tests/figure_model_pose_test.zi b/tests/figure_model_pose_test.zi index 95c6a1e2..b953351a 100644 --- a/tests/figure_model_pose_test.zi +++ b/tests/figure_model_pose_test.zi @@ -2,6 +2,8 @@ #import "figure_math" #import "figure_joints" #import "figure_model" +#import "figure_cloth" +#import "std/byte_text_linux" #import "kryon/scene" #import "kryon/scene_gltf" #import "std/math" @@ -101,6 +103,40 @@ ArmMotion :: (model: *FigureModel, scene: *Scene, path: string) -> bool { return shoulder_change > 0.12 && shoulder_change < 0.24 && largest_step < 0.18 && largest_turn > 0.45 } +SleeveContact :: (model: *FigureModel, scene: *Scene) -> bool { + pose := ModelPose(0.0) + // Sweep a sleeve close to the front skirt panel during a low reach. + min_gap: float64 = 1.0 + measured: s64 + for sample: 0..16 { + pose.elbows[0] = .{0.20, 0.82, 0.22} + pose.wrists[0] = .{0.18, 0.68, 0.21 + 0.05 * cast(float64)sample / 16.0} + if !FigureModelPose(model, scene, *pose) { return false } + elbow := ModelPoint(model, scene, FigureSideRole(0, FIGURE_LOWER_ARM)) + wrist := ModelPoint(model, scene, FigureSideRole(0, FIGURE_HAND)) + root := scene.nodes[model.instance.root_node] + for index: 0..model.instance.meshes.count - 1 { + inst := *model.instance.meshes[index] + source := *model.model.meshes[inst.mesh_index] + if TextView(source.name[:]) != "PracticeSkirt" { continue } + mesh := scene.meshes[scene.nodes[inst.scene_node].mesh] + rest_hips := model.rest_at[model.bones[FIGURE_HIPS]] + radius := 0.062 * root.scale.x + for vertex: 0..inst.skin.positions.count - 1 { + if rest_hips.y - inst.skin.positions[vertex].y < 0.10 { continue } + point := FigureAdd(root.position, FigureScale(FigureRotate(model.facing, + scene.positions[mesh.first_vertex + vertex]), root.scale.x)) + restored := FigureClothOutside(point, elbow, wrist, radius, .{1.0, 0.0, 0.0}) + gap := FigureDistance(restored, point) + min_gap = FigureMin(min_gap, radius - gap) + measured += 1 + } + } + } + print("skirt/sleeve contact: % skirt vertices sampled, minimum sleeve radius clearance % m\n", measured, min_gap) + return measured >= 17 * 100 && min_gap >= 0.060 * scene.nodes[model.instance.root_node].scale.x +} + main :: () -> s32 { fail: s32 paths: [2]string = .["shared/figure/woman.vrm", "shared/figure/man.vrm"] @@ -114,6 +150,7 @@ main :: () -> s32 { print("model pose: could not load %\n", path) return 1 } + worst_pelvis: float64 worst_ankle: float64 worst_drift: float64 worst_hand: float64 @@ -124,6 +161,8 @@ main :: () -> s32 { if !FigureModelPose(*model, *scene, *pose) { return 1 } + pelvis := ModelPoint(*model, *scene, FIGURE_HIPS) + worst_pelvis = FigureMax(worst_pelvis, FigureDistance(pelvis, pose.pelvis)) for side: cast(s32)0..1 { ankle := ModelPoint(*model, *scene, FigureSideRole(side, FIGURE_FOOT)) if sample == 0 { @@ -139,9 +178,12 @@ main :: () -> s32 { worst_hand = FigureMax(worst_hand, FigureDistance(pointing, wanted)) } } - print("model pose: % ankle error % m, planted drift % m, wrist error % m, hand direction error %\n", - path, worst_ankle, worst_drift, worst_wrist, worst_hand) - if worst_ankle > 0.0001 || worst_drift > 0.0001 || worst_wrist > 0.0001 || worst_hand > 0.001 { + print("model pose: % pelvis error % m, ankle error % m, planted drift % m, wrist error % m, hand direction error %\n", + path, worst_pelvis, worst_ankle, worst_drift, worst_wrist, worst_hand) + if worst_pelvis > 0.0001 || worst_ankle > 0.0001 || worst_drift > 0.0001 || worst_wrist > 0.0001 || worst_hand > 0.001 { + fail += 1 + } + if path == paths[0] && !SleeveContact(*model, *scene) { fail += 1 } if !ArmMotion(*model, *scene, path) { diff --git a/tests/figure_model_sole_test.zi b/tests/figure_model_sole_test.zi index 93f051bb..c0d9d505 100644 --- a/tests/figure_model_sole_test.zi +++ b/tests/figure_model_sole_test.zi @@ -1,4 +1,4 @@ -// Measure the rendered, skinned slipper vertices, not ankle-bone guesses. +// Measure the rendered, skinned plantar vertices, not ankle-bone guesses. #import "figure_math" #import "figure_joints" #import "figure_model" @@ -17,6 +17,7 @@ SoleWorld :: (figure: *FigureModel, matrix: GltfMatrix, point: Vector3, scene: * SoleCheck :: (figure: *FigureModel, scene: *Scene, path: string) -> s32 { worst_gap: float64 + worst_penetration: float64 worst_flat: float64 worst_pivot: float64 measured: s64 @@ -59,7 +60,7 @@ SoleCheck :: (figure: *FigureModel, scene: *Scene, path: string) -> s32 { for mesh_index: 0..figure.instance.meshes.count - 1 { inst := *figure.instance.meshes[mesh_index] source_mesh := *figure.model.meshes[inst.mesh_index] - if TextView(source_mesh.name[:]) != "PracticeClothSlippers" { + if TextView(source_mesh.name[:]) != "PracticeBareFeet" { continue } side := inst.primitive_index @@ -72,11 +73,12 @@ SoleCheck :: (figure: *FigureModel, scene: *Scene, path: string) -> s32 { ball: Vector3 for vertex: 0..inst.skin.positions.count - 1 { rest := inst.skin.positions[vertex] + actual := SoleWorld(figure, figure.instance.node_world[inst.gltf_node], + scene.positions[mesh.first_vertex + vertex], scene) + worst_penetration = FigureMax(worst_penetration, -actual.y) if FigureAbs(rest.y) > 0.000001 { continue } - actual := SoleWorld(figure, figure.instance.node_world[inst.gltf_node], - scene.positions[mesh.first_vertex + vertex], scene) low = FigureMin(low, actual.y) high = FigureMax(high, actual.y) facing := FigureRotate(figure.facing, rest) @@ -94,15 +96,16 @@ SoleCheck :: (figure: *FigureModel, scene: *Scene, path: string) -> s32 { if mode == 0 || mode == 3 { worst_flat = FigureMax(worst_flat, high - low) } - actual := ifx mode == 2 then ball else heel - target := ifx mode == 2 then pose.balls[side] else pose.heels[side] + heel_down := pose.heels[side].y <= pose.balls[side].y + actual := ifx heel_down then heel else ball + target := ifx heel_down then pose.heels[side] else pose.balls[side] worst_pivot = FigureMax(worst_pivot, FigureDistance(actual, target)) } } } - print("sole test: % vertices %, floor error % m, flatness % m, heel/ball pivot error % m\n", - path, measured, worst_gap, worst_flat, worst_pivot) - return ifx measured < 1000 || worst_gap >= 0.001 || worst_flat >= 0.001 || worst_pivot >= 0.001 then 1 else 0 + print("sole test: % vertices %, floor error % m, skin penetration % m, flatness % m, heel/ball pivot error % m\n", + path, measured, worst_gap, worst_penetration, worst_flat, worst_pivot) + return ifx measured < 1000 || worst_gap >= 0.001 || worst_penetration >= 0.001 || worst_flat >= 0.001 || worst_pivot >= 0.001 then 1 else 0 } main :: () -> s32 { @@ -110,14 +113,16 @@ main :: () -> s32 { paths: [2]string = .["shared/figure/woman.vrm", "shared/figure/man.vrm"] model: FigureModel defer FigureModelRelease(*model) - for path: paths { + expected: [2]s32 = .[36, 8] + for index: 0..paths.count - 1 { + path := paths[index] scene: Scene SceneInit(*scene) defer SceneFree(*scene) if !FigureModelLoad(*model, *scene, path) { return 1 } - if model.sole_count[0] != 33 || model.sole_count[1] != 33 { + if model.sole_count[0] != expected[index] || model.sole_count[1] != expected[index] { print("sole test: stale measurements after loading %\n", path) return 1 } diff --git a/tests/slippers_test.py b/tests/slippers_test.py deleted file mode 100644 index 888c4030..00000000 --- a/tests/slippers_test.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -"""Validate the shipped slipper geometry, skin bindings and CC0 metadata.""" -import argparse -import hashlib -import json -from pathlib import Path -import struct -import numpy as np - - -def load(path): - with path.open('rb') as stream: - assert struct.unpack('