Vector normalization

The formula for half the vector is (Hv) = (Lv + Vv) / | Lv + Vv |, where Lv is the light vector, and Vv is the view vector.

Am I doing this correctly in Python code?

Vvx = 0-xi  # view vector (calculating it from surface points)
Vvy = 0-yi
Vvz = 0-zi
Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz))  # normalizing
Vvx = Vvx / Vv
Vvy = Vvy / Vv
Vvz = Vvz / Vv
Lv = (1,1,1)  # light vector
Hn = math.sqrt(((1 + Vvx) * (1 + Vvx)) + ((1 + Vvy) * (1 + Vvy)) +
               ((1 + Vvz) * (1 + Vvz))) 
Hv = ((1 + Vvx) / Hn, (1 + Vvy) / Hn, (1 + Vvz) / Hn)  # half-way vector
+3
source share
1 answer

It is not right. What you wrote is a simple vector addition of two vectors, the result of which is a normalized unit vector.

Here is how I would do it:

import math

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

if __name__ == '__main__':
    l = [1, 1, 1]
    v = [0, 0, 0]

    h = normalize(add(l, v))
    print h
+20
source

Source: https://habr.com/ru/post/1773415/


All Articles