Skip to content

Instantly share code, notes, and snippets.

@rkandas
Created November 27, 2021 16:00
Show Gist options
  • Save rkandas/874fe5add05dbf9d76dda0460975be9d to your computer and use it in GitHub Desktop.
Save rkandas/874fe5add05dbf9d76dda0460975be9d to your computer and use it in GitHub Desktop.
Imports the given FBX model, Decimates the meshes and exports as FBX
import bpy
import os
import sys
'''
Imports the given FBX model, Decimates the meshes and exports as FBX
@input
<input_fbx_filepath>
@output
decimated mesh as FBX file
'''
class Decimator:
def __init__(self, fbx_file):
self.clean_scene()
bpy.ops.import_scene.fbx(filepath=fbx_file)
mesh = bpy.context.selected_objects[0]
self.simplifymesh(mesh)
self.export_fbx(mesh,fbx_file)
def clean_scene(self):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete(use_global=False)
for item in bpy.data.meshes:
bpy.data.meshes.remove(item)
def simplifymesh(self, mesh):
bpy.context.view_layer.objects.active = mesh
mod = mesh.modifiers.new(name='Decimate', type='DECIMATE')
bpy.context.object.modifiers['Decimate'].use_collapse_triangulate = True
nfaces = len(mesh.data.polygons)
print('INPUT FACE COUNT:', nfaces)
if nfaces > 10000:
ratio = 10000 / float(nfaces)
mod.ratio = float('%s' % ('%.6g' % (ratio)))
print('ratio: ', mod.ratio)
bpy.ops.object.modifier_apply(modifier=mod.name)
print('OUTPUT FACE COUNT:', len(mesh.data.polygons))
def export_fbx(self, mesh, fbx_file):
outpath = os.path.dirname(fbx_file)
(outfile, ext) = os.path.splitext(fbx_file)
if not os.path.isdir(outpath): os.makedirs(outpath)
output_fbx = os.path.join(outpath, outfile + "_decimated.fbx")
print('EXPORTING', output_fbx)
bpy.ops.object.select_all(action='DESELECT')
mesh.select_set(state=True)
bpy.ops.export_scene.fbx(filepath=output_fbx)
fbx_file = sys.argv[-1]
print('args: ', fbx_file)
blender = Decimator(fbx_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment