官术网_书友最值得收藏!

Normalizing vectors

A vector with a length of 1 is called a normal vector (or unit vector). Generally, unit vectors are used to represent a direction without a magnitude. The dot product of two unit vectors will always fall in the -1 to 1 range.

Aside from the 0 vector, any vector can be normalized by scaling the vector by the inverse of its length:

  1. Implement the normalize function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    void normalize(vec3 &v) {

        float lenSq = v.x * v.x + v.y * v.y + v.z * v.z;

        if (lenSq < VEC3_EPSILON) { return; }

        float invLen = 1.0f / sqrtf(lenSq);    

        v.x *= invLen;

        v.y *= invLen;

        v.z *= invLen;

    }

  2. Implement the normalized function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    vec3 normalized(const vec3 &v) {

        float lenSq = v.x * v.x + v.y * v.y + v.z * v.z;

        if (lenSq < VEC3_EPSILON) { return v; }

        float invLen = 1.0f / sqrtf(lenSq);

        return vec3(

            v.x * invLen,

            v.y * invLen,

            v.z * invLen

        );

    }

The normalize function takes a reference to a vector and normalizes it in place. The normalized function, on the other hand, takes a constant reference and does not modify the input vector. Instead, it returns a new vector.

主站蜘蛛池模板: 贺州市| 子长县| 东乌珠穆沁旗| 盐源县| 临桂县| 绵阳市| 嘉禾县| 周口市| 旺苍县| 永康市| 乌兰浩特市| 东阳市| 桐柏县| 永顺县| 项城市| 武义县| 中卫市| 无为县| 紫阳县| 万年县| 临潭县| 张家界市| 湘西| 山东| 衡阳县| 海兴县| 龙里县| 土默特左旗| 长兴县| 仁怀市| 丽水市| 任丘市| 新丰县| 湾仔区| 安福县| 六安市| 永丰县| 沂水县| 济南市| 鹿邑县| 临澧县|