# [Numpy-discussion] Help on vectorization of mesh normals computation

Nicolas Rougier Nicolas.Rougier@loria...
Thu Jun 17 12:48:23 CDT 2010

```Hello,

I'm trying to find a way to compute the normals of a mesh (vertices + indices) using only vectorized computations and I wonder if anyone already did that. Here my code so far:

# Mesh generation + indices for triangles
n = 24
vertices = numpy.zeros(((n*n),3), dtype=numpy.float32)
normals  = numpy.zeros(((n*n),3), dtype=numpy.float32)
indices  = numpy.zeros((2*(n-1)*(n-1),3), dtype=numpy.int)
for xi in range(n):
for yi in range(n):
i = yi*n + xi
vertices[i] = xi/float(n-1), yi/float(n-1), 0
j=0
for yi in range(n-1):
for xi in range(n-1):
i = yi*n + xi
indices[j+0] = i,  i+1,i+n
indices[j+1] = i+n,i+1,i+n+1
j += 2

# Normal computations
normals[:] = 0,0,0
P1 = vertices[indices[:,0]]
P2 = vertices[indices[:,1]]
P3 = vertices[indices[:,2]]
N = numpy.cross(P2-P3,P3-P1)
for i in range(self.indices.shape[0]):
normals[indices[i]] += N[i]

I would like to get rid of the last 'for' loop but did not find the proper way to do it. Anyone got an idea ?

Nicolas
```