Пример #1
0
void
SbMatrix::multLineMatrix(const SbLine &src, SbLine &dst) const
{
	SbVec3f pos, dir;
	multVecMatrix(src.getPosition(), pos);
	multDirMatrix(src.getDirection(), dir);
	dst.setValue(pos, pos+dir);
}
Пример #2
0
SbBool
SbCylinder::intersect(const SbLine &line, SbVec3f &enter, SbVec3f &exit) const
//
////////////////////////////////////////////////////////////////////////
{
    // The intersection will actually be done on a radius 1 cylinder
    // aligned with the y axis, so we transform the line into that
    // space, then intersect, then transform the results back.

    // rotation to y axis
    SbRotation	rotToYAxis(axis.getDirection(), SbVec3f(0,1,0));
    SbMatrix	mtxToYAxis;
    mtxToYAxis.setRotate(rotToYAxis);

    // scale to unit space
    float	scaleFactor = 1.0f/radius;
    SbMatrix	toUnitCylSpace;
    toUnitCylSpace.setScale(SbVec3f(scaleFactor, scaleFactor, scaleFactor));
    toUnitCylSpace.multLeft(mtxToYAxis);

    // find the given line un-translated
    SbVec3f origin = line.getPosition();
    origin -= axis.getPosition();
    SbLine noTranslationLine(origin, origin + line.getDirection());

    // find the un-translated line in unit cylinder's space
    SbLine cylLine;
    toUnitCylSpace.multLineMatrix(noTranslationLine, cylLine);

    // find the intersection on the unit cylinder
    SbVec3f cylEnter, cylExit;
    SbBool intersected = unitCylinderIntersect(cylLine, cylEnter, cylExit);

    if (intersected) {
        // transform back to original space
        SbMatrix fromUnitCylSpace = toUnitCylSpace.inverse();

        fromUnitCylSpace.multVecMatrix(cylEnter, enter);
        enter += axis.getPosition();

        fromUnitCylSpace.multVecMatrix(cylExit, exit);
        exit += axis.getPosition();
    }

    return intersected;
}
Пример #3
0
bool
XipGeomUtils::intersect(const SbLine &line, const SbPlane &plane, SbVec3f &pt)
{
    float t, denom;

    // solve for t:
    //  n . (l.p + t * l.d) - d == 0

    denom = plane.getNormal().dot(line.getDirection());
    if ( fabs(denom) < XIP_EPSILON )
        return FALSE;

    //  t = - (n . l.p - d) / (n . l.d)
    t = - (plane.getNormal().dot(line.getPosition()) - plane.getDistanceFromOrigin()) /  denom;

    pt = line.getPosition() + t * line.getDirection();
    return TRUE;
}
Пример #4
0
//////////////////////////////////////////////////////////////////////////////
//
// Sphere line intersection - this sets the parameter intersection,
// and returns TRUE if the line and sphere really do intersect.
//
// line-sphere intersection algorithm lifted from Eric Haines chapter in 
// Glassner's "Introduction to Ray Tracing", pp. 35-7
//
SbBool
SbSphere::intersect(const SbLine &l, SbVec3f &intersection) const
//
//////////////////////////////////////////////////////////////////////////////
{
    float   B,C;	// At^2 + Bt + C = 0, but A is 1 since we normalize Rd
    float   discr;	// discriminant (B^2 - 4AC)
    SbVec3f v;
    float   t,sqroot;
    SbBool  doesIntersect = TRUE;

    // setup B,C
    v = l.getPosition() - center;
    B = 2.0 * (l.getDirection().dot(v));
    C = v.dot(v) - (radius * radius);

    // compute discriminant
    // if negative, there is no intersection
    discr = B*B - 4.0*C;
    if (discr < 0.0) {
	// line and sphere do not intersect
	doesIntersect = FALSE;
    }
    else {
	// compute t0: (-B - sqrt(B^2 - 4AC)) / 2A  (A = 1)
	sqroot = sqrtf(discr);
	t = (-B - sqroot) * 0.5;
	if (t < 0.0) {
	    // no intersection, try t1: (-B + sqrt(B^2 - 4AC)) / 2A  (A = 1)
	    t = (-B + sqroot) * 0.5;
	}

	if (t < 0.0) {
	    // line and sphere do not intersect
	    doesIntersect = FALSE;
	}
	else {
	    // intersection! point is (point + (dir * t))
	    intersection = l.getPosition() + (l.getDirection() * t);
	}
    }

    return doesIntersect;
}
Пример #5
0
SbBool
SbCylinder::unitCylinderIntersect(const SbLine &l,
                                  SbVec3f &enter, SbVec3f &exit)
//
////////////////////////////////////////////////////////////////////////
{
    float		A, B, C, discr, sqroot, t0, t1;
    const SbVec3f	&pos = l.getPosition(), &dir = l.getDirection();
    SbBool		doesIntersect = TRUE;

    A = dir[0] * dir[0] + dir[2] * dir[2];

    B = 2.0f * (pos[0] * dir[0] + pos[2] * dir[2]);

    C = pos[0] * pos[0] + pos[2] * pos[2] - 1;

    // discriminant = B^2 - 4AC
    discr = B*B - 4.0f*A*C;

    // if discriminant is negative, no intersection
    if (discr < 0.0) {
        doesIntersect = FALSE;
    }
    else {
        sqroot = float(sqrtf(discr));

        // magic to stabilize the answer
        if (B > 0.0) {
            t0 = -(2.0f * C) / (sqroot + B);
            t1 = -(sqroot + B) / (2.0f * A);
        }
        else {
            t0 = (2.0f * C) / (sqroot - B);
            t1 = (sqroot - B) / (2.0f * A);
        }

        enter = pos + (dir * t0);
        exit = pos + (dir * t1);
    }

    return doesIntersect;
}
Пример #6
0
float MeshFillHole::findClosestPoint(const SbLine& ray, const TBoundary& polygon,
                                     unsigned long& vertex_index, SbVec3f& closestPoint) const
{
    // now check which vertex of the polygon is closest to the ray
    float minDist = FLT_MAX;
    vertex_index = ULONG_MAX;

    const MeshCore::MeshKernel & rMesh = myMesh->Mesh.getValue().getKernel();
    const MeshCore::MeshPointArray& pts = rMesh.GetPoints();
    for (TBoundary::const_iterator it = polygon.begin(); it != polygon.end(); ++it) {
        SbVec3f vertex;
        const Base::Vector3f& v = pts[*it];
        vertex.setValue(v.x,v.y,v.z);
        SbVec3f point = ray.getClosestPoint(vertex);
        float distance = (vertex-point).sqrLength();
        if (distance < minDist) {
            minDist = distance;
            vertex_index = *it;
            closestPoint = vertex;
        }
    }

    return minDist;
}
Пример #7
0
//////////////////////////////////////////////////////////////////////////////
//
// Sphere line intersection - this sets the parameter intersection,
// and returns TRUE if the line and sphere really do intersect.
//
// line-sphere intersection algorithm lifted from Eric Haines chapter in 
// Glassner's "Introduction to Ray Tracing", pp. 35-7
//
SbBool
SbSphere::intersect(const SbLine &l, SbVec3f &enter, SbVec3f &exit) const
//
//////////////////////////////////////////////////////////////////////////////
{
    float   B,C;	// At^2 + Bt + C = 0, but A is 1 since we normalize Rd
    float   discr;	// discriminant (B^2 - 4AC)
    SbVec3f v;
    float   sqroot;
    SbBool  doesIntersect = TRUE;

    // setup B,C
    v = l.getPosition() - center;
    B = 2.0 * (l.getDirection().dot(v));
    C = v.dot(v) - (radius * radius);

    // compute discriminant
    // if negative, there is no intersection
    discr = B*B - 4.0*C;

    if (discr < 0.0) {
	// line and sphere do not intersect
	doesIntersect = FALSE;
    }
    else {
	sqroot = sqrtf(discr);
	    
	float t0 = (-B - sqroot) * 0.5;
	enter = l.getPosition() + (l.getDirection() * t0);
	
	float t1 = (-B + sqroot) * 0.5;
	exit = l.getPosition() + (l.getDirection() * t1);
    }

    return doesIntersect;
}
Пример #8
0
/*!
  Returns the two closest points on the lines.  If the lines are
  parallel, all points are equally close and we return \c FALSE. If
  the lines are not parallel, the point positions will be stored in \a
  ptOnThis and \a ptOnLine2, and we'll return \c TRUE.

  Note that both SbLine instances are considered to be infinite in
  both directions from their definition points, as far as this
  function is concerned.

  \sa getClosestPoint().
*/
SbBool
SbLine::getClosestPoints(const SbLine& line2,
                         SbVec3f& ptOnThis, SbVec3f& ptOnLine2) const
{
#if 1 
  // new optimized version based on formulas from from Boyko Bantchev

  // p1 = point on line 1
  // p2 = point on line 2
  // d1 = line 1 direction
  // d2 = line 2 direction
  // q1 = closest point on line 1
  // q2 = closest point on line 2

  // The solution (q1 and q2) must be on their respective 
  // lines:
  //
  // q1 = p1 + t1 * d1                               (0)
  // q2 = p2 + t2 * d2
  //
  // we set u = p2 - p1, and get:
  //
  // q2 - q1 = u + t2*d2 - t1*d1                     (1)
  //
  // the solution line q2 - q1 is orthogonal to d1 and d2 
  // (or a null vector if the lines intersect), which yields:
  //
  // (u + t2*d2 - t1*d1) · d1 = 0                    (2)
  // (u + t2*d2 - t1*d1) · d2 = 0
  //
  // we know |d1| and |d2| == 1, and set d1 · d2 = t
  //
  // t1 - t*t2 = u · d1
  // t*t1 - t2 = u · d2
  //
  // Solve for t1, and find q1 using (0):
  //
  // t1 = (u·d1 - t * (u·d2))/ (1 - t^2)
  //
  // just find q2 by using line2.getClosestPoint(q1)

  SbVec3f p1 = this->pos;
  SbVec3f p2 = line2.pos;
  
  SbVec3f d1 = this->dir;
  SbVec3f d2 = line2.dir;

  SbVec3f u = p2-p1;
  float t = d1.dot(d2);

  const float eps = 1.0e-06f;
  if (t < -1.0f + eps || t > 1.0f-eps) {
    // lines are parallel
    return FALSE;
  }
  t = (u.dot(d1) - t * u.dot(d2)) / (1-t*t);
  ptOnThis = p1 + t * d1;
  ptOnLine2 = line2.getClosestPoint(ptOnThis);
  return TRUE;
#else // old version

#if COIN_DEBUG
  if(this->getDirection().length() == 0.0)
    SoDebugError::postWarning("SbLine::getClosestPoints",
                              "This line has no direction (zero vector).");
  if(line2.getDirection().length() == 0.0)
    SoDebugError::postWarning("SbLine::getClosestPoints",
                              "argument line has no direction (zero vector).");
#endif // COIN_DEBUG

  // Check if the lines are parallel.
  // FIXME: should probably use equals() here.
  if(line2.dir == this->dir) return FALSE;
  else if(line2.dir == -this->dir) return FALSE;


  // From the discussion on getClosestPoint(), we know that the point
  // we wish to find on a line can be expressed as:
  //
  //                  (Q1-P0)·D0
  //   Q0 = P0 + D0 * ----------
  //                     |D0|
  //
  // ...where P0 is a point on the first line, D0 is the direction
  // vector and Q1 is the "closest point" on the other line. From this
  // we get two equations with two unknowns. By substituting for
  // Q1 we get a new equation with a single unknown, Q0:
  //
  //                   (         (Q0 - P1)·D1    )
  //                   (P1 + D1 * ------------ - P0) · D0
  //                   (             |D1|        )
  //   Q0 = P0 + D0 * ------------------------------------
  //                                |D0|
  //
  // Which obviously is bloody hard (perhaps impossible?) to solve
  // analytically. Damn. Back to the pen and pencil stuff.
  //
  // Ok, new try. Since we're looking for the minimum distance between the
  // two lines, we should be able to solve it by expressing the distance
  // between the points we want to find as a parametrized function and
  // take the derivative:
  //
  //   f(t0, t1) = |Q1 - Q0| = |P1+D1*t1 - (P0+D0*t0)|
  //
  //                         (t1*D1 - P0)·D0
  // t0 can be expressed as  ---------------  which gives us
  //                               |D0|
  //
  //   f(t) = |P1 + D1*t - P0 - D0N * ((t*D1 - P0)·D0)|, t = t1
  //                                                     D0N = D0 normalized
  //                               _____________
  // ..which is eual to   f(t) = \/Þ² + ß² + ð²  , where Þ, ß, and ð
  // is the full expression above with the x, y, and z components
  // of the vectors.
  //
  // Since we're looking for the minimum value of the function, we can just
  // ignore the square root. We'll do the next parts of the math on a
  // general components case, since it's the same for the x, y and z parts.
  //
  // Expanding any of the Þ, ß, or ð expressions, we get this:
  //   (P1[i] - D1[i]*t - P0[i] - D0N[i]*D0[x]*D1[x]*t + D0N[i]*D0[x]*P0[x]
  //      - D0N[i]*D0[y]*D1[y]*t + D0N[i]*D0[y]*P0[y] - D0N[i]*D0[z]*D1[z]*t
  //      + D0N[i]*D0[z]*P0[z])² ,
  // where i=[x|y|z].
  //
  // Derivating this by using the chain rule (i.e. g(t)² =
  // 2*g(t)*g'(t)), we'll get this equation for finding the t yielding
  // the minimum distance between two points Q0 and Q1 on the lines:
  //
  //      -(cx*dx+cy*dy+cz*dz)
  //  t = --------------------
  //        dx² + dy² + dz²
  //
  //  di = D1[i] - D0N[i] * (D0[x]*D1[x] + D0[y]*D1[y] + D0[z]*D1[z])
  // and
  //  ci = P1[i] - P0[i] + D0N[i] * (D0[x]*P0[x] + D0[y]*P0[y] + D0[z]*P0[z])
  // where i=[x|y|z].
  //
  // Now we'll substitute t back in for t1 in   Q1 = P1 + D1*t1, which'll
  // also let us find Q0 by an invocation of getClosestPoint().
  //
  // That's it. I can't believe this took me 4 hours to complete. Code worked
  // on the first run, though. :-)
  //                                                           19980815 mortene.

  SbVec3f P0 = this->pos;
  SbVec3f P1 = line2.pos;
  SbVec3f D0 = this->dir;
  SbVec3f D1 = line2.dir;
  SbVec3f D0N = D0;

  // we warn about lines with no direction above, just normalize
  (void) D0N.normalize();

  float c[3], d[3];

  for (int i=0; i < 3; i++) {
    d[i] =
      D1[i] - D0N[i]*(D0[0]*D1[0] + D0[1]*D1[1] + D0[2]*D1[2]);
    c[i] =
      P1[i] - P0[i] + D0N[i]*(D0[0]*P0[0] + D0[1]*P0[1] + D0[2]*P0[2]);
  }

  float t = -(c[0]*d[0]+c[1]*d[1]+c[2]*d[2]) / (d[0]*d[0]+d[1]*d[1]+d[2]*d[2]);

  ptOnLine2 = line2.pos + line2.dir * t;
  ptOnThis = this->getClosestPoint(ptOnLine2);

  return TRUE;
#endif
}
Пример #9
0
SbVec3f
SbLineProjector::project(const SbVec2f &point)
//
////////////////////////////////////////////////////////////////////////
{
    // Convert two line points to world space
	SbLine worldLine;
	workingToWorld.multLineMatrix( line, worldLine );
	SbVec3f wldPt1 = worldLine.getPosition();
	SbVec3f wldDir = worldLine.getDirection();
	SbVec3f wldPt2 = wldPt1 + wldDir;

    // Convert two line points to normalized screen space.
	SbVec3f nrmScnPt1, nrmScnPt2;
	viewVol.projectToScreen( wldPt1, nrmScnPt1 );
	viewVol.projectToScreen( wldPt2, nrmScnPt2 );

    // Convert two line points and input point 
    // to viewPlane space, a screen space that's got view plane's aspect ratio:
	float vvW  = (viewVol.getWidth()  == 0.0) ? 1 : viewVol.getWidth();
	float vvH  = (viewVol.getHeight() == 0.0) ? 1 : viewVol.getHeight();
	SbVec3f     vpPt1( nrmScnPt1[0] * vvW, nrmScnPt1[1] * vvH, 0);
	SbVec3f     vpPt2( nrmScnPt2[0] * vvW, nrmScnPt2[1] * vvH, 0);
	SbVec3f vpInPoint(     point[0] * vvW,     point[1] * vvH, 0);

    // Create the viewPlaneLine -- our line expressed in viewPlane space:
        SbLine  viewPlaneLine( vpPt1, vpPt2 );

    // In viewplane space, find the closest point on our line to the cursor.
	SbVec3f vpClosestPt = viewPlaneLine.getClosestPoint( vpInPoint );
	vpClosestPt.setValue( vpClosestPt[0], vpClosestPt[1], 0 );

    // If we've got a perspective view, we may need to clamp the point we
    // choose so that it's not too close to the vanishing point.
    // Otherwise we'll just use our vpClosestPt

	SbVec3f vpClampedPt = vpClosestPt;

	if ( viewVol.getProjectionType() == SbViewVolume::PERSPECTIVE ) {

	// Find the vanishing point of our line in viewPlane space: 
	    // Convert the direction of our line from world space into space 
	    // after the affine matrix (i.e. just before the projection matrix)
	    SbMatrix vvAffine, vvProj;
	    viewVol.getMatrices( vvAffine, vvProj );
	    SbVec3f postAffineDir;
	    vvAffine.multDirMatrix( wldDir, postAffineDir ); 

	  // If the direction of the line is parallel to the view plane,
	  // then the z component of postAffineDir is 0.
	  // In this case, we will not need to clamp our point and moreover,
	  // if we try we'll wind up dividing by zero pretty soon.
	  if ( postAffineDir[2] != 0.0 ) {

	    // If we send a line out from (0,0,0) into the viewVolume towards 
	    // postAffineDir, it will vanish at the same point as any other line
	    // parallel to this direction.  Also, all points along this line 
	    // will project to the same point on the near (or far) plane.
	    // So a line connecting (0,0,0) and the point at postAffineDir will
	    // intersect the near plane at the vanishing point.  Transforming 
	    // any point on this line by vvProj will yield the same x,y result 
	    // and the z component will vary with depth.
	    // So multiply the postAffineDir as a vector through the projection
	    // matrix and use the x,y for the vanishing point.
	    SbVec3f projVanish;
	    vvProj.multVecMatrix( postAffineDir, projVanish );

	    // Convert from [-1,1] range to [0,1] range for normalized coords.
	    SbVec3f nrmScnVanish;
	    nrmScnVanish[0] = (1.0 + projVanish[0]) * 0.5;
	    nrmScnVanish[1] = (1.0 + projVanish[1]) * 0.5;

	    // Finally, get the vanishing point in viewPlane coords:
	    SbVec3f vpVanish( nrmScnVanish[0] * vvW, nrmScnVanish[1] * vvH, 0 );

#if 0
	    // Check that the vanishing point is correct:
	    // Project nrmScnVanish on the plane to see if it goes along wldDir:
	    SbVec2f nrmScnVanish2( nrmScnVanish[0], nrmScnVanish[1] );
	    SbLine vanishWorldLine;
	    viewVol.projectPointToLine( nrmScnVanish2, vanishWorldLine );
	    SbVec3f test = vanishWorldLine.getDirection();
	    fprintf(stderr,"wldDir = %f %f %f\n",wldDir[0],wldDir[1],wldDir[2]);
	    fprintf(stderr,"checkDir = %f %f %f\n", test[0], test[1],test[2]);
#endif

	// The points vpPt1 and vpPt2 define the line in viewPlane space.
	// We can't go on the other side of the vanishing point from these 
	// defining points in screen space or the point will be undefined when 
	// we cast it into world space.
	// So clamp our selected point to lie on vpPt1's side of the vanishing 
	// point.  Since points near the vanishing point will also be incredibly
	// far away, introduce an (arbitrary) metric, VANISH_DELTA.
	// Our selection must be more than VANISH_DELTA times the average of
	// viewVolumeHeight and viewVolumeWidth from the vanishing point.
#define VANISH_DELTA .01
	    float vanishSafetyDist = VANISH_DELTA * .5 * (vvW + vvH);
#undef VANISH_DELTA
	    // Make pt0, the point from which we measure distances along vpLine.
	    // It will be one extra unit away from vpVanish than safetyDist
	    SbVec3f pt0 = viewPlaneLine.getPosition();
	    pt0.setValue( pt0[0], pt0[1], 0 );
	    SbVec3f pt0ToVanishDir = vpVanish - pt0;
	    pt0ToVanishDir.normalize();
	    float   pt0ToVanishDist = vanishSafetyDist + 1.0;
	    pt0 = vpVanish - pt0ToVanishDist * pt0ToVanishDir;

	    // Get vector and dist from pt0 to vpClosestPt
	    SbVec3f pt0ToClosest = vpClosestPt - pt0;
	    float   pt0ToClosestDist = pt0ToClosest.length();

	    // If vpClosestPt is too far from pt0, clamp it:
	    float   clampDist = pt0ToVanishDist - vanishSafetyDist;
	    if (    (pt0ToClosestDist > clampDist) 
		 && (pt0ToClosest.dot(pt0ToVanishDir) > 0.0) ) {
		vpClampedPt = pt0 + clampDist * pt0ToVanishDir;
	    }
	  }
	}

    // Convert result back into normalized screen space:
	SbVec2f nrmScnClampedPt( vpClampedPt[0] / vvW, vpClampedPt[1] / vvH);

    // Create a line in working space by projecting our point into the scene:
	SbVec3f result, whoCares;
	SbLine workingLine = getWorkingLine( nrmScnClampedPt );

    // Find point on the projector line closest to workingLine
	if (! line.getClosestPoints(workingLine, result, whoCares)) {
#ifdef DEBUG
	    SoDebugError::post("SbLineProjector::project",
			       "Couldn't get closest point");
#endif
    }

    return result;
}
SbRotation
SbSphereSectionProjector::getRotation(const SbVec3f &p1, const SbVec3f &p2)
//
////////////////////////////////////////////////////////////////////////
{
    SbBool tol1 = isWithinTolerance(p1);
    SbBool tol2 = isWithinTolerance(p2);

    if (tol1 && tol2) {
	// both points in tolerance, rotate about
	// sphere center

	return SbRotation(
	    p1 - sphere.getCenter(),
	    p2 - sphere.getCenter());
    }
    else if (!tol1 && !tol2) {
	// both points out of tolerance, rotate about
	// plane point

	// Would like to just use this:
	SbRotation badRot = SbRotation(p1 - planePoint, p2 - planePoint);
	// but fp instablity gives back a goofy axis, so we don't get
	// pure roll.

	// So we need to snap the axis to be parallel to plane dir
	SbVec3f badAxis; float goodAngle;
	badRot.getValue(badAxis, goodAngle);

	SbVec3f goodAxis;
	if (badAxis.dot(planeDir) > 0.0)
	    goodAxis = planeDir;
	else 	    
	    goodAxis = -planeDir;

	SbRotation rollRot(goodAxis, goodAngle);

	//Now find rotation in the direction perpendicular to this:
	SbVec3f diff1 = p1 - planePoint;
	SbVec3f diff2 = p2 - planePoint;
	float d = diff2.length() - diff1.length();

	// Check for degenerate cases
	float theta = d / sphere.getRadius();
	if ( fabs(theta) < 0.000001 || fabs(theta) > 1.0 )
	    return rollRot;

	diff1.normalize();
	SbVec3f pullAxis = planeDir.cross( diff1 );
	pullAxis.normalize();
	SbRotation pullRot(pullAxis, getRadialFactor() * theta );

	SbRotation totalRot = rollRot * pullRot;
	return totalRot;

    }
    else {
	// one point in, one point out, so rotate about
	// the center of the sphere from the point on the
	// sphere to the intersection of the plane and the
	// sphere closest to the point off the sphere

	SbLine planeLine;
	SbVec3f intersection;

	if (tol1) {
	    planeLine.setValue(planePoint, p2);
	}
	else {
	    planeLine.setValue(planePoint, p1);
	}

	if (! sphere.intersect(planeLine, intersection))
#ifdef DEBUG
	    SoDebugError::post("SbSphereSectionProjector::getRotation",
			       "Couldn't intersect plane line with sphere");
#else
	/* Do nothing */;
#endif

	if (tol1) {
	    // went off sphere
	    return SbRotation(
		p1 - sphere.getCenter(),
		intersection - sphere.getCenter());
	}
	else {
	    // came on to sphere
	    // "Hey cutie. You've got quite a radius..."
	    return SbRotation(
		intersection - sphere.getCenter(),
		p2 - sphere.getCenter());
	}
    }

}