Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

initial pass at adding an arm weight corrector

Scott Petrovic9064b1316ffe
diff --git a/src/Mesh2MotionEngine.ts b/src/Mesh2MotionEngine.ts
index 4cbb7da..241687b 100644
--- a/src/Mesh2MotionEngine.ts
+++ b/src/Mesh2MotionEngine.ts
@@ -637,6 +637,12 @@ export class Mesh2MotionEngine {
this.edit_skeleton_step.get_preview_plane_height()
)
+ // Pass arm plane correction settings to the weight skin step
+ this.weight_skin_step.set_arm_plane_correction_settings(
+ this.edit_skeleton_step.use_arm_plane_correction(),
+ this.edit_skeleton_step.get_arm_plane_offset()
+ )
+
this.weight_skin_step.create_binding_skeleton()
// add geometry data needed for skinning
@@ -673,6 +679,12 @@ export class Mesh2MotionEngine {
this.edit_skeleton_step.use_head_weight_correction(),
this.edit_skeleton_step.get_preview_plane_height()
)
+
+ // Pass arm plane correction settings to the weight skin step
+ this.weight_skin_step.set_arm_plane_correction_settings(
+ this.edit_skeleton_step.use_arm_plane_correction(),
+ this.edit_skeleton_step.get_arm_plane_offset()
+ )
}
public show_contributors_dialog (): void {
diff --git a/src/create.html b/src/create.html
index 0033e34..d77532a 100644
--- a/src/create.html
+++ b/src/create.html
@@ -297,6 +297,23 @@
<hr />
</div>
+ <!-- Arm plane controls -->
+ <div id="use-arm-plane-container" style="display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 1rem;">
+ <div class="styled-checkbox">
+ <input type="checkbox" id="arm-plane-checkbox" />
+ <label for="arm-plane-checkbox">Use Arm Plane Correction</label>
+
+ <img data-tippy-content="If the arms are grabbing weights from the torso (common when arms point down in an A-pose), use a divider to define where the arm area starts." src="images/icons/help.svg" alt="Help" width="20" height="20" />
+
+ </div>
+ <div id="arm-plane-setting-container" style="display: flex; align-items: center; gap: 0.5rem;">
+ <label for="arm-plane-offset-input">Distance:</label>
+ <input type="range" id="arm-plane-offset-input" min="-0.50" max="0.50" step="0.01" value="0.00" />
+ <span id="arm-plane-offset-label" style="width: 2rem;">0.00</span>
+ </div>
+ <hr />
+ </div>
+
<!-- back to load skeleton -->
<div class="display: flex; gap: 0.5rem;">
<button class="no-style-button" id="action_back_to_load_skeleton">&#x2039; Back</button>
diff --git a/src/lib/UI.ts b/src/lib/UI.ts
index a375b7d..9c565f0 100644
--- a/src/lib/UI.ts
+++ b/src/lib/UI.ts
@@ -61,6 +61,13 @@ export class UI {
dom_preview_plane_height_label: HTMLElement | null = null
dom_preview_plane_setting_container: HTMLElement | null = null
+ // arm plane controls
+ dom_use_arm_plane_container: HTMLElement | null = null
+ dom_arm_plane_checkbox: HTMLInputElement | null = null
+ dom_arm_plane_offset_input: HTMLInputElement | null = null
+ dom_arm_plane_offset_label: HTMLElement | null = null
+ dom_arm_plane_setting_container: HTMLElement | null = null
+
dom_skinned_mesh_tools: HTMLElement | null = null
dom_skinned_mesh_animation_tools: HTMLElement | null = null
dom_back_to_edit_skeleton_button: HTMLButtonElement | null = null
@@ -184,6 +191,13 @@ export class UI {
this.dom_preview_plane_height_label = document.querySelector('#preview-plane-height-label')
this.dom_preview_plane_setting_container = document.querySelector('#preview-plane-setting-container')
+ // arm plane controls
+ this.dom_use_arm_plane_container = document.querySelector('#use-arm-plane-container')
+ this.dom_arm_plane_checkbox = document.querySelector('#arm-plane-checkbox')
+ this.dom_arm_plane_offset_input = document.querySelector('#arm-plane-offset-input')
+ this.dom_arm_plane_offset_label = document.querySelector('#arm-plane-offset-label')
+ this.dom_arm_plane_setting_container = document.querySelector('#arm-plane-setting-container')
+
this.dom_bind_pose_button = document.querySelector('#action_bind_pose')
// this.dom_scale_skeleton_input_box = document.querySelector('#scale-input')
this.dom_move_to_origin_button = document.querySelector('#action_move_to_origin')
diff --git a/src/lib/Utilities.ts b/src/lib/Utilities.ts
index f5e6c3c..f2fe32f 100644
--- a/src/lib/Utilities.ts
+++ b/src/lib/Utilities.ts
@@ -117,6 +117,24 @@ export class Utility {
return name.includes('leaf') || name.includes('tip')
}
+ /**
+ * The point halfway between a bone's start joint and its first child's joint.
+ * This is the reference point the skinning solvers measure vertex distances
+ * against — a bone's "center of mass" rather than its start joint, which
+ * keeps long bones from losing vertices to their neighbors.
+ * Childless bones fall back to their own world position.
+ */
+ static bone_midpoint_to_child (bone: Bone): Vector3 {
+ const bone_position = Utility.world_position_from_object(bone)
+ if (bone.children.length === 0) {
+ return bone_position.clone()
+ }
+ // Assume first child is the relevant one
+ const child = bone.children[0] as Bone
+ const child_position = Utility.world_position_from_object(child)
+ return new Vector3().lerpVectors(bone_position, child_position, 0.5)
+ }
+
static bone_list_from_hierarchy (bone_hierarchy: Object3D): Bone[] {
if (bone_hierarchy === undefined || bone_hierarchy === null) {
console.warn('bone_hierarchy is undefined or null')
diff --git a/src/lib/processes/edit-skeleton/ArmPlaneManager.ts b/src/lib/processes/edit-skeleton/ArmPlaneManager.ts
new file mode 100644
index 0000000..6b258b9
--- /dev/null
+++ b/src/lib/processes/edit-skeleton/ArmPlaneManager.ts
@@ -0,0 +1,145 @@
+import { Group, Mesh, PlaneGeometry, MeshBasicMaterial, type Scene, DoubleSide } from 'three'
+
+/**
+ * ArmPlaneManager - manages the pair of mirrored vertical planes that show where
+ * the arm weight correction cuts off during the edit skeleton step.
+ *
+ * Unlike PreviewPlaneManager (one horizontal plane, singleton) this owns two
+ * planes at +X and -X, so it is a plain class instantiated by the step that
+ * needs it.
+ */
+export class ArmPlaneManager {
+ private readonly arm_plane_group_name: string = 'arm_plane_group'
+
+ // State tracking
+ private scene_ref: Scene | null = null
+ private plane_group: Group | null = null
+ private left_plane_mesh: Mesh | null = null
+ private right_plane_mesh: Mesh | null = null
+ private current_plane_x: number = 0.0
+ private current_center_y: number = 0.0
+ private current_center_z: number = 0.0
+ private readonly plane_size: number = 2.0
+ private is_visible: boolean = false
+
+ /**
+ * Initialize the manager with a scene reference
+ * @param scene The main scene
+ */
+ public initialize (scene: Scene): void {
+ this.scene_ref = scene
+ }
+
+ /**
+ * Set the visibility of the arm planes. Creates them on demand and removes
+ * them when hidden, so nothing lingers in the scene between steps.
+ */
+ public set_visibility (visible: boolean): void {
+ if (visible && !this.is_visible) {
+ this.add_planes()
+ } else if (!visible && this.is_visible) {
+ this.remove_planes()
+ }
+ }
+
+ /**
+ * Move the planes to a new distance from the center line. The planes are
+ * centered on the shoulder joint's height/depth so they sit over the torso.
+ *
+ * State is stored even when the planes are hidden, so callers can update the
+ * position before or after toggling visibility.
+ */
+ public update_position (plane_x: number, center_y: number, center_z: number): void {
+ this.current_plane_x = plane_x
+ this.current_center_y = center_y
+ this.current_center_z = center_z
+
+ if (this.left_plane_mesh !== null && this.right_plane_mesh !== null) {
+ this.left_plane_mesh.position.set(-plane_x, center_y, center_z)
+ this.right_plane_mesh.position.set(plane_x, center_y, center_z)
+ }
+ }
+
+ public is_plane_visible (): boolean {
+ return this.is_visible
+ }
+
+ /**
+ * Remove both planes from the scene and dispose their resources
+ */
+ public remove_planes (): void {
+ if (this.plane_group !== null && this.scene_ref !== null) {
+ [this.left_plane_mesh, this.right_plane_mesh].forEach((plane_mesh) => {
+ if (plane_mesh === null) return
+ plane_mesh.geometry.dispose()
+ if (plane_mesh.material instanceof MeshBasicMaterial) {
+ plane_mesh.material.dispose()
+ }
+ })
+
+ this.scene_ref.remove(this.plane_group)
+ }
+
+ this.plane_group = null
+ this.left_plane_mesh = null
+ this.right_plane_mesh = null
+ this.is_visible = false
+ }
+
+ /**
+ * Clean up all resources and reset state
+ */
+ public cleanup (): void {
+ this.remove_planes()
+ this.scene_ref = null
+ this.current_plane_x = 0.0
+ this.current_center_y = 0.0
+ this.current_center_z = 0.0
+ this.is_visible = false
+ }
+
+ /**
+ * Build the two vertical planes at the currently stored position
+ */
+ private add_planes (): void {
+ if (this.scene_ref === null) {
+ throw new Error('ArmPlaneManager not initialized with scene reference')
+ }
+
+ this.remove_planes()
+
+ this.plane_group = new Group()
+ this.plane_group.name = this.arm_plane_group_name
+
+ this.left_plane_mesh = this.create_plane_mesh('arm_plane_left')
+ this.right_plane_mesh = this.create_plane_mesh('arm_plane_right')
+
+ this.plane_group.add(this.left_plane_mesh)
+ this.plane_group.add(this.right_plane_mesh)
+ this.scene_ref.add(this.plane_group)
+
+ this.is_visible = true
+
+ // apply the stored position to the freshly created meshes
+ this.update_position(this.current_plane_x, this.current_center_y, this.current_center_z)
+ }
+
+ private create_plane_mesh (name: string): Mesh {
+ const geometry = new PlaneGeometry(this.plane_size, this.plane_size)
+ const material = new MeshBasicMaterial({
+ color: 0x3399ff, // blue, to distinguish from the green head weight correction plane
+ transparent: true,
+ opacity: 0.5,
+ side: DoubleSide,
+ wireframe: false
+ })
+
+ const plane_mesh = new Mesh(geometry, material)
+ plane_mesh.name = name
+
+ // rotate so the plane's normal points along X (a vertical wall facing sideways)
+ plane_mesh.rotation.y = Math.PI / 2
+
+ return plane_mesh
+ }
+}
diff --git a/src/lib/processes/edit-skeleton/StepEditSkeleton.ts b/src/lib/processes/edit-skeleton/StepEditSkeleton.ts
index 192fa7c..2ad2ae6 100644
--- a/src/lib/processes/edit-skeleton/StepEditSkeleton.ts
+++ b/src/lib/processes/edit-skeleton/StepEditSkeleton.ts
@@ -3,6 +3,8 @@ import { Generators } from '../../Generators.ts'
import { Utility } from '../../Utilities.ts'
import { UndoRedoSystem } from './UndoRedoSystem.ts'
import { PreviewPlaneManager } from './PreviewPlaneManager.ts'
+import { ArmPlaneManager } from './ArmPlaneManager.ts'
+import { ArmWeightCorrector } from '../../solvers/ArmWeightCorrector.ts'
import { IndependentBoneMovement } from './IndependentBoneMovement.ts'
import { ModalDialog } from '../../ModalDialog.ts'
import {
@@ -53,10 +55,16 @@ export class StepEditSkeleton extends EventTarget {
private enable_head_weight_correction: boolean = false
private head_weight_correction_height: number = 1.4 // default
+ // Arm plane state. The offset is relative to the shoulder joint's X position,
+ // so it has to match the default in create.html's slider.
+ private enable_arm_plane_correction: boolean = false
+ private arm_plane_offset: number = 0.0
+
private readonly joint_texture = new TextureLoader().load('/images/skeleton-joint-point.png')
private _added_event_listeners: boolean = false
private readonly preview_plane_manager: PreviewPlaneManager = PreviewPlaneManager.getInstance()
+ private readonly arm_plane_manager: ArmPlaneManager = new ArmPlaneManager()
public readonly independent_bone_movement: IndependentBoneMovement = new IndependentBoneMovement()
// UI elements specific for this area
@@ -117,10 +125,21 @@ export class StepEditSkeleton extends EventTarget {
}
}
+ // only human skeletons have the arm plane correction option
+ if (this.ui.dom_use_arm_plane_container != null) {
+ if (skeleton_type === SkeletonType.Human) {
+ this.ui.dom_use_arm_plane_container.style.display = 'block'
+ } else {
+ this.ui.dom_use_arm_plane_container.style.display = 'none'
+ this.enable_arm_plane_correction = false // force setting to false in case it was enabled before
+ }
+ }
+
this.update_skeleton_template_image(skeleton_type)
// show/hide settings for the head correct depending on if it is checked
this.show_preview_plane_options()
+ this.show_arm_plane_options()
}
private update_skeleton_template_image(skeleton_type: SkeletonType): void {
@@ -204,6 +223,47 @@ export class StepEditSkeleton extends EventTarget {
)
this.initialize_preview_plane(main_scene)
+ this.initialize_arm_plane(main_scene)
+ }
+
+ private initialize_arm_plane (main_scene: Scene): void {
+ this.arm_plane_manager.initialize(main_scene)
+
+ // off by default, but can be enabled if we navigate back to the step
+ this.arm_plane_manager.set_visibility(this.enable_arm_plane_correction)
+ this.refresh_arm_plane_position()
+
+ // set default value (and label) for arm plane offset on UI
+ if (this.ui.dom_arm_plane_offset_input !== null && this.ui.dom_arm_plane_offset_label !== null) {
+ this.ui.dom_arm_plane_offset_input.value = this.arm_plane_offset.toString()
+ this.ui.dom_arm_plane_offset_label.textContent = this.arm_plane_offset.toFixed(2)
+ }
+
+ // the checkbox is forced off for non-human rigs, so keep the DOM in sync
+ // with our state instead of leaving a checked box next to a hidden slider
+ if (this.ui.dom_arm_plane_checkbox !== null) {
+ this.ui.dom_arm_plane_checkbox.checked = this.enable_arm_plane_correction
+ }
+ }
+
+ /**
+ * Move the arm planes to wherever the shoulder joint currently is, plus the
+ * user's offset. The solver derives its plane the same way at skin time, so
+ * what the user sees here is what actually gets applied.
+ */
+ private refresh_arm_plane_position (): void {
+ const bones = this.threejs_skeleton.bones
+ if (bones.length === 0) { return }
+
+ const anchor_x = ArmWeightCorrector.shoulder_anchor_x(bones)
+ if (anchor_x === null) { return } // no arm bones on this rig
+
+ const shoulder_bone = ArmWeightCorrector.find_shoulder_bone(bones)
+ const shoulder_position = shoulder_bone === undefined
+ ? new Vector3()
+ : Utility.world_position_from_object(shoulder_bone)
+
+ this.arm_plane_manager.update_position(anchor_x + this.arm_plane_offset, shoulder_position.y, shoulder_position.z)
}
private initialize_preview_plane (main_scene: Scene): void {
@@ -351,6 +411,32 @@ export class StepEditSkeleton extends EventTarget {
return this.head_weight_correction_height
}
+ /**
+ * Toggle the arm plane correction and the planes that visualize it
+ */
+ public set_use_arm_plane_correction (is_enabled: boolean): void {
+ this.enable_arm_plane_correction = is_enabled
+ this.arm_plane_manager.set_visibility(is_enabled)
+ this.refresh_arm_plane_position()
+ }
+
+ public use_arm_plane_correction (): boolean {
+ return this.enable_arm_plane_correction
+ }
+
+ /**
+ * Set how far the arm plane sits from the shoulder joint
+ * @param offset Distance along X to add to the shoulder joint position
+ */
+ public set_arm_plane_offset (offset: number): void {
+ this.arm_plane_offset = offset
+ this.refresh_arm_plane_position()
+ }
+
+ public get_arm_plane_offset (): number {
+ return this.arm_plane_offset
+ }
+
public add_event_listeners (): void {
if (this.ui.dom_move_to_origin_button !== null) {
this.ui.dom_move_to_origin_button.addEventListener('click', () => {
@@ -434,6 +520,30 @@ export class StepEditSkeleton extends EventTarget {
this.ui.dom_preview_plane_height_label.textContent = this.head_weight_correction_height.toFixed(2)
}
})
+
+ // Add arm plane event listeners
+ this.ui.dom_arm_plane_checkbox?.addEventListener('change', (event) => {
+ const target = event.target as HTMLInputElement
+ this.set_use_arm_plane_correction(target.checked)
+
+ this.show_arm_plane_options()
+ })
+
+ this.ui.dom_arm_plane_offset_input?.addEventListener('input', (event) => {
+ const target = event.target as HTMLInputElement
+ const offset = parseFloat(target.value)
+ this.set_arm_plane_offset(isNaN(offset) ? 0.00 : offset)
+
+ // Update the label to show current value
+ if (this.ui.dom_arm_plane_offset_label !== null) {
+ this.ui.dom_arm_plane_offset_label.textContent = this.arm_plane_offset.toFixed(2)
+ }
+ })
+
+ // keep the arm planes anchored to the shoulder joint when bones get moved
+ this.addEventListener('skeletonTransformed', () => {
+ this.refresh_arm_plane_position()
+ })
}
private show_preview_plane_options (): void {
@@ -442,6 +552,12 @@ export class StepEditSkeleton extends EventTarget {
}
}
+ private show_arm_plane_options (): void {
+ if (this.ui.dom_arm_plane_setting_container !== null) {
+ this.ui.dom_arm_plane_setting_container.style.display = this.use_arm_plane_correction() ? 'flex' : 'none'
+ }
+ }
+
// returning back to edit skeleton step later will call this to reset undo state
public clear_undo_history (): void {
this.undo_redo_system.clear_history()
@@ -492,12 +608,22 @@ export class StepEditSkeleton extends EventTarget {
if (this.ui.dom_preview_plane_height_input !== null) {
this.ui.dom_preview_plane_height_input.removeEventListener('input', () => {})
}
+
+ // Remove arm plane event listeners
+ if (this.ui.dom_arm_plane_checkbox !== null) {
+ this.ui.dom_arm_plane_checkbox.removeEventListener('change', () => {})
+ }
+
+ if (this.ui.dom_arm_plane_offset_input !== null) {
+ this.ui.dom_arm_plane_offset_input.removeEventListener('input', () => {})
+ }
}
public cleanup_on_exit_step (): void {
this.remove_event_listeners()
this.clear_hover_point_if_exists()
this.remove_preview_plane()
+ this.arm_plane_manager.cleanup()
}
/**
diff --git a/src/lib/processes/weight-skin/StepWeightSkin.ts b/src/lib/processes/weight-skin/StepWeightSkin.ts
index bd86d17..9d598b6 100644
--- a/src/lib/processes/weight-skin/StepWeightSkin.ts
+++ b/src/lib/processes/weight-skin/StepWeightSkin.ts
@@ -150,6 +150,17 @@ export class StepWeightSkin extends EventTarget {
this.bone_skinning_formula.set_preview_plane_height(height)
}
+ /**
+ * Configure arm plane correction settings for the solver
+ * @param enabled Whether arm plane correction is enabled
+ * @param offset Distance along X from the shoulder joint to place the plane
+ */
+ public set_arm_plane_correction_settings (enabled: boolean, offset: number): void {
+ if (this.bone_skinning_formula === undefined) return
+ this.bone_skinning_formula.set_arm_plane_correction_enabled(enabled)
+ this.bone_skinning_formula.set_arm_plane_offset(offset)
+ }
+
public calculate_weights (): number[][] {
if (this.bone_skinning_formula === undefined) return [[], []]
return this.bone_skinning_formula.calculate_indexes_and_weights()
diff --git a/src/lib/solvers/ArmWeightCorrector.test.ts b/src/lib/solvers/ArmWeightCorrector.test.ts
new file mode 100644
index 0000000..f39a5f1
--- /dev/null
+++ b/src/lib/solvers/ArmWeightCorrector.test.ts
@@ -0,0 +1,208 @@
+import { describe, it, expect } from 'vitest'
+import { Bone, BufferGeometry, Float32BufferAttribute, type Vector3 } from 'three'
+import { Utility } from '../Utilities'
+import { ArmWeightCorrector } from './ArmWeightCorrector'
+
+/**
+ * Builds a minimal symmetric humanoid-ish rig with these WORLD positions:
+ *
+ * root (0, 0, 0)
+ * spine_01 (0, 1.0, 0) chest (0, 1.5, 0)
+ * clavicle (+/-0.1, 1.5, 0)
+ * upperarm (+/-1.0, 1.5, 0) lowerarm (+/-2.0, ...) hand (+/-3.0, ...)
+ *
+ * Which puts the midpoint-to-child reference points the solver measures against at:
+ * spine_01 (0, 1.25, 0) chest (+/-0.05, 1.5, 0) clavicle (+/-0.55, 1.5, 0)
+ */
+function build_test_rig (): Bone[] {
+ const root = new Bone()
+ root.name = 'root'
+
+ const spine = new Bone()
+ spine.name = 'spine_01'
+ spine.position.set(0, 1.0, 0)
+ root.add(spine)
+
+ const chest = new Bone()
+ chest.name = 'chest'
+ chest.position.set(0, 0.5, 0)
+ spine.add(chest)
+
+ const bones: Bone[] = [root, spine, chest]
+
+ const build_arm = (side: string, direction: number): void => {
+ const clavicle = new Bone()
+ clavicle.name = `clavicle_${side}`
+ clavicle.position.set(direction * 0.1, 0, 0) // world x = direction * 0.1
+
+ const upperarm = new Bone()
+ upperarm.name = `upperarm_${side}`
+ upperarm.position.set(direction * 0.9, 0, 0) // world x = direction * 1.0
+
+ const lowerarm = new Bone()
+ lowerarm.name = `lowerarm_${side}`
+ lowerarm.position.set(direction * 1.0, 0, 0) // world x = direction * 2.0
+
+ const hand = new Bone()
+ hand.name = `hand_${side}`
+ hand.position.set(direction * 1.0, 0, 0) // world x = direction * 3.0
+
+ lowerarm.add(hand)
+ upperarm.add(lowerarm)
+ clavicle.add(upperarm)
+ chest.add(clavicle)
+
+ bones.push(clavicle, upperarm, lowerarm, hand)
+ }
+
+ build_arm('l', 1)
+ build_arm('r', -1)
+
+ root.updateWorldMatrix(true, true)
+ return bones
+}
+
+function bone_index (bones: Bone[], name: string): number {
+ return bones.findIndex(bone => bone.name === name)
+}
+
+function geometry_from_points (points: Array<[number, number, number]>): BufferGeometry {
+ const geometry = new BufferGeometry()
+ geometry.setAttribute('position', new Float32BufferAttribute(points.flat(), 3))
+ return geometry
+}
+
+describe('ArmWeightCorrector.shoulder_anchor_x', () => {
+ it('returns the absolute world X of the upperarm bone', () => {
+ const bones = build_test_rig()
+ expect(ArmWeightCorrector.shoulder_anchor_x(bones)).toBeCloseTo(1.0)
+ })
+
+ it('returns null when the rig has no arm bones', () => {
+ const snake_head = new Bone()
+ snake_head.name = 'head'
+ expect(ArmWeightCorrector.shoulder_anchor_x([snake_head])).toBeNull()
+ })
+})
+
+describe('ArmWeightCorrector.apply_arm_weight_correction', () => {
+ it('reassigns inboard vertices off arm bones onto the nearest non-arm bone', () => {
+ const bones = build_test_rig()
+ const upperarm_l = bone_index(bones, 'upperarm_l')
+
+ // a chest-height vertex inboard of the shoulder plane (x = 1.0), closest to
+ // the clavicle's reference point at 0.55
+ const geometry = geometry_from_points([[0.35, 1.5, 0]])
+ const skin_indices = [upperarm_l, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ expect(skin_indices[0]).not.toBe(upperarm_l)
+ expect(bones[skin_indices[0]].name).toBe('clavicle_l')
+ expect(skin_weights[0] + skin_weights[1] + skin_weights[2] + skin_weights[3]).toBeCloseTo(1.0)
+ })
+
+ it('leaves vertices outboard of the plane alone', () => {
+ const bones = build_test_rig()
+ const upperarm_l = bone_index(bones, 'upperarm_l')
+
+ const geometry = geometry_from_points([[1.5, 1.5, 0]])
+ const skin_indices = [upperarm_l, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ expect(skin_indices[0]).toBe(upperarm_l)
+ expect(skin_weights[0]).toBe(1.0)
+ })
+
+ it('applies symmetrically to the negative X side', () => {
+ const bones = build_test_rig()
+ const upperarm_r = bone_index(bones, 'upperarm_r')
+
+ const geometry = geometry_from_points([[-0.35, 1.5, 0]])
+ const skin_indices = [upperarm_r, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ expect(bones[skin_indices[0]].name).toBe('clavicle_r')
+ })
+
+ it('never hands a vertex to the clavicle when the offset pushes the plane past it', () => {
+ // clavicle midpoint sits at x = 0.55, so a -0.5 offset puts the plane at 0.5
+ const bones = build_test_rig()
+ const upperarm_l = bone_index(bones, 'upperarm_l')
+
+ const geometry = geometry_from_points([[0.45, 1.5, 0]])
+ const skin_indices = [upperarm_l, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, -0.5).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ // still corrected (0.45 < 0.5), and the replacement is never an arm bone
+ expect(bones[skin_indices[0]].name.includes('arm')).toBe(false)
+ })
+
+ it('is a no-op when the rig has no arm bones', () => {
+ const snake_head = new Bone()
+ snake_head.name = 'head'
+ snake_head.updateWorldMatrix(true, true)
+
+ const geometry = geometry_from_points([[0, 0, 0]])
+ const skin_indices = [0, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, [snake_head], 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ expect(skin_indices).toEqual([0, 0, 0, 0])
+ expect(skin_weights).toEqual([1.0, 0, 0, 0])
+ })
+
+ it('does not strip weights from the clavicle itself', () => {
+ const bones = build_test_rig()
+ const clavicle_l = bone_index(bones, 'clavicle_l')
+
+ const geometry = geometry_from_points([[0.35, 1.5, 0]])
+ const skin_indices = [clavicle_l, 0, 0, 0]
+ const skin_weights = [1.0, 0, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ expect(skin_indices[0]).toBe(clavicle_l)
+ expect(skin_weights[0]).toBe(1.0)
+ })
+
+ it('merges the stolen weight into an existing slot for the replacement bone', () => {
+ const bones = build_test_rig()
+ const upperarm_l = bone_index(bones, 'upperarm_l')
+ const clavicle_l = bone_index(bones, 'clavicle_l')
+
+ const geometry = geometry_from_points([[0.35, 1.5, 0]])
+ const skin_indices = [upperarm_l, clavicle_l, 0, 0]
+ const skin_weights = [0.6, 0.4, 0, 0]
+
+ new ArmWeightCorrector(geometry, bones, 0).apply_arm_weight_correction(skin_indices, skin_weights)
+
+ // all of it collapses onto the single clavicle slot
+ expect(skin_indices[1]).toBe(clavicle_l)
+ expect(skin_weights[1]).toBeCloseTo(1.0)
+ expect(skin_weights[0]).toBe(0)
+ })
+})
+
+describe('Utility.bone_midpoint_to_child', () => {
+ it('returns the halfway point to the first child', () => {
+ const bones = build_test_rig()
+ const upperarm_l = bones[bone_index(bones, 'upperarm_l')]
+ const midpoint: Vector3 = Utility.bone_midpoint_to_child(upperarm_l)
+ expect(midpoint.x).toBeCloseTo(1.5)
+ })
+
+ it('falls back to the bone position when childless', () => {
+ const bones = build_test_rig()
+ const hand_l = bones[bone_index(bones, 'hand_l')]
+ expect(Utility.bone_midpoint_to_child(hand_l).x).toBeCloseTo(3.0)
+ })
+})
diff --git a/src/lib/solvers/ArmWeightCorrector.ts b/src/lib/solvers/ArmWeightCorrector.ts
new file mode 100644
index 0000000..6826bb1
--- /dev/null
+++ b/src/lib/solvers/ArmWeightCorrector.ts
@@ -0,0 +1,231 @@
+import {
+ Vector3,
+ Bone,
+ type BufferGeometry
+} from 'three'
+
+import { Utility } from '../Utilities.js'
+
+/**
+ * Pulls torso vertices back off the arm bones.
+ *
+ * When a character's arms hang down (A-pose or lower) the upperarm/lowerarm
+ * bones run close to the ribcage and hips, so the closest-midpoint assignment
+ * hands chest vertices to an arm bone. Lifting the arm then drags part of the
+ * torso with it.
+ *
+ * This defines a vertical plane anchored at the shoulder joint's X position
+ * (nudged in or out by the user's offset) and mirrored to both sides. Any
+ * vertex *inboard* of that plane (|x| < plane_x) that was given to an arm bone
+ * has that weight taken away and handed to its nearest non-arm bone.
+ *
+ * The "arm" set is the upperarm bone and everything below it. The clavicle is
+ * deliberately excluded — it sits inboard of the shoulder joint and legitimately
+ * covers part of the chest.
+ */
+export class ArmWeightCorrector {
+ private readonly geometry: BufferGeometry
+ private readonly bones: Bone[]
+ private readonly arm_plane_offset: number
+
+ constructor (geometry: BufferGeometry, bones_master_data: Bone[], arm_plane_offset: number) {
+ this.geometry = geometry
+ this.bones = bones_master_data
+ this.arm_plane_offset = arm_plane_offset
+ }
+
+ /**
+ * Distance from the model's center line to the shoulder joint, which is where
+ * the arm plane sits when the user's offset is zero.
+ *
+ * Shared with the edit-skeleton preview so the plane the user sees and the
+ * plane the solver uses are derived the same way. The solver runs against a
+ * clone of the edited armature, so both recompute this from bones rather than
+ * passing an absolute coordinate around.
+ *
+ * @returns the absolute world X of the shoulder joint, or null if no arm bone was found
+ */
+ public static shoulder_anchor_x (bones: Bone[]): number | null {
+ const shoulder_bone = ArmWeightCorrector.find_shoulder_bone(bones)
+ if (shoulder_bone === undefined) {
+ return null
+ }
+ return Math.abs(Utility.world_position_from_object(shoulder_bone).x)
+ }
+
+ /**
+ * The bone the arm plane is anchored to. Human rigs name it `upperarm_l`;
+ * the fallbacks cover rigs that use other conventions.
+ */
+ public static find_shoulder_bone (bones: Bone[]): Bone | undefined {
+ const name_priority = ['upperarm', 'shoulder', 'arm']
+ for (const keyword of name_priority) {
+ const match = bones.find(bone => bone.name.toLowerCase().includes(keyword))
+ if (match !== undefined) {
+ return match
+ }
+ }
+ return undefined
+ }
+
+ /**
+ * Reassign arm-bone weights on vertices inboard of the arm plane.
+ * Modifies skin_indices and skin_weights in place. Runs before smoothing so
+ * the smoother blends the new torso/arm boundary instead of leaving a seam.
+ */
+ public apply_arm_weight_correction (skin_indices: number[], skin_weights: number[]): void {
+ const anchor_x = ArmWeightCorrector.shoulder_anchor_x(this.bones)
+ if (anchor_x === null) { return } // no arm bones on this rig, nothing to correct
+
+ const plane_x = anchor_x + this.arm_plane_offset
+ if (plane_x <= 0) { return } // plane pushed past the center line, would strip both arms entirely
+
+ const arm_bone_indices = this.find_arm_bone_indices()
+ if (arm_bone_indices.size === 0) { return }
+
+ const fallback_bones = this.build_fallback_bone_candidates(arm_bone_indices)
+ if (fallback_bones.length === 0) { return }
+
+ this.correct_vertex_weights(skin_indices, skin_weights, plane_x, arm_bone_indices, fallback_bones)
+ }
+
+ /**
+ * Every upperarm bone plus all of its descendants (lowerarm, hand, fingers),
+ * on both sides. Walking the hierarchy rather than matching a keyword list
+ * gives exactly "upperarm and below" without needing to enumerate every
+ * finger bone name, and it leaves the clavicle alone.
+ */
+ private find_arm_bone_indices (): Set<number> {
+ const bone_to_index = new Map<Bone, number>()
+ this.bones.forEach((bone, idx) => bone_to_index.set(bone, idx))
+
+ const arm_bone_indices = new Set<number>()
+
+ this.bones.forEach((bone) => {
+ if (!bone.name.toLowerCase().includes('upperarm')) { return }
+
+ bone.traverse((descendant) => {
+ if (!(descendant instanceof Bone)) { return }
+ const index = bone_to_index.get(descendant)
+ if (index !== undefined) {
+ arm_bone_indices.add(index)
+ }
+ })
+ })
+
+ return arm_bone_indices
+ }
+
+ /**
+ * Bones a stripped vertex can be handed to: everything that isn't an arm bone,
+ * minus the root (global transform only) and leaf/orientation bones, which the
+ * solver never assigns vertices to.
+ */
+ private build_fallback_bone_candidates (arm_bone_indices: Set<number>): Array<{ index: number, midpoint: Vector3 }> {
+ const candidates: Array<{ index: number, midpoint: Vector3 }> = []
+
+ this.bones.forEach((bone, idx) => {
+ if (arm_bone_indices.has(idx)) { return }
+ if (bone.name === 'root' || Utility.is_leaf_bone(bone)) { return }
+ candidates.push({ index: idx, midpoint: Utility.bone_midpoint_to_child(bone) })
+ })
+
+ return candidates
+ }
+
+ private correct_vertex_weights (
+ skin_indices: number[],
+ skin_weights: number[],
+ plane_x: number,
+ arm_bone_indices: Set<number>,
+ fallback_bones: Array<{ index: number, midpoint: Vector3 }>
+ ): void {
+ const vertex_count = this.geometry.attributes.position.array.length / 3
+
+ for (let i = 0; i < vertex_count; i++) {
+ const vertex_position = new Vector3().fromBufferAttribute(this.geometry.attributes.position, i)
+
+ // Math.abs is what makes this symmetric: one slider drives both arms,
+ // regardless of which side of the model is +X.
+ if (Math.abs(vertex_position.x) >= plane_x) { continue } // outboard of the plane, genuinely arm territory
+
+ const offset = i * 4
+
+ // Take the weight away from every arm bone influencing this vertex.
+ // Index 0 is the root bone, which never receives weights, so it doubles
+ // as the "empty slot" marker (same convention as HeadWeightCorrector).
+ let stolen_weight = 0
+ let first_freed_slot = -1
+ for (let j = 0; j < 4; j++) {
+ if (!arm_bone_indices.has(skin_indices[offset + j])) { continue }
+ if (skin_weights[offset + j] <= 0) { continue }
+
+ stolen_weight += skin_weights[offset + j]
+ skin_weights[offset + j] = 0
+ skin_indices[offset + j] = 0
+ if (first_freed_slot === -1) {
+ first_freed_slot = j
+ }
+ }
+
+ if (stolen_weight <= 0) { continue }
+
+ const replacement_bone_index = this.find_closest_fallback_bone(vertex_position, fallback_bones)
+
+ // Merge into the replacement bone's existing slot if it already influences
+ // this vertex, otherwise reuse one of the slots we just emptied.
+ let target_slot = -1
+ for (let j = 0; j < 4; j++) {
+ if (skin_indices[offset + j] === replacement_bone_index && skin_weights[offset + j] > 0) {
+ target_slot = j
+ break
+ }
+ }
+
+ if (target_slot === -1) {
+ target_slot = first_freed_slot
+ skin_indices[offset + target_slot] = replacement_bone_index
+ }
+
+ skin_weights[offset + target_slot] += stolen_weight
+
+ this.normalize_vertex_weights(skin_weights, offset)
+ }
+ }
+
+ private find_closest_fallback_bone (
+ vertex_position: Vector3,
+ fallback_bones: Array<{ index: number, midpoint: Vector3 }>
+ ): number {
+ let closest_distance = Infinity
+ let closest_index = fallback_bones[0].index
+
+ for (const candidate of fallback_bones) {
+ const distance = candidate.midpoint.distanceTo(vertex_position)
+ if (distance < closest_distance) {
+ closest_distance = distance
+ closest_index = candidate.index
+ }
+ }
+
+ return closest_index
+ }
+
+ /**
+ * Normalize weights for a single vertex to ensure they sum to 1.0
+ */
+ private normalize_vertex_weights (skin_weights: number[], offset: number): void {
+ const total_weight =
+ skin_weights[offset] +
+ skin_weights[offset + 1] +
+ skin_weights[offset + 2] +
+ skin_weights[offset + 3]
+
+ if (total_weight > 0) {
+ skin_weights[offset] /= total_weight
+ skin_weights[offset + 1] /= total_weight
+ skin_weights[offset + 2] /= total_weight
+ skin_weights[offset + 3] /= total_weight
+ }
+ }
+}
diff --git a/src/lib/solvers/SkinningAlgorithm.ts b/src/lib/solvers/SkinningAlgorithm.ts
index a92bf48..31bfedd 100644
--- a/src/lib/solvers/SkinningAlgorithm.ts
+++ b/src/lib/solvers/SkinningAlgorithm.ts
@@ -7,6 +7,7 @@ import {
import { Utility } from '../Utilities.js'
import { SkeletonType } from '../enums/SkeletonType.js'
import { HeadWeightCorrector } from './HeadWeightCorrector.js'
+import { ArmWeightCorrector } from './ArmWeightCorrector.js'
import { WeightCalculator } from './WeightCalculator.js'
import { ExtremityWeightCorrector } from './ExtremityWeightCorrector.js'
import { WeightSmoother } from './WeightSmoother.js'
@@ -30,6 +31,11 @@ export default class SkinningAlgorithm {
private use_head_weight_correction: boolean = false
private preview_plane_height: number = 1.4
+ // Arm plane correction properties. The offset is relative to the shoulder
+ // joint's X, which the corrector reads off the bones itself.
+ private use_arm_plane_correction: boolean = false
+ private arm_plane_offset: number = 0.0
+
constructor (bone_hier: Object3D, skeleton_type: SkeletonType) {
this.skeleton_type = skeleton_type
this.bones_master_data = Utility.bone_list_from_hierarchy(bone_hier)
@@ -47,6 +53,14 @@ export default class SkinningAlgorithm {
this.preview_plane_height = height
}
+ public set_arm_plane_correction_enabled (enabled: boolean): void {
+ this.use_arm_plane_correction = enabled
+ }
+
+ public set_arm_plane_offset (offset: number): void {
+ this.arm_plane_offset = offset
+ }
+
public calculate_indexes_and_weights (): number[][] {
const skin_indices: number[] = []
const skin_weights: number[] = []
@@ -64,6 +78,19 @@ export default class SkinningAlgorithm {
const extremity_corrector = new ExtremityWeightCorrector(this.geometry, this.bones_master_data)
extremity_corrector.apply_extremity_weight_correction(skin_indices, skin_weights)
+ // Step 1c: Hand torso vertices back from the arm bones. Arms that hang down
+ // (A-pose or lower) run close to the ribcage, so the closest-bone pass gives
+ // them chest vertices. Runs before smoothing so the smoother blends the new
+ // torso/arm boundary instead of leaving a hard seam.
+ if (this.use_arm_plane_correction) {
+ const arm_weight_corrector = new ArmWeightCorrector(
+ this.geometry,
+ this.bones_master_data,
+ this.arm_plane_offset
+ )
+ arm_weight_corrector.apply_arm_weight_correction(skin_indices, skin_weights)
+ }
+
// Step 2: Smooth weight boundaries between adjacent bones
const weight_smoother = new WeightSmoother(this.geometry, this.bones_master_data)
weight_smoother.smooth_bone_weight_boundaries(skin_indices, skin_weights)
diff --git a/src/lib/solvers/WeightCalculator.ts b/src/lib/solvers/WeightCalculator.ts
index 80bf19c..1f107a9 100644
--- a/src/lib/solvers/WeightCalculator.ts
+++ b/src/lib/solvers/WeightCalculator.ts
@@ -40,7 +40,7 @@ export class WeightCalculator {
* Must be called before calculate_median_bone_weights.
*/
public initialize_caches (): void {
- this.cached_median_child_bone_positions = this.bones.map(b => this.midpoint_to_child(b))
+ this.cached_median_child_bone_positions = this.bones.map(b => Utility.bone_midpoint_to_child(b))
this.bones.forEach((b, idx) => this.bone_object_to_index.set(b, idx))
// The root bone is only for global transform changes, and leaf/orientation
@@ -105,17 +105,6 @@ export class WeightCalculator {
}
}
- private midpoint_to_child (bone: Bone): Vector3 {
- const bone_position = Utility.world_position_from_object(bone)
- if (bone.children.length === 0) {
- return bone_position.clone()
- }
- // Assume first child is the relevant one
- const child = bone.children[0] as Bone
- const child_position = Utility.world_position_from_object(child)
- return new Vector3().lerpVectors(bone_position, child_position, 0.5)
- }
-
// every vertex checks to see if it is below the hips area,
// so do this calculation once and cache it for the lookup later
private calculate_distance_to_bottom_of_position_tracking_bone (): number {