Skip to content

Instantly share code, notes, and snippets.

@Utopiah
Last active October 18, 2022 09:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Utopiah/111c8ee32505a11ad7a6c629f277c2a4 to your computer and use it in GitHub Desktop.
Save Utopiah/111c8ee32505a11ad7a6c629f277c2a4 to your computer and use it in GitHub Desktop.
Blender Python script to triangulate obj coming from Google Blocks
# Blender Python script to triangulate obj coming from Google Blocks
# result http://vatelier.net/MyDemo/TestingTriangulation/
# via https://blender.stackexchange.com/questions/34537/how-to-batch-convert-between-file-formats
import bpy # Python interface for Blender, use Shift+F4 to start the interactive console.
# alternatively for headless server side batch conversion use blender -b -P triangulate_obj.py
import os
def convert_in_dir(path):
for root, dirs, files in os.walk(path):
for f in files:
if f.endswith('.obj') :
print(f)
mesh_file = os.path.join(path, f)
obj_file = os.path.splitext(mesh_file)[0] + "_triangulated.obj"
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
bpy.ops.import_scene.obj(filepath=mesh_file)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.export_scene.obj(filepath=obj_file, use_triangles=True)
# export to glTF, for AFrame us gltf-model-next from aframe-extras
# cf http://vatelier.net/MyDemo/TestingTriangulation/gltf.html
if "gltf" in dir(bpy.ops.export_scene):
gltf_file = os.path.splitext(mesh_file)[0] + ".gltf"
bpy.ops.export_scene.gltf(filepath=gltf_file)
return;
path = 'C:/Users/UCB/Downloads/testing_triangulation/'
# assuming a lot of subdirectories to with one or more obj file to fix
for root, dirs, files in os.walk(path):
# convert_in_dir(path)
for d in dirs:
cd = os.path.join(path, d)
convert_in_dir(cd)
@Utopiah
Copy link
Author

Utopiah commented Jul 30, 2017

Could` add an option to automatically reduce the number of polygon non interactively (could do N versions with own ratios)

bpy.ops.object.modifier_add(type='DECIMATE')
bpy.context.object.modifiers["Decimate"].use_collapse_triangulate = True
bpy.context.object.modifiers["Decimate"].ratio = 0.1

@Adra8373
Copy link

Hi

Thanks for your code.

I have a question from where did you run this code is it from blender script?

I run it from blender scripts it does not give any error but I did not get any new generated files?

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment