Potential Bug in vtkMath::Cross Template Function
Description
There appears to be a potential bug in the vtkMath::Cross
template function within the VTK library. The issue arises from the direct assignment of values to the output vector c
without using temporary variables to store intermediate results. This can cause problems, especially when the input vectors a
and b
overlap with the output vector c
.
Current Implementation
The current implementation of the template function vtkMath::Cross
is as follows:
template <class VectorT1, class VectorT2, class VectorT3> void vtkMath::Cross(VectorT1&& a, VectorT2&& b, VectorT3& c)
{
c[0] = a[1] * b[2] - a[2] * b[1];
c[1] = a[2] * b[0] - a[0] * b[2];
c[2] = a[0] * b[1] - a[1] * b[0];
}
Problem
This implementation can lead to incorrect results when the input vectors a
and b
overlap with the output vector c
.
Proposed Fix
To avoid this issue, I suggest using temporary variables to store intermediate results before assigning them to the output vector c
. Below is the modified version of the template function:
template <class VectorT1, class VectorT2, class VectorT3> void vtkMath::Cross(VectorT1&& a, VectorT2&& b, VectorT3& c)
{
// Use temporary variables to store intermediate results
auto Cx = a[1] * b[2] - a[2] * b[1];
auto Cy = a[2] * b[0] - a[0] * b[2];
auto Cz = a[0] * b[1] - a[1] * b[0];
// Assign results to c
c[0] = Cx;
c[1] = Cy;
c[2] = Cz;
}