Matheus Weber
Matheus Weber

Reputation: 259

How can I generate a spline curve using glm_gtx_spline::catmullRom?

I have 4 points that I had do travel with the camera using a spline curve, how can I generate the curve using the glm::gtx_spline::catmullRom?

It is a function from glm_gtx_spline http://glm.g-truc.net/0.9.4/api/a00203.html

genType catmullRom (genType const &v1, genType const &v2, genType const &v3, genType const &v4, typename genType::value_type const &s)

Upvotes: 3

Views: 2637

Answers (1)

jsb
jsb

Reputation: 963

A Catmull-Rom spline generally consists of several segments that each interpolate one pair of successive control points. The glm::catmullRom function computes only one segment of this curve, which depends on four successive control points (p0, p1, p2, p3). The curve segment always goes from p1 to p2, while the points p0 and p3 only affect how the curve bends in between, as illustrated here:

Catmull-Rom curve segment
(image by Hadunsford - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=28956755)

By chaining several of these curve segments in sequence, you create a Catmull-Rom spline that interpolates a sequence of (an arbitrary number of) control points. If each Catmull-Rom curve segment is computed from four successive control points, the resulting spline will be continuous and smooth (C1 continuous).

Given a vector cp of n control points, the following function computes the value of the Catmull-Rom spline at parameter t (where t goes from 0 to n-1):

glm::vec3 catmull_rom_spline(const std::vector<glm::vec3>& cp, float t)
{
    // indices of the relevant control points
    int i0 = glm::clamp<int>(t - 1, 0, cp.size() - 1);
    int i1 = glm::clamp<int>(t,     0, cp.size() - 1);
    int i2 = glm::clamp<int>(t + 1, 0, cp.size() - 1);
    int i3 = glm::clamp<int>(t + 2, 0, cp.size() - 1);

    // parameter on the local curve interval
    float local_t = glm::fract(t);

    return glm::catmullRom(cp[i0], cp[i1], cp[i2], cp[i3], local_t);
}

In this implementation, the relevant control point indices are clamped to the range (0, n-1). Conceptually, this achieves a doubling of the first and last control points which has the effect that the first and last control point of cp are also interpolated.

Varying the parameter t between 0 and n-1 will now trace out points on a smooth curve interpolating all points in cp.

Upvotes: 6

Related Questions