5

I am developing a game where game consist lots of buildings. I finished modelling of buildings. But in optimization of game I understood that I need to use some thing like a LOD system. For that I want to export my buildings with decimated versions of them. Each buildings in different file.

Can I write a script that performs that operation automatically?

For example script can take a root file as input and iterates all the folder under root. Then exports all blend files with decimated versions.

I know python but I've never write script for blender.

user3160302
  • 375
  • 3
  • 10
  • yes, off course. you can!... please check some references like https://blenderartists.org/forum/showthread.php?249833-Open-a-file-from-Blender-using-python or others... ... the main is the blender appi documentation. http://www.blender.org/api/blender_python_api_current/ – yhoyo May 20 '17 at 16:02

1 Answers1

7

Ok, I wrote a script for my purpose. Maybe it will be helpful for somebody.

Here is the python script that decimates model and save as a new file. You can change iteration and decimateRatio

import bpy
import os

##Cleans all decimate modifiers
def cleanAllDecimateModifiers(obj):
    for m in obj.modifiers:
        if(m.type=="DECIMATE"):
#           print("Removing modifier ")
            obj.modifiers.remove(modifier=m)


numberOfIteration=2
decimateRatio=0.3
modifierName='DecimateMod'

for i in range(0,numberOfIteration):
    objectList=bpy.data.objects
    for obj in objectList:
        if(obj.type=="MESH"):


            cleanAllDecimateModifiers(obj)

            modifier=obj.modifiers.new(modifierName,'DECIMATE')
            modifier.ratio=1-decimateRatio*(i+1)
            modifier.use_collapse_triangulate=True

    fileName=bpy.data.filepath
    fileName=os.path.splitext(fileName)[0]

    #Trim decimate version of file name
    indexOf_=fileName.rfind('_')
    if(indexOf_!=-1 and fileName[indexOf_]+fileName[indexOf_+1]=="_d"):
        fileName=fileName.split("_d")[0]


    fileName='{}{}{}{}'.format(fileName, "_d",str(i+2),".blend")

    bpy.ops.wm.save_as_mainfile(filepath=fileName)

Also you can run this script with a bash command for all child files having .blend extension.

find . -name '*.blend' -exec blender {} --background --python myScript.py \;

Thanks to Attie for bash command

user3160302
  • 375
  • 3
  • 10
  • What does the use_collapse_triangulate attribute do? I see that it is described as "Keep triangulated faces resulting from decimation (collapse only)," but what does that mean? When I check or uncheck the corresponding option ("Triangulate") in Blender's GUI, I see no change in the number of faces or triangles in the resulting mesh. So, what does it do? – HelloGoodbye Aug 28 '18 at 16:47
  • 1
    Is there a wayto apply the newly added modifiers before saving the file? – Ziad Sep 27 '19 at 15:52