Return triangle index instead of vertex index (Fixes #18081) (#18647)

# Objective

- Fixes #18081
- Enable use-cases like getting UVs or texture colors for the hit point
(which are currently not possible due to this bug).

## Solution

- Return the triangle index instead of the first vertex index of the
triangle.

## Testing

Tested successfully with my project which does a raycast to get the UV
coordinates of the hit. My code:
```rust
fn get_uv(
    mesh: &Mesh,
    attribute: &MeshVertexAttribute,
    hit: &RayMeshHit,
    _gizmos: &mut Gizmos,
) -> Result<Vec2> {
    let (a, b, c) = get_indices(mesh, hit)?;

    let attrs = mesh
        .attribute(*attribute)
        .ok_or_eyre(format!("Attribute {:?} not found", &attribute))?;
    let all_uvs: &Vec<[f32; 2]> = match &attrs {
        VertexAttributeValues::Float32x2(positions) => positions,
        _ => bail!("Unexpected types in {:?}", Mesh::ATTRIBUTE_UV_0),
    };

    let bary = hit.barycentric_coords;

    Ok(Vec2::from_array(all_uvs[a]) * bary.x
        + Vec2::from_array(all_uvs[b]) * bary.y
        + Vec2::from_array(all_uvs[c]) * bary.z)
}

fn get_indices(mesh: &Mesh, hit: &RayMeshHit) -> Result<(usize, usize, usize)> {
    let i = hit
        .triangle_index
        .ok_or_eyre("Intersection Index not found")?;

    Ok(mesh.indices().map_or_else(
        || (i, i + 1, i + 2),
        |indices| match indices {
            Indices::U16(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
            Indices::U32(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
        },
    ))
}
```

PS: created a new PR because the old one was coming from and targeting
the wrong branches
This commit is contained in:
Beni Bachmann 2025-03-31 20:50:15 +02:00 committed by François Mockers
parent eb37e86a1f
commit 10daca0947

View File

@ -189,7 +189,7 @@ pub fn ray_mesh_intersection<I: TryInto<usize> + Clone + Copy>(
.transform_vector3(ray.direction * hit.distance)
.length(),
triangle: Some(tri_vertices.map(|v| mesh_transform.transform_point3(v))),
triangle_index: Some(a),
triangle_index: Some(tri_idx),
})
})
}