5
\$\begingroup\$

I'm primarily looking for ways to increase the performance of my code.

It is used to transform mesh data from blender into a format I can use and then save it to a file.

First it collects the colors of each vertex with an index to reference them, then for each of the vertices it writes its coordinates followed by its average color. The last part decides if each polygon is a triangle or a rectangle and writes the indices of each of its vertices, while converting rectangles to 2 triangles.

import bpy
mesh = "mesh"
filepath = "filepath"
out = open(filepath, 'w')
m = bpy.data.meshes[mesh]
colData = m.vertex_colors["Col"].data
colors = []
index = []
for pol in m.polygons:
    count = 0
    for li in pol.loop_indices:
        for rgb in colData[li].color:
            colors += [rgb]
        index += [pol.vertices[count]]
        count += 1
for ver in m.vertices:
    indices = [i for i, x in enumerate(index) if x == ver.index]
    for f in ver.co:
        out.write(str(f)+' ')
    for f in range(3):
        c = 0
        for i in indices:
            c += colors[i*3+f]
        c = c/len(indices)
        out.write(str(c)+' ')
    out.write('\n')
out.write('\n')
for pol in m.polygons:
    if len(pol.vertices)==3: 
        for i in pol.vertices:
            out.write(str(i)+' ')
    else:
        for i in pol.vertices[:3]:
            out.write(str(i)+' ')
        for i in pol.vertices[2:]:
            out.write(str(i)+' ')
        out.write(str(pol.vertices[0])+' ')  
    out.write('\n')
out.write('\n')
out.close()
\$\endgroup\$
1
\$\begingroup\$

You could try to replace some loops with string formatting, for example change this

for i in pol.vertices[:3]:
    out.write(str(i)+' ')
for i in pol.vertices[2:]:
    out.write(str(i)+' ')
out.write(str(pol.vertices[0])+' ')  

to this

out.write('{0} {1} {2} {2} {3} {0} '.format(*pol.vertices))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.