Skip to content

Instantly share code, notes, and snippets.

@robotconscience
Last active January 29, 2024 16:04
Show Gist options
  • Save robotconscience/e7da1c7e160609bbe928e77c14f0f928 to your computer and use it in GitHub Desktop.
Save robotconscience/e7da1c7e160609bbe928e77c14f0f928 to your computer and use it in GitHub Desktop.
Blender - glTF Variants -> individual USDZs
# exports each selected object into its own file
import bpy
import os
# export to blend file location
basedir = os.path.dirname(bpy.data.filepath)
if not basedir:
raise Exception("Blend file is not saved")
view_layer = bpy.context.view_layer
obj_active = view_layer.objects.active
selection = bpy.context.selected_objects
bpy.ops.object.select_all(action='DESELECT')
for obj in selection:
obj.select_set(True)
# some exporters only use the active object
view_layer.objects.active = obj
name = bpy.path.clean_name(obj.name)
fn = os.path.join(basedir, name)
# loop through variants
gltf2_active_variant = bpy.data.scenes[0].gltf2_active_variant
# loop on all mesh
if obj.type == "MESH":
mesh = obj.data
if bpy.data.scenes[0].get('gltf2_KHR_materials_variants_variants') and len(bpy.data.scenes[0].gltf2_KHR_materials_variants_variants) > 0:
i = 0
for v in bpy.data.scenes[0].gltf2_KHR_materials_variants_variants:
name = v.name
idx = i
# seems to be a bug?
# v.variant_idx
print("Exporting " + name +":"+ str(idx))
bpy.context.scene.gltf2_active_variant = idx
bpy.ops.scene.gltf2_display_variant()
bpy.ops.wm.usd_export(filepath=fn + "_variant_" + name +".usdz", selected_objects_only=True)
i = i + 1
else:
print("no variants found")
else:
# debugging stuff
print(len(bpy.data.scenes[0].gltf2_KHR_materials_variants_variants))
print(bpy.data.scenes[0].get('gltf2_KHR_materials_variants_variants'))
else:
print("Not a mesh?")
obj.select_set(False)
print("written:", fn)
view_layer.objects.active = obj_active
for obj in selection:
obj.select_set(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment