Import a 3D Model and automatically assign and export animations
TypeScript
Distribute weight dabs across the hit triangle (#166)
ReneArmenta-lsca37b968f24dd
diff --git a/src/lib/processes/weight-painting/WeightPaintBrush.test.ts b/src/lib/processes/weight-painting/WeightPaintBrush.test.tsnew file mode 100644index 0000000..90f7060--- /dev/null+++ b/src/lib/processes/weight-painting/WeightPaintBrush.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from 'vitest'+import {+ BufferGeometry, Float32BufferAttribute, Mesh, MeshBasicMaterial, PerspectiveCamera,+ PlaneGeometry, Vector3, type Intersection+} from 'three'+import { WeightPaintBrush } from './WeightPaintBrush'+import { WeightPaintManager, type BrushVertex } from './WeightPaintManager'++class RecordingManager {+ public readonly calls: BrushVertex[][] = []++ public begin_stroke (): void {}+ public finish_stroke (): void {}+ public normalize_all_weights (): void {}++ public paint_vertices (+ _mesh: Mesh,+ _geometry_index: number,+ vertices: BrushVertex[]+ ): number {+ this.calls.push(vertices.map(vertex => ({ ...vertex })))+ return vertices.length+ }+}++interface BrushScene {+ brush: WeightPaintBrush+ manager: RecordingManager+ mesh: Mesh+ camera: PerspectiveCamera+ positions: Mesh['geometry']['attributes']['position']+}++function brush_scene (): BrushScene {+ const manager = new RecordingManager()+ const brush = new WeightPaintBrush(manager as unknown as WeightPaintManager)+ // a fixed world-space radius keeps the test independent of the viewport size+ brush.world_radius = () => 1++ const geometry = new PlaneGeometry(10, 10, 20, 20)+ const mesh = new Mesh(geometry, new MeshBasicMaterial())+ mesh.userData.geometry_index = 0+ mesh.updateMatrixWorld(true)++ const camera = new PerspectiveCamera(50, 1, 0.1, 100)+ camera.position.set(0, 0, 5)+ camera.lookAt(0, 0, 0)+ camera.updateMatrixWorld(true)++ return { brush, manager, mesh, camera, positions: geometry.attributes.position }+}++function dab (scene: BrushScene, x: number): boolean {+ const intersection = { object: scene.mesh, point: new Vector3(x, 0, 0) } as unknown as Intersection+ return scene.brush.paint(intersection, scene.camera, 'head', [])+}++function vertex_index_at (scene: BrushScene, x: number, y: number): number {+ for (let i = 0; i < scene.positions.count; i++) {+ if (Math.abs(scene.positions.getX(i) - x) < 1e-6 &&+ Math.abs(scene.positions.getY(i) - y) < 1e-6) {+ return i+ }+ }+ throw new Error(`no vertex at ${x}, ${y}`)+}++function falloff_of (vertices: BrushVertex[], vertex_index: number): number | undefined {+ return vertices.find(vertex => vertex.vertex_index === vertex_index)?.falloff+}++describe('WeightPaintBrush', () => {+ it('sweeps between dabs so a fast drag paints a continuous stroke', () => {+ const scene = brush_scene()+ const middle = vertex_index_at(scene, 1, 0)++ scene.brush.begin_stroke()+ expect(dab(scene, 0)).toBe(true)+ expect(falloff_of(scene.manager.calls[0], middle)).toBeUndefined()++ // without sweeping, the vertex between the two dabs would be left unpainted+ expect(dab(scene, 2)).toBe(true)+ expect(scene.manager.calls).toHaveLength(2)+ expect(falloff_of(scene.manager.calls[1], middle)).toBeGreaterThan(0.9)+ })++ it('only applies the falloff increase during a stroke', () => {+ const scene = brush_scene()+ const center = vertex_index_at(scene, 1, 0)++ scene.brush.begin_stroke()+ dab(scene, 0)+ dab(scene, 1)+ expect(falloff_of(scene.manager.calls[1], center)).toBeGreaterThan(0.9)++ // the vertex already reached full falloff during this stroke, so a dab on+ // top of it must not stack another helping of weight+ expect(dab(scene, 1)).toBe(false)+ expect(scene.manager.calls).toHaveLength(2)+ })++ it('does not sweep across the gap after leaving the mesh', () => {+ const scene = brush_scene()++ scene.brush.begin_stroke()+ dab(scene, -4)+ scene.brush.reset_dab_path()+ dab(scene, 4)++ expect(scene.manager.calls).toHaveLength(2)+ const painted_x = scene.manager.calls[1].map(vertex => scene.positions.getX(vertex.vertex_index))+ expect(painted_x.length).toBeGreaterThan(0)+ expect(painted_x.every(x => Math.abs(x - 4) <= 1.000001)).toBe(true)+ expect(painted_x.some(x => Math.abs(x) < 3)).toBe(false)+ })++ it('distributes a dab across the touched triangle and its neighbours', () => {+ const manager = new RecordingManager()+ const brush = new WeightPaintBrush(manager as unknown as WeightPaintManager)+ // a tiny radius proves the paint comes from the surface hit, not a vertex+ // that happens to fall inside the brush+ brush.world_radius = () => 0.0001++ const geometry = new BufferGeometry()+ geometry.setAttribute('position', new Float32BufferAttribute([+ 0, 0, 0,+ 1, 0, 0,+ 0, 1, 0,+ 1, 1, 0+ ], 3))+ geometry.setIndex([0, 1, 2, 2, 1, 3])+ const mesh = new Mesh(geometry, new MeshBasicMaterial())+ mesh.userData.geometry_index = 0+ mesh.updateMatrixWorld(true)++ const camera = new PerspectiveCamera(50, 1, 0.1, 100)+ camera.position.set(0, 0, 5)+ camera.lookAt(0, 0, 0)+ camera.updateMatrixWorld(true)++ const intersection = {+ object: mesh,+ point: new Vector3(1 / 3, 1 / 3, 0),+ face: { a: 0, b: 1, c: 2, normal: new Vector3(0, 0, 1), materialIndex: 0 }+ } as unknown as Intersection++ brush.begin_stroke()+ expect(brush.paint(intersection, camera, 'head', [])).toBe(true)++ const painted = new Map(manager.calls[0].map(vertex => [vertex.vertex_index, vertex.falloff]))+ expect(painted.get(0)).toBeCloseTo(1 / 3, 2)+ expect(painted.get(1)).toBeCloseTo(1 / 3, 2)+ expect(painted.get(2)).toBeCloseTo(1 / 3, 2)+ // vertex 3 shares an edge with the touched triangle, so it gets half+ expect(painted.get(3)).toBeCloseTo(1 / 6, 2)+ })+})diff --git a/src/lib/processes/weight-painting/WeightPaintBrush.ts b/src/lib/processes/weight-painting/WeightPaintBrush.tsindex 447eee1..14adfcb 100644--- a/src/lib/processes/weight-painting/WeightPaintBrush.ts+++ b/src/lib/processes/weight-painting/WeightPaintBrush.ts@@ -1,4 +1,4 @@-import { MathUtils, Matrix3, Mesh, SkinnedMesh, Vector3, type Bone, type Intersection, type PerspectiveCamera } from 'three'+import { MathUtils, Matrix3, Mesh, SkinnedMesh, Triangle, Vector3, type Bone, type BufferGeometry, type Intersection, type PerspectiveCamera } from 'three'import { WeightPaintManager, type BrushVertex, type WeightPaintMode } from './WeightPaintManager.ts'/**@@ -24,6 +24,8 @@ export class WeightPaintBrush {private readonly sweep = new Vector3()private readonly sweep_offset = new Vector3()private readonly sweep_closest = new Vector3()+ // triangle adjacency per geometry, used to spread a dab across the surface+ private readonly adjacency_cache = new WeakMap<BufferGeometry, number[][]>()constructor (private readonly manager: WeightPaintManager) {}@@ -94,6 +96,9 @@ export class WeightPaintBrush {const point = new Vector3()const normal = new Vector3()const vertices: BrushVertex[] = []+ // A dab should paint the surface it lands on even when no vertex happens to+ // sit under the cursor, so seed the touched triangle and its neighbours.+ const surface_falloffs = this.surface_falloffs(object, intersection)// Sweep from the previous dab's hit point so fast pointer moves paint a// continuous stroke instead of leaving gaps between discrete samples.@@ -118,22 +123,25 @@ export class WeightPaintBrush {}const distance = point.distanceTo(this.sweep_closest)- if (distance > radius) { continue }-- if (is_skinned) {- // Ignore vertices behind the surface the brush is touching, so the- // brush cannot paint through the mesh to the far side.- const depth = point.sub(this.sweep_closest).dot(ray_direction)- if (depth > radius * 0.5) { continue }- } else if (normals !== undefined && normal_matrix !== null) {- // The preview meshes are not deformed, so the surface normal is enough- // to keep the brush from painting the back of the model.- normal.fromBufferAttribute(normals, i).applyMatrix3(normal_matrix).normalize()- if (normal.dot(ray_direction) > -0.05) { continue }+ const surface_falloff = surface_falloffs.get(i) ?? 0+ if (distance > radius && surface_falloff <= 0) { continue }++ if (surface_falloff <= 0) {+ if (is_skinned) {+ // Ignore vertices behind the surface the brush is touching, so the+ // brush cannot paint through the mesh to the far side.+ const depth = point.sub(this.sweep_closest).dot(ray_direction)+ if (depth > radius * 0.5) { continue }+ } else if (normals !== undefined && normal_matrix !== null) {+ // The preview meshes are not deformed, so the surface normal is enough+ // to keep the brush from painting the back of the model.+ normal.fromBufferAttribute(normals, i).applyMatrix3(normal_matrix).normalize()+ if (normal.dot(ray_direction) > -0.05) { continue }+ }}- const t = 1 - distance / radius- const falloff = t * t * (3 - 2 * t)+ const t = Math.max(0, 1 - distance / radius)+ const falloff = Math.max(t * t * (3 - 2 * t), surface_falloff)// The first dab that reaches a vertex is usually at the brush edge. Only// applying the increase lets the stroke keep strengthening that vertex// as the brush center passes over it.@@ -160,6 +168,78 @@ export class WeightPaintBrush {return painted_count > 0}+ /**+ * Falloff for the triangle under the brush and its immediate neighbours.+ *+ * The barycentric coordinates of the hit point spread the dab across the+ * triangle's three vertices, so painting anywhere on the surface changes the+ * surrounding vertices instead of requiring the cursor to sit on one. Each+ * direct neighbour of those vertices then receives half that influence, which+ * blends the painted patch into the rest of the surface.+ */+ private surface_falloffs (object: Mesh, intersection: Intersection): Map<number, number> {+ const falloffs = new Map<number, number>()+ const face = intersection.face+ const positions = object.geometry.attributes.position+ if (face === undefined || face === null || positions === undefined) { return falloffs }++ const triangle = [face.a, face.b, face.c]+ if (triangle.some(index => index < 0 || index >= positions.count)) { return falloffs }++ const world = triangle.map(index => {+ const vertex = new Vector3()+ object.getVertexPosition(index, vertex)+ return vertex.applyMatrix4(object.matrixWorld)+ })+ const barycentric = Triangle.getBarycoord(intersection.point, world[0], world[1], world[2], new Vector3())+ if (barycentric === null) { return falloffs }++ const influences = [barycentric.x, barycentric.y, barycentric.z]+ for (let i = 0; i < triangle.length; i++) {+ const influence = MathUtils.clamp(influences[i] ?? 0, 0, 1)+ if (influence <= 0) { continue }+ falloffs.set(triangle[i], influence)+ }++ const adjacency = this.adjacency_for(object.geometry)+ for (const index of triangle) {+ const influence = (falloffs.get(index) ?? 0) * 0.5+ if (influence <= 0) { continue }+ for (const neighbour of adjacency[index] ?? []) {+ falloffs.set(neighbour, Math.max(falloffs.get(neighbour) ?? 0, influence))+ }+ }+ return falloffs+ }++ /** Vertex adjacency built from the geometry's triangles, cached per geometry. */+ private adjacency_for (geometry: BufferGeometry): number[][] {+ const cached = this.adjacency_cache.get(geometry)+ if (cached !== undefined) { return cached }++ const positions = geometry.attributes.position+ const vertex_count = positions?.count ?? 0+ const neighbours: Array<Set<number>> = Array.from({ length: vertex_count }, () => new Set<number>())+ const index = geometry.getIndex()+ const triangle_count = Math.floor((index !== null ? index.count : vertex_count) / 3)++ for (let triangle = 0; triangle < triangle_count; triangle++) {+ const a = index !== null ? index.getX(triangle * 3) : triangle * 3+ const b = index !== null ? index.getX(triangle * 3 + 1) : triangle * 3 + 1+ const c = index !== null ? index.getX(triangle * 3 + 2) : triangle * 3 + 2+ neighbours[a]?.add(b)+ neighbours[a]?.add(c)+ neighbours[b]?.add(a)+ neighbours[b]?.add(c)+ neighbours[c]?.add(a)+ neighbours[c]?.add(b)+ }++ const adjacency = neighbours.map(set => [...set])+ this.adjacency_cache.set(geometry, adjacency)+ return adjacency+ }+/** World-space brush radius at a surface point, derived from the pixel size. */public world_radius (camera: PerspectiveCamera, point: Vector3): number {const forward = camera.getWorldDirection(new Vector3())