3.7 Curves

While triangles can be used to represent thin shapes for modeling fine geometry like hair, fur, or fields of grass, it’s worthwhile to have a specialized Shape in order to more efficiently render these sorts of objects, since many individual instances of them are often present. The Curve shape, introduced in this section, represents thin geometry modeled with cubic Bézier splines, which are defined by four control points, normal p 0 , normal p 1 , normal p 2 , and normal p 3 . The Bézier spline passes through the first and last control points; intermediate points are given by the polynomial

normal p Subscript Baseline left-parenthesis u right-parenthesis equals left-parenthesis 1 minus u right-parenthesis cubed normal p 0 plus 3 left-parenthesis 1 minus u right-parenthesis squared u normal p 1 plus 3 left-parenthesis 1 minus u right-parenthesis u squared normal p 2 plus u cubed normal p 3 period
(3.3)

(See Figure 3.15.) Given a curve specified in another cubic basis, such as a Hermite spline, it’s easy enough to convert to Bézier basis, so the implementation here leaves that burden on the user. This functionality could be easily added if it was frequently needed.

Figure 3.15: A cubic Bézier curve is defined by four control points, normal p Subscript Baseline Subscript i . The curve normal p Subscript Baseline left-parenthesis u right-parenthesis , defined in Equation (3.3), passes through the first and last control points at u equals 0 and u equals 1 , respectively.

The Curve shape is defined by a 1D Bézier curve along with a width that is linearly interpolated from starting and ending widths along its extent. Together, these define a flat 2D surface (Figure 3.16). It’s possible to directly intersect rays with this representation without tessellating it, which in turn makes it possible to efficiently render smooth curves without using too much storage.

Figure 3.16: Basic Geometry of the Curve Shape. A 1D Bézier curve is offset by half of the specified width in both the directions orthogonal to the curve at each point along it. The resulting area represents the curve’s surface.

Figure 3.17 shows a bunny model with fur modeled with over one million Curves.

Figure 3.17: Furry Bunny. Bunny model with over one million Curve shapes used to model fur. Here, we’ve used unrealistically long curves to better show off the Curve’s capabilities.

<<Curve Declarations>>= 
class Curve : public Shape { public: <<Curve Public Methods>> 
Curve(const Transform *ObjectToWorld, const Transform *WorldToObject, bool reverseOrientation, const std::shared_ptr<CurveCommon> &common, Float uMin, Float uMax) : Shape(ObjectToWorld, WorldToObject, reverseOrientation), common(common), uMin(uMin), uMax(uMax) { } Bounds3f ObjectBound() const; bool Intersect(const Ray &ray, Float *tHit, SurfaceInteraction *isect, bool testAlphaTexture) const; Float Area() const; Interaction Sample(const Point2f &u) const;
private: <<Curve Private Methods>> 
bool recursiveIntersect(const Ray &r, Float *tHit, SurfaceInteraction *isect, const Point3f cp[4], const Transform &rayToObject, Float u0, Float u1, int depth) const;
<<Curve Private Data>> 
const std::shared_ptr<CurveCommon> common; const Float uMin, uMax;
};

There are three types of curves that the Curve shape can represent, shown in Figure 3.18.

  • Flat: Curves with this representation are always oriented to face the ray being intersected with them; they are useful for modeling fine swept cylindrical shapes like hair or fur.
  • Cylinder: For curves that span a few pixels on the screen (like spaghetti seen from not too far away), the Curve shape can compute a shading normal that makes the curve appear to actually be a cylinder.
  • Ribbon: This variant is useful for modeling shapes that don’t actually have a cylindrical cross section (such as a blade of grass).

Figure 3.18: The Three Types of Curves That the Curve Shape Can Represent. On the left is a flat curve that is always oriented to be perpendicular to a ray approaching it. The middle is a variant of this curve where the shading normal is set so that the curve appears to be cylindrical. On the right is a ribbon, which has a fixed orientation at its starting and ending points; intermediate orientations are smoothly interpolated between them.

The CurveType enumerant records which of them a given Curve instance models.

The flat and cylinder curve variants are intended to be used as convenient approximations of deformed cylinders. It should be noted that intersections found with respect to them do not correspond to a physically realizable 3D shape, which can potentially lead to minor inconsistencies when taking a scene with true cylinders as a reference.

<<CurveType Declarations>>= 
enum class CurveType { Flat, Cylinder, Ribbon };

Given a curve specified in a pbrt scene description file, it can be worthwhile to split it into a few segments, each covering part of the u parametric range of the curve. (One reason for doing so is that axis-aligned bounding boxes don’t tightly bound wiggly curves, but subdividing Bézier splines makes them less wiggly—the variation diminishing property of polynomial splines.) Therefore, the Curve constructor takes both a parametric range of u values, left-bracket u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal a normal x Baseline right-bracket , as well as a pointer to a CurveCommon structure, which stores the control points and other information about the curve that is shared across curve segments. In this way, the memory footprint for individual curve segments is minimized, which makes it easier to keep many of them in memory.

<<Curve Public Methods>>= 
Curve(const Transform *ObjectToWorld, const Transform *WorldToObject, bool reverseOrientation, const std::shared_ptr<CurveCommon> &common, Float uMin, Float uMax) : Shape(ObjectToWorld, WorldToObject, reverseOrientation), common(common), uMin(uMin), uMax(uMax) { }

<<Curve Private Data>>= 
const std::shared_ptr<CurveCommon> common; const Float uMin, uMax;

The CurveCommon constructor mostly just initializes member variables with values passed into it for the control points, the curve width, etc. The control points provided to it should be in the curve’s object space.

For Ribbon curves, CurveCommon stores a surface normal to orient the curve at each endpoint. The constructor precomputes the angle between the two normal vectors and one over the sine of this angle; these values will be useful when computing the orientation of the curve at arbitrary points along its extent.

<<Curve Method Definitions>>= 
CurveCommon::CurveCommon(const Point3f c[4], Float width0, Float width1, CurveType type, const Normal3f *norm) : type(type), cpObj{c[0], c[1], c[2], c[3]}, width{width0, width1} { if (norm) { n[0] = Normalize(norm[0]); n[1] = Normalize(norm[1]); normalAngle = std::acos(Clamp(Dot(n[0], n[1]), 0, 1)); invSinNormalAngle = 1 / std::sin(normalAngle); } }

<<CurveCommon Declarations>>= 
struct CurveCommon { const CurveType type; const Point3f cpObj[4]; const Float width[2]; Normal3f n[2]; Float normalAngle, invSinNormalAngle; };

Bounding boxes of Curves can be computed by taking advantage of the convex hull property, a property of Bézier curves that says that they must lie within the convex hull of their control points. Therefore, the bounding box of the control points gives a conservative bound of the underlying curve. The ObjectBound() method first computes a bounding box of the control points of the 1D Bézier segment to bound the spline along the center of the curve. These bounds are then expanded by half the maximum width the curve takes on over its parametric extent to get the 3D bounds of the Shape that the Curve represents.

<<Curve Method Definitions>>+=  
Bounds3f Curve::ObjectBound() const { <<Compute object-space control points for curve segment, cpObj>>  Bounds3f b = Union(Bounds3f(cpObj[0], cpObj[1]), Bounds3f(cpObj[2], cpObj[3])); Float width[2] = { Lerp(uMin, common->width[0], common->width[1]), Lerp(uMax, common->width[0], common->width[1]) }; return Expand(b, std::max(width[0], width[1]) * 0.5f); }

The CurveCommon class stores the control points for the full curve, but Curve instances generally need the four control points that represent the Bézier curve for its u extent. These control points are computed using a technique called blossoming. The blossom p left-parenthesis u 0 comma u 1 comma u 2 right-parenthesis of a cubic Bézier spline is defined by three stages of linear interpolation, starting with the original control points:

StartLayout 1st Row 1st Column normal a Subscript i 2nd Column equals left-parenthesis 1 minus u 0 right-parenthesis normal p Subscript Baseline Subscript i Baseline plus u 0 normal p Subscript Baseline Subscript i plus 1 Baseline i element-of left-bracket 0 comma 1 comma 2 right-bracket 2nd Row 1st Column normal b Subscript j 2nd Column equals left-parenthesis 1 minus u 1 right-parenthesis normal a Subscript j Baseline plus u 1 normal a Subscript j plus 1 Baseline j element-of left-bracket 0 comma 1 right-bracket 3rd Row 1st Column normal c 2nd Column equals left-parenthesis 1 minus u 2 right-parenthesis normal b 0 plus u 2 normal b 1 EndLayout
(3.4)

The blossom p left-parenthesis u comma u comma u right-parenthesis gives the curve’s value at position u . (To verify this for yourself, expand Equation (3.4) using u Subscript i Baseline equals u , simplify, and compare to Equation (3.3).)

BlossomBezier() implements this computation.

<<Curve Utility Functions>>= 
static Point3f BlossomBezier(const Point3f p[4], Float u0, Float u1, Float u2) { Point3f a[3] = { Lerp(u0, p[0], p[1]), Lerp(u0, p[1], p[2]), Lerp(u0, p[2], p[3]) }; Point3f b[2] = { Lerp(u1, a[0], a[1]), Lerp(u1, a[1], a[2]) }; return Lerp(u2, b[0], b[1]); }

Figure 3.19: Blossoming to Find Control Points for a Segment of a Bézier Curve. The four blossoms in Equation (3.5) give the control points for the curve from u Subscript normal m normal i normal n to u Subscript normal m normal a normal x . Blossoming provides an elegant method to compute the Bézier control points of the curve that represent a subset of the overall curve.

The four control points for the curve segment over the range u Subscript normal m normal i normal n to u Subscript normal m normal a normal x are given by the blossoms:

StartLayout 1st Row 1st Column normal p 0 2nd Column equals normal p Subscript Baseline left-parenthesis u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal i normal n Baseline right-parenthesis 2nd Row 1st Column normal p 1 2nd Column equals normal p Subscript Baseline left-parenthesis u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal a normal x Baseline right-parenthesis 3rd Row 1st Column normal p 2 2nd Column equals normal p Subscript Baseline left-parenthesis u Subscript normal m normal i normal n Baseline comma u Subscript normal m normal a normal x Baseline comma u Subscript normal m normal a normal x Baseline right-parenthesis 4th Row 1st Column normal p 3 2nd Column equals normal p Subscript Baseline left-parenthesis u Subscript normal m normal a normal x Baseline comma u Subscript normal m normal a normal x Baseline comma u Subscript normal m normal a normal x Baseline right-parenthesis EndLayout
(3.5)

(Figure 3.19).

Given this machinery, it’s straightforward to compute the four control points for the curve segment that a Curve is responsible for.

<<Compute object-space control points for curve segment, cpObj>>= 

The Curve intersection algorithm is based on discarding curve segments as soon as it can be determined that the ray definitely doesn’t intersect them and otherwise recursively splitting the curve in half to create two smaller segments that are then tested. Eventually, the curve is linearly approximated for an efficient intersection test. After some preparation, the recursiveIntersect() call starts this process with the full segment that the Curve represents.

<<Curve Method Definitions>>+=  
bool Curve::Intersect(const Ray &r, Float *tHit, SurfaceInteraction *isect, bool testAlphaTexture) const { <<Transform Ray to object space>> 
Vector3f oErr, dErr; Ray ray = (*WorldToObject)(r, &oErr, &dErr);
<<Compute object-space control points for curve segment, cpObj>>  <<Project curve control points to plane perpendicular to ray>> 
Vector3f dx, dy; CoordinateSystem(ray.d, &dx, &dy); Transform objectToRay = LookAt(ray.o, ray.o + ray.d, dx); Point3f cp[4] = { objectToRay(cpObj[0]), objectToRay(cpObj[1]), objectToRay(cpObj[2]), objectToRay(cpObj[3]) };
<<Compute refinement depth for curve, maxDepth>> 
Float L0 = 0; for (int i = 0; i < 2; ++i) L0 = std::max(L0, std::max(std::max(std::abs(cp[i].x - 2 * cp[i + 1].x + cp[i + 2].x), std::abs(cp[i].y - 2 * cp[i + 1].y + cp[i + 2].y)), std::abs(cp[i].z - 2 * cp[i + 1].z + cp[i + 2].z))); Float eps = std::max(common->width[0], common->width[1]) * .05f; // width / 20 #define LOG4(x) (std::log(x) * 0.7213475108f) Float fr0 = LOG4(1.41421356237f * 12.f * L0 / (8.f * eps)); #undef LOG4 int r0 = (int)std::round(fr0); int maxDepth = Clamp(r0, 0, 10);
return recursiveIntersect(ray, tHit, isect, cp, Inverse(objectToRay), uMin, uMax, maxDepth); }

Like the ray–triangle intersection algorithm from Section 3.6.2, the ray–curve intersection test is based on transforming the curve to a coordinate system with the ray’s origin at the origin of the coordinate system and the ray’s direction aligned to be along the plus z axis. Performing this transformation at the start greatly reduces the number of operations that must be performed for intersection tests.

For the Curve shape, we’ll need an explicit representation of the transformation, so the LookAt() function is used to generate it here. The origin is the ray’s origin, the “look at” point is a point offset from the origin along the ray’s direction, and the “up” direction is an arbitrary direction orthogonal to the ray direction.

<<Project curve control points to plane perpendicular to ray>>= 
Vector3f dx, dy; CoordinateSystem(ray.d, &dx, &dy); Transform objectToRay = LookAt(ray.o, ray.o + ray.d, dx); Point3f cp[4] = { objectToRay(cpObj[0]), objectToRay(cpObj[1]), objectToRay(cpObj[2]), objectToRay(cpObj[3]) };

The maximum number of times to subdivide the curve is computed so that the maximum distance from the eventual linearized curve at the finest refinement level is bounded to be less than a small fixed distance. We won’t go into the details of this computation, which is implemented in the fragment <<Compute refinement depth for curve, maxDepth>>.

The recursiveIntersect() method then tests whether the given ray intersects the given curve segment over the given parametric range left-bracket monospace u Baseline monospace 0 monospace comma monospace u Baseline monospace 1 monospace right-bracket .

<<Curve Method Definitions>>+= 
bool Curve::recursiveIntersect(const Ray &ray, Float *tHit, SurfaceInteraction *isect, const Point3f cp[4], const Transform &rayToObject, Float u0, Float u1, int depth) const { <<Try to cull curve segment versus ray>> 
<<Compute bounding box of curve segment, curveBounds>> 
Bounds3f curveBounds = Union(Bounds3f(cp[0], cp[1]), Bounds3f(cp[2], cp[3])); Float maxWidth = std::max(Lerp(u0, common->width[0], common->width[1]), Lerp(u1, common->width[0], common->width[1])); curveBounds = Expand(curveBounds, 0.5 * maxWidth);
<<Compute bounding box of ray, rayBounds>> 
Float rayLength = ray.d.Length(); Float zMax = rayLength * ray.tMax; Bounds3f rayBounds(Point3f(0, 0, 0), Point3f(0, 0, zMax));
if (Overlaps(curveBounds, rayBounds) == false) return false;
if (depth > 0) { <<Split curve segment into sub-segments and test for intersection>> 
Float uMid = 0.5f * (u0 + u1); Point3f cpSplit[7]; SubdivideBezier(cp, cpSplit); return (recursiveIntersect(ray, tHit, isect, &cpSplit[0], rayToObject, u0, uMid, depth - 1) || recursiveIntersect(ray, tHit, isect, &cpSplit[3], rayToObject, uMid, u1, depth - 1));
} else { <<Intersect ray with curve segment>> 
<<Test ray against segment endpoint boundaries>> 
<<Test sample point against tangent perpendicular at curve start>> 
Float edge = (cp[1].y - cp[0].y) * -cp[0].y + cp[0].x * (cp[0].x - cp[1].x); if (edge < 0) return false;
<<Test sample point against tangent perpendicular at curve end>> 
edge = (cp[2].y - cp[3].y) * -cp[3].y + cp[3].x * (cp[3].x - cp[2].x); if (edge < 0) return false;
<<Compute line w that gives minimum distance to sample point>> 
Vector2f segmentDirection = Point2f(cp[3]) - Point2f(cp[0]); Float denom = segmentDirection.LengthSquared(); if (denom == 0) return false; Float w = Dot(-Vector2f(cp[0]), segmentDirection) / denom;
<<Compute u coordinate of curve intersection point and hitWidth>> 
Float u = Clamp(Lerp(w, u0, u1), u0, u1); Float hitWidth = Lerp(u, common->width[0], common->width[1]); Normal3f nHit; if (common->type == CurveType::Ribbon) { <<Scale hitWidth based on ribbon orientation>> 
Float sin0 = std::sin((1 - u) * common->normalAngle) * common->invSinNormalAngle; Float sin1 = std::sin(u * common->normalAngle) * common->invSinNormalAngle; nHit = sin0 * common->n[0] + sin1 * common->n[1]; hitWidth *= AbsDot(nHit, ray.d) / rayLength;
}
<<Test intersection point against curve width>> 
Vector3f dpcdw; Point3f pc = EvalBezier(cp, Clamp(w, 0, 1), &dpcdw); Float ptCurveDist2 = pc.x * pc.x + pc.y * pc.y; if (ptCurveDist2 > hitWidth * hitWidth * .25) return false; if (pc.z < 0 || pc.z > zMax) return false;
<<Compute v coordinate of curve intersection point>> 
Float ptCurveDist = std::sqrt(ptCurveDist2); Float edgeFunc = dpcdw.x * -pc.y + pc.x * dpcdw.y; Float v = (edgeFunc > 0) ? 0.5f + ptCurveDist / hitWidth : 0.5f - ptCurveDist / hitWidth;
<<Compute hit t and partial derivatives for curve intersection>> 
if (tHit != nullptr) { *tHit = pc.z / rayLength; <<Compute error bounds for curve intersection>> 
Vector3f pError(2 * hitWidth, 2 * hitWidth, 2 * hitWidth);
<<Compute partial-differential normal p slash partial-differential u and partial-differential normal p slash partial-differential v for curve intersection>> 
Vector3f dpdu, dpdv; EvalBezier(common->cpObj, u, &dpdu); if (common->type == CurveType::Ribbon) dpdv = Normalize(Cross(nHit, dpdu)) * hitWidth; else { <<Compute curve partial-differential normal p slash partial-differential v for flat and cylinder curves>> 
Vector3f dpduPlane = (Inverse(rayToObject))(dpdu); Vector3f dpdvPlane = Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) * hitWidth; if (common->type == CurveType::Cylinder) { <<Rotate dpdvPlane to give cylindrical appearance>> 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);
} dpdv = rayToObject(dpdvPlane);
}
*isect = (*ObjectToWorld)(SurfaceInteraction( ray(pc.z), pError, Point2f(u, v), -ray.d, dpdu, dpdv, Normal3f(0, 0, 0), Normal3f(0, 0, 0), ray.time, this)); }
return true;
} }

The method starts by checking to see if the ray intersects the curve segment’s bounding box; if it doesn’t, no intersection is possible and it can return immediately.

<<Try to cull curve segment versus ray>>= 
<<Compute bounding box of curve segment, curveBounds>> 
Bounds3f curveBounds = Union(Bounds3f(cp[0], cp[1]), Bounds3f(cp[2], cp[3])); Float maxWidth = std::max(Lerp(u0, common->width[0], common->width[1]), Lerp(u1, common->width[0], common->width[1])); curveBounds = Expand(curveBounds, 0.5 * maxWidth);
<<Compute bounding box of ray, rayBounds>> 
Float rayLength = ray.d.Length(); Float zMax = rayLength * ray.tMax; Bounds3f rayBounds(Point3f(0, 0, 0), Point3f(0, 0, zMax));
if (Overlaps(curveBounds, rayBounds) == false) return false;

Along the lines of the implementation in Curve::ObjectBound(), a conservative bounding box for the segment can be found by taking the bounds of the curve’s control points and expanding by half of the maximum width of the curve over the u range being considered.

<<Compute bounding box of curve segment, curveBounds>>= 
Bounds3f curveBounds = Union(Bounds3f(cp[0], cp[1]), Bounds3f(cp[2], cp[3])); Float maxWidth = std::max(Lerp(u0, common->width[0], common->width[1]), Lerp(u1, common->width[0], common->width[1])); curveBounds = Expand(curveBounds, 0.5 * maxWidth);

Because the ray’s origin is at left-parenthesis 0 comma 0 comma 0 right-parenthesis and its direction is aligned with the plus z axis in the intersection space, its bounding box only includes the origin in x and y (Figure 3.20); its z extent is given by the z range that its parametric extent covers.

Figure 3.20: Ray–Curve Bounds Test. In the ray coordinate system, the ray’s origin is at left-parenthesis 0 comma 0 comma 0 right-parenthesis and its direction is aligned with the plus z axis. Therefore, if the 2D point left-parenthesis x comma y right-parenthesis equals left-parenthesis 0 comma 0 right-parenthesis is outside the x y bounding box of the curve segment, then it’s impossible that the ray intersects the curve.

<<Compute bounding box of ray, rayBounds>>= 
Float rayLength = ray.d.Length(); Float zMax = rayLength * ray.tMax; Bounds3f rayBounds(Point3f(0, 0, 0), Point3f(0, 0, zMax));

If the ray does intersect the curve’s bounding box and the recursive splitting hasn’t bottomed out, then the curve is split in half along the parametric u range. SubdivideBezier() computes seven control points: the first four correspond to the control points for the first half of the split curve, and the last four (starting with the last control point of the first half) correspond to the control points for the second half. Two calls to recursiveIntersect() test the two sub-segments.

<<Split curve segment into sub-segments and test for intersection>>= 
Float uMid = 0.5f * (u0 + u1); Point3f cpSplit[7]; SubdivideBezier(cp, cpSplit); return (recursiveIntersect(ray, tHit, isect, &cpSplit[0], rayToObject, u0, uMid, depth - 1) || recursiveIntersect(ray, tHit, isect, &cpSplit[3], rayToObject, uMid, u1, depth - 1));

While we could use the BlossomBezier() function to compute the control points of the subdivided curves, they can be more efficiently computed by taking advantage of the fact that we’re always splitting the curve exactly in the middle of its parametric extent. This computation is implemented in the SubdivideBezier() function; the seven control points it computes correspond to using left-parenthesis 0 comma 0 comma 0 right-parenthesis , left-parenthesis 0 comma 0 comma 1 slash 2 right-parenthesis , left-parenthesis 0 comma 1 slash 2 comma 1 slash 2 right-parenthesis , left-parenthesis 1 slash 2 comma 1 slash 2 comma 1 slash 2 right-parenthesis , left-parenthesis 1 slash 2 comma 1 slash 2 comma 1 right-parenthesis , left-parenthesis 1 slash 2 comma 1 comma 1 right-parenthesis , and left-parenthesis 1 comma 1 comma 1 right-parenthesis as blossoms in Equation (3.4).

<<Curve Utility Functions>>+=  
inline void SubdivideBezier(const Point3f cp[4], Point3f cpSplit[7]) { cpSplit[0] = cp[0]; cpSplit[1] = (cp[0] + cp[1]) / 2; cpSplit[2] = (cp[0] + 2 * cp[1] + cp[2]) / 4; cpSplit[3] = (cp[0] + 3 * cp[1] + 3 * cp[2] + cp[3]) / 8; cpSplit[4] = (cp[1] + 2 * cp[2] + cp[3]) / 4; cpSplit[5] = (cp[2] + cp[3]) / 2; cpSplit[6] = cp[3]; }

After a number of subdivisions, an intersection test is performed. Parts of this test are made more efficient by using a linear approximation of the curve; the variation diminishing property allows us to make this approximation without introducing too much error.

<<Intersect ray with curve segment>>= 
<<Test ray against segment endpoint boundaries>> 
<<Test sample point against tangent perpendicular at curve start>> 
Float edge = (cp[1].y - cp[0].y) * -cp[0].y + cp[0].x * (cp[0].x - cp[1].x); if (edge < 0) return false;
<<Test sample point against tangent perpendicular at curve end>> 
edge = (cp[2].y - cp[3].y) * -cp[3].y + cp[3].x * (cp[3].x - cp[2].x); if (edge < 0) return false;
<<Compute line w that gives minimum distance to sample point>> 
Vector2f segmentDirection = Point2f(cp[3]) - Point2f(cp[0]); Float denom = segmentDirection.LengthSquared(); if (denom == 0) return false; Float w = Dot(-Vector2f(cp[0]), segmentDirection) / denom;
<<Compute u coordinate of curve intersection point and hitWidth>> 
Float u = Clamp(Lerp(w, u0, u1), u0, u1); Float hitWidth = Lerp(u, common->width[0], common->width[1]); Normal3f nHit; if (common->type == CurveType::Ribbon) { <<Scale hitWidth based on ribbon orientation>> 
Float sin0 = std::sin((1 - u) * common->normalAngle) * common->invSinNormalAngle; Float sin1 = std::sin(u * common->normalAngle) * common->invSinNormalAngle; nHit = sin0 * common->n[0] + sin1 * common->n[1]; hitWidth *= AbsDot(nHit, ray.d) / rayLength;
}
<<Test intersection point against curve width>> 
Vector3f dpcdw; Point3f pc = EvalBezier(cp, Clamp(w, 0, 1), &dpcdw); Float ptCurveDist2 = pc.x * pc.x + pc.y * pc.y; if (ptCurveDist2 > hitWidth * hitWidth * .25) return false; if (pc.z < 0 || pc.z > zMax) return false;
<<Compute v coordinate of curve intersection point>> 
Float ptCurveDist = std::sqrt(ptCurveDist2); Float edgeFunc = dpcdw.x * -pc.y + pc.x * dpcdw.y; Float v = (edgeFunc > 0) ? 0.5f + ptCurveDist / hitWidth : 0.5f - ptCurveDist / hitWidth;
<<Compute hit t and partial derivatives for curve intersection>> 
if (tHit != nullptr) { *tHit = pc.z / rayLength; <<Compute error bounds for curve intersection>> 
Vector3f pError(2 * hitWidth, 2 * hitWidth, 2 * hitWidth);
<<Compute partial-differential normal p slash partial-differential u and partial-differential normal p slash partial-differential v for curve intersection>> 
Vector3f dpdu, dpdv; EvalBezier(common->cpObj, u, &dpdu); if (common->type == CurveType::Ribbon) dpdv = Normalize(Cross(nHit, dpdu)) * hitWidth; else { <<Compute curve partial-differential normal p slash partial-differential v for flat and cylinder curves>> 
Vector3f dpduPlane = (Inverse(rayToObject))(dpdu); Vector3f dpdvPlane = Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) * hitWidth; if (common->type == CurveType::Cylinder) { <<Rotate dpdvPlane to give cylindrical appearance>> 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);
} dpdv = rayToObject(dpdvPlane);
}
*isect = (*ObjectToWorld)(SurfaceInteraction( ray(pc.z), pError, Point2f(u, v), -ray.d, dpdu, dpdv, Normal3f(0, 0, 0), Normal3f(0, 0, 0), ray.time, this)); }
return true;

Figure 3.21: Curve Segment Boundaries. The intersection test for a segment of a larger curve computes edge functions for the lines that are perpendicular to the segment endpoints (dashed lines). If a potential intersection point (solid dot) is on the other side of the edge than the segment, it is rejected; another curve segment (if present on that side) should account for this intersection instead.

It’s important that the intersection test only accept intersections that are on the Curve’s surface for the u segment currently under consideration. Therefore, the first step of the intersection test is to compute edge functions for lines perpendicular to the curve starting point and ending point and to classify the potential intersection point against them (Figure 3.21).

<<Test ray against segment endpoint boundaries>>= 
<<Test sample point against tangent perpendicular at curve start>> 
Float edge = (cp[1].y - cp[0].y) * -cp[0].y + cp[0].x * (cp[0].x - cp[1].x); if (edge < 0) return false;
<<Test sample point against tangent perpendicular at curve end>> 
edge = (cp[2].y - cp[3].y) * -cp[3].y + cp[3].x * (cp[3].x - cp[2].x); if (edge < 0) return false;

Projecting the curve control points into the ray coordinate system makes this test more efficient for two reasons. First, because the ray’s direction is oriented with the plus z axis, the problem is reduced to a 2D test in x and y . Second, because the ray origin is at the origin of the coordinate system, the point we need to classify is left-parenthesis 0 comma 0 right-parenthesis , which simplifies evaluating the edge function, just like the ray–triangle intersection test.

Edge functions were introduced for ray–triangle intersection tests in Equation (3.1); see also Figure 3.14. To define the edge function, we need any two points on the line perpendicular to the curve going through starting point. The first control point, normal p 0 , is a fine choice for the first point. For the second one, we’ll compute the vector perpendicular to the curve’s tangent and add that offset to the control point.

Differentiation of Equation (3.3) shows that the tangent to the curve at the first control point normal p 0 is 3 left-parenthesis normal p 1 minus normal p 0 right-parenthesis . The scaling factor doesn’t matter here, so we’ll use bold t equals normal p 1 minus normal p 0 here. Computing the vector perpendicular to the tangent is easy in 2D: it’s just necessary to swap the x and y coordinates and negate one of them. (To see why this works, consider the dot product left-parenthesis x comma y right-parenthesis dot left-parenthesis y comma negative x right-parenthesis equals x y plus minus y x equals 0 . Because the cosine of the angle between the two vectors is zero, they must be perpendicular.) Thus, the second point on the edge is

normal p 0 plus left-parenthesis normal p 1 Subscript y Baseline minus normal p 0 Subscript y Baseline comma minus left-parenthesis normal p 1 Subscript x Baseline minus normal p 0 Subscript x Baseline right-parenthesis right-parenthesis equals normal p 0 plus left-parenthesis normal p 1 Subscript y Baseline minus normal p 0 Subscript y Baseline comma normal p 0 Subscript x Baseline minus normal p 1 Subscript x Baseline right-parenthesis period

Substituting these two points into the definition of the edge function, Equation (3.1), and simplifying gives

e left-parenthesis normal p Subscript Baseline right-parenthesis equals left-parenthesis normal p 1 Subscript y Baseline minus normal p 0 Subscript y Baseline right-parenthesis left-parenthesis normal p Subscript Baseline Subscript y Baseline minus normal p 0 Subscript y Baseline right-parenthesis minus left-parenthesis normal p Subscript Baseline Subscript x Baseline minus normal p 0 Subscript x Baseline right-parenthesis left-parenthesis normal p 0 Subscript x Baseline minus normal p 1 Subscript x Baseline right-parenthesis period

Finally, substituting normal p Subscript Baseline equals left-parenthesis 0 comma 0 right-parenthesis gives the final expression to test:

e left-parenthesis left-parenthesis 0 comma 0 right-parenthesis right-parenthesis equals left-parenthesis normal p 1 Subscript y Baseline minus normal p 0 Subscript y Baseline right-parenthesis left-parenthesis minus normal p 0 Subscript y Baseline right-parenthesis plus normal p 0 Subscript x Baseline left-parenthesis normal p 0 Subscript x Baseline minus normal p 1 Subscript x Baseline right-parenthesis period

<<Test sample point against tangent perpendicular at curve start>>= 
Float edge = (cp[1].y - cp[0].y) * -cp[0].y + cp[0].x * (cp[0].x - cp[1].x); if (edge < 0) return false;

The <<Test sample point against tangent perpendicular at curve end>> fragment, not included here, does the corresponding test at the end of the curve.

The next part of the test is to determine the u value along the curve segment where the point left-parenthesis 0 comma 0 right-parenthesis is closest to the curve. This will be the intersection point, if it’s no farther than the curve’s width away from the center at that point. Determining this distance for a cubic Bézier curve is not efficient, so instead this intersection approach approximates the curve with a linear segment to compute this u value.

Figure 3.22: Approximation of a Cubic Bézier Curve with a Linear Segment. For this part of the ray–curve intersection test, we approximate the Bézier with a linear segment (dashed line) passing through its starting and ending points. (In practice, after being subdivided, the curve will be already nearly linear, so the error is less than this figure suggests.)

We’ll linearly approximate the Bézier curve with a line segment from its starting point normal p 0 to its end point normal p 3 that is parameterized by w . In this case, the position is normal p 0 at w equals 0 and normal p 3 at w equals 1 (Figure 3.22). Our task now is to compute the value of w along the line corresponding to the point on the line normal p prime that is closest to the point normal p Subscript . The key insight to apply is that at normal p prime , the vector from the corresponding point on the line to normal p Subscript will be perpendicular to the line (Figure 3.23 (a)).

Figure 3.23: (a) Given an infinite line and a point normal p , then the vector from the point to the closest point on the line, normal p prime , is perpendicular to the line. (b) Because this vector is perpendicular, we can compute the distance from the first point of the line to the point of closest approach, normal p prime as d equals double-vertical-bar normal p Subscript Baseline minus normal p 0 double-vertical-bar cosine theta .

Equation (2.1) gives us a relationship between the dot product of two vectors, their lengths, and the cosine of the angle between them. In particular, it shows us how to compute the cosine of the angle between the vector from normal p 0 to normal p Subscript and the vector from normal p 0 to normal p 3 :

cosine theta equals StartFraction left-parenthesis normal p Subscript Baseline minus normal p 0 right-parenthesis dot left-parenthesis normal p 3 minus normal p 0 right-parenthesis Over double-vertical-bar normal p Subscript Baseline minus normal p 0 double-vertical-bar double-vertical-bar normal p 3 minus normal p 0 double-vertical-bar EndFraction period

Because the vector from normal p prime to normal p Subscript is perpendicular to the line (Figure 3.23(b)), then we can compute the distance along the line from normal p 0 to normal p prime as

d equals double-vertical-bar normal p Subscript Baseline minus normal p 0 double-vertical-bar cosine theta equals StartFraction left-parenthesis normal p Subscript Baseline minus normal p 0 right-parenthesis dot left-parenthesis normal p 3 minus normal p 0 right-parenthesis Over double-vertical-bar normal p 3 minus normal p 0 double-vertical-bar EndFraction period

Finally, the parametric offset w along the line is the ratio of d to the line’s length,

w equals StartFraction d Over double-vertical-bar normal p 3 minus normal p 0 double-vertical-bar EndFraction equals StartFraction left-parenthesis normal p Subscript Baseline minus normal p 0 right-parenthesis dot left-parenthesis normal p 3 minus normal p 0 right-parenthesis Over double-vertical-bar normal p 3 minus normal p 0 double-vertical-bar squared EndFraction period

The computation of the value of w is in turn slightly simplified from the fact that normal p Subscript Baseline equals left-parenthesis 0 comma 0 right-parenthesis in the intersection coordinate system.

<<Compute line w that gives minimum distance to sample point>>= 
Vector2f segmentDirection = Point2f(cp[3]) - Point2f(cp[0]); Float denom = segmentDirection.LengthSquared(); if (denom == 0) return false; Float w = Dot(-Vector2f(cp[0]), segmentDirection) / denom;

The parametric u coordinate of the (presumed) closest point on the Bézier curve to the candidate intersection point is computed by linearly interpolating along the u range of the segment. Given this u value, the width of the curve at that point can be computed.

<<Compute u coordinate of curve intersection point and hitWidth>>= 
Float u = Clamp(Lerp(w, u0, u1), u0, u1); Float hitWidth = Lerp(u, common->width[0], common->width[1]); Normal3f nHit; if (common->type == CurveType::Ribbon) { <<Scale hitWidth based on ribbon orientation>> 
Float sin0 = std::sin((1 - u) * common->normalAngle) * common->invSinNormalAngle; Float sin1 = std::sin(u * common->normalAngle) * common->invSinNormalAngle; nHit = sin0 * common->n[0] + sin1 * common->n[1]; hitWidth *= AbsDot(nHit, ray.d) / rayLength;
}

For Ribbon curves, the curve is not always oriented to face the ray. Rather, its orientation is interpolated between two surface normals given at each endpoint. Here, spherical linear interpolation is used to interpolate the normal at u (recall Section 2.9.2). The curve’s width is then scaled by the cosine of the angle between the normalized ray direction and the ribbon’s orientation so that it reflects the visible width of the curve from the given direction.

<<Scale hitWidth based on ribbon orientation>>= 
Float sin0 = std::sin((1 - u) * common->normalAngle) * common->invSinNormalAngle; Float sin1 = std::sin(u * common->normalAngle) * common->invSinNormalAngle; nHit = sin0 * common->n[0] + sin1 * common->n[1]; hitWidth *= AbsDot(nHit, ray.d) / rayLength;

To finally classify the potential intersection as a hit or miss, the Bézier curve must still be evaluated at u using the EvalBezier() function. (Because the control points cp represent the curve segment currently under consideration, it’s important to use w rather than u in the function call, however, since w is in the range left-bracket 0 comma 1 right-bracket .) The derivative of the curve at this point will be useful shortly, so it’s recorded now.

We’d like to test whether the distance from normal p Subscript to this point on the curve pc is less than half the curve’s width. Because normal p Subscript Baseline equals left-parenthesis 0 comma 0 right-parenthesis , we can equivalently test whether the distance from pc to the origin is less than half the width or, equivalently, whether the squared distance is less than one quarter the width squared. If this test passes, the last thing to check is if the intersection point is in the ray’s parametric t range.

<<Test intersection point against curve width>>= 
Vector3f dpcdw; Point3f pc = EvalBezier(cp, Clamp(w, 0, 1), &dpcdw); Float ptCurveDist2 = pc.x * pc.x + pc.y * pc.y; if (ptCurveDist2 > hitWidth * hitWidth * .25) return false; if (pc.z < 0 || pc.z > zMax) return false;

EvalBezier() computes the blossom p left-parenthesis u comma u comma u right-parenthesis to evaluate a point on a Bézier spline. It optionally also returns the derivative of the curve at the point.

<<Curve Utility Functions>>+= 
static Point3f EvalBezier(const Point3f cp[4], Float u, Vector3f *deriv = nullptr) { Point3f cp1[3] = { Lerp(u, cp[0], cp[1]), Lerp(u, cp[1], cp[2]), Lerp(u, cp[2], cp[3]) }; Point3f cp2[2] = { Lerp(u, cp1[0], cp1[1]), Lerp(u, cp1[1], cp1[2]) }; if (deriv) *deriv = (Float)3 * (cp2[1] - cp2[0]); return Lerp(u, cp2[0], cp2[1]); }

If the earlier tests have all passed, we have found a valid intersection, and the v coordinate of the intersection point can now be computed. The curve’s v coordinate ranges from 0 to 1, taking on the value 0.5 at the center of the curve; here, we classify the intersection point, left-parenthesis 0 comma 0 right-parenthesis , with respect to an edge function going through the point on the curve pc and a point along its derivative to determine which side of the center the intersection point is on and in turn how to compute v .

<<Compute v coordinate of curve intersection point>>= 
Float ptCurveDist = std::sqrt(ptCurveDist2); Float edgeFunc = dpcdw.x * -pc.y + pc.x * dpcdw.y; Float v = (edgeFunc > 0) ? 0.5f + ptCurveDist / hitWidth : 0.5f - ptCurveDist / hitWidth;

Finally, the partial derivatives are computed, and the SurfaceInteraction for the intersection can be initialized.

<<Compute hit t and partial derivatives for curve intersection>>= 
if (tHit != nullptr) { *tHit = pc.z / rayLength; <<Compute error bounds for curve intersection>> 
Vector3f pError(2 * hitWidth, 2 * hitWidth, 2 * hitWidth);
<<Compute partial-differential normal p slash partial-differential u and partial-differential normal p slash partial-differential v for curve intersection>> 
Vector3f dpdu, dpdv; EvalBezier(common->cpObj, u, &dpdu); if (common->type == CurveType::Ribbon) dpdv = Normalize(Cross(nHit, dpdu)) * hitWidth; else { <<Compute curve partial-differential normal p slash partial-differential v for flat and cylinder curves>> 
Vector3f dpduPlane = (Inverse(rayToObject))(dpdu); Vector3f dpdvPlane = Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) * hitWidth; if (common->type == CurveType::Cylinder) { <<Rotate dpdvPlane to give cylindrical appearance>> 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);
} dpdv = rayToObject(dpdvPlane);
}
*isect = (*ObjectToWorld)(SurfaceInteraction( ray(pc.z), pError, Point2f(u, v), -ray.d, dpdu, dpdv, Normal3f(0, 0, 0), Normal3f(0, 0, 0), ray.time, this)); }

The partial derivative partial-differential normal p slash partial-differential u comes directly from the derivative of the underlying Bézier curve. The second partial derivative, partial-differential normal p slash partial-differential v , is computed in different ways based on the type of the curve. For ribbons, we have partial-differential normal p slash partial-differential u and the surface normal, and so partial-differential normal p slash partial-differential v must be the vector such that partial-differential normal p slash partial-differential u times partial-differential normal p slash partial-differential v equals bold n and has length equal to the curve’s width.

<<Compute partial-differential normal p slash partial-differential u and partial-differential normal p slash partial-differential v for curve intersection>>= 
Vector3f dpdu, dpdv; EvalBezier(common->cpObj, u, &dpdu); if (common->type == CurveType::Ribbon) dpdv = Normalize(Cross(nHit, dpdu)) * hitWidth; else { <<Compute curve partial-differential normal p slash partial-differential v for flat and cylinder curves>> 
Vector3f dpduPlane = (Inverse(rayToObject))(dpdu); Vector3f dpdvPlane = Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) * hitWidth; if (common->type == CurveType::Cylinder) { <<Rotate dpdvPlane to give cylindrical appearance>> 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);
} dpdv = rayToObject(dpdvPlane);
}

For flat and cylinder curves, we transform partial-differential normal p slash partial-differential u to the intersection coordinate system. For flat curves, we know that partial-differential normal p slash partial-differential v lies in the x y plane, is perpendicular to partial-differential normal p slash partial-differential u , and has length equal to hitWidth. We can find the 2D perpendicular vector using the same approach as was used earlier for the perpendicular curve segment boundary edges.

<<Compute curve partial-differential normal p slash partial-differential v for flat and cylinder curves>>= 
Vector3f dpduPlane = (Inverse(rayToObject))(dpdu); Vector3f dpdvPlane = Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) * hitWidth; if (common->type == CurveType::Cylinder) { <<Rotate dpdvPlane to give cylindrical appearance>> 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);
} dpdv = rayToObject(dpdvPlane);

The partial-differential normal p slash partial-differential v vector for cylinder curves is rotated around the dpduPlane axis so that its appearance resembles a cylindrical cross-section.

<<Rotate dpdvPlane to give cylindrical appearance>>= 
Float theta = Lerp(v, -90., 90.); Transform rot = Rotate(-theta, dpduPlane); dpdvPlane = rot(dpdvPlane);

The Curve::Area() method, not included here, first approximates the curve length by the length of its control hull. It then multiplies this length by the average curve width over its extent to approximate the overall surface area.