------------------------------------------------------------------------------ Bounding box intersection code from David Gobbi. Go through the bounding planes one at a time and compute the parametric coordinate of each intersection.
| 430 | // bounding planes one at a time and compute the parametric coordinate |
| 431 | // of each intersection. |
| 432 | int vtkBox::IntersectWithLine(const double bounds[6], const double p1[3], const double p2[3], |
| 433 | double& t1, double& t2, double x1[3], double x2[3], int& plane1, int& plane2) |
| 434 | { |
| 435 | plane1 = -1; |
| 436 | plane2 = -1; |
| 437 | t1 = 0.0; |
| 438 | t2 = 1.0; |
| 439 | |
| 440 | for (int j = 0; j < 3; j++) |
| 441 | { |
| 442 | for (int k = 0; k < 2; k++) |
| 443 | { |
| 444 | // Compute distances of p1 and p2 from the plane along the plane normal |
| 445 | int i = 2 * j + k; |
| 446 | double d1 = (bounds[i] - p1[j]) * (1 - 2 * k); |
| 447 | double d2 = (bounds[i] - p2[j]) * (1 - 2 * k); |
| 448 | |
| 449 | // If both distances are positive, both points are outside |
| 450 | if (d1 > 0 && d2 > 0) |
| 451 | { |
| 452 | return 0; |
| 453 | } |
| 454 | // If one of the distances is positive, the line crosses the plane |
| 455 | else if (d1 > 0 || d2 > 0) |
| 456 | { |
| 457 | // Compute fractional distance "t" of the crossing between p1 & p2 |
| 458 | double t = 0.0; |
| 459 | if (d1 != 0) |
| 460 | { |
| 461 | t = d1 / (d1 - d2); |
| 462 | } |
| 463 | |
| 464 | // If point p1 was clipped, adjust t1 |
| 465 | if (d1 > 0) |
| 466 | { |
| 467 | if (t >= t1) |
| 468 | { |
| 469 | t1 = t; |
| 470 | plane1 = i; |
| 471 | } |
| 472 | } |
| 473 | // else point p2 was clipped, so adjust t2 |
| 474 | else |
| 475 | { |
| 476 | if (t <= t2) |
| 477 | { |
| 478 | t2 = t; |
| 479 | plane2 = i; |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | // If this happens, there's no line left |
| 484 | if (t1 > t2) |
| 485 | { |
| 486 | // Allow for planes that are coincident or slightly inverted |
| 487 | if (plane1 < 0 || plane2 < 0 || (plane1 >> 1) != (plane2 >> 1)) |
| 488 | { |
| 489 | return 0; |