メインコンテンツまでスキップ

triangleDistanceSq: Point-to-Triangle Distance Calculation

Hybrid Distance Computation Using Edge and Plane Methods

The triangle distance function computes the shortest squared distance from a point to a triangle surface using a hybrid approach combining edge projection and plane distance calculations.

The algorithm determines point classification relative to the triangle using cross product sign testing:

signs=sign(v21×np1)+sign(v32×np2)+sign(v13×np3)\text{signs} = \text{sign}(\vec{v_{21}} \times \vec{n} \cdot \vec{p_1}) + \text{sign}(\vec{v_{32}} \times \vec{n} \cdot \vec{p_2}) + \text{sign}(\vec{v_{13}} \times \vec{n} \cdot \vec{p_3})

Where n=v21×v13\vec{n} = \vec{v_{21}} \times \vec{v_{13}} represents the triangle normal vector.

Edge Distance Calculation

For points outside the triangle (signs<2\text{signs} < 2), distance is computed using edge projections:

dedge=min(v21saturate(v21p1v212)p12,)d_{\text{edge}} = \min\left(\left\|\vec{v_{21}} \cdot \text{saturate}\left(\frac{\vec{v_{21}} \cdot \vec{p_1}}{\|\vec{v_{21}}\|^2}\right) - \vec{p_1}\right\|^2, \ldots\right)

The saturate function clamps projection parameters to [0,1][0,1], ensuring closest points lie within edge segments.

Plane Distance Calculation

For points inside the triangle projection (signs2\text{signs} \geq 2), distance uses perpendicular plane distance:

dplane=(np1)2n2d_{\text{plane}} = \frac{(\vec{n} \cdot \vec{p_1})^2}{\|\vec{n}\|^2}

This computes the squared perpendicular distance from the point to the triangle plane.

ライブエディター
const fragment = () => Scope(() => {
      const tri = Triangle({
              a: vec3(-0.4, -0.3, 0),
              b: vec3(0.4, -0.3, 0),
              c: vec3(0, 0.5, 0)
      })
      const pos = vec3(uv.mul(2).sub(1), 0)
      const dist = distanceSq(tri, pos)
      const field = dist.sqrt().mul(8)
      const gradient = field.fract()
      return vec4(vec3(gradient), 1)
})