Last active
January 12, 2024 23:05
-
-
Save danthemango/1aaab8264c75be9c165dc8610357e3f3 to your computer and use it in GitHub Desktop.
enable optix GPU rendering in blender python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy, sys, os | |
# enable GPU rendering if possible | |
# use whatever device type is available, in oder of device_type_preferences left-to-right | |
def set_device_type(device_type_preferences=['OPTIX', 'CUDA', 'CPU']): | |
prefs = bpy.context.preferences | |
cycles_prefs = prefs.addons['cycles'].preferences | |
enabled_devices = [] | |
for device_type_preference in device_type_preferences: | |
if device_type_preference != 'CPU': | |
bpy.context.scene.cycles.device = 'GPU' | |
else: | |
bpy.context.scene.cycles.device = 'CPU' | |
cycles_prefs.compute_device_type = device_type_preference | |
cycles_prefs.refresh_devices() | |
preferred_devices = [device for device in cycles_prefs.devices if device.type == device_type_preference] | |
if len(preferred_devices) == 0: | |
continue | |
for device in preferred_devices: | |
device.use = True | |
enabled_devices.append(device) | |
break | |
for enabled_device in enabled_devices: | |
print('enabled_device:', enabled_device.name, enabled_device.type) | |
bpy.context.scene.cycles.device = 'GPU' | |
def render_blend_to_png(blend_file, output_png, samples=1000): | |
# Open the blend file | |
bpy.ops.wm.open_mainfile(filepath=blend_file) | |
# Set Cycles as the rendering engine | |
bpy.context.scene.render.engine = 'CYCLES' | |
set_device_type() | |
# Set the number of samples | |
bpy.context.scene.cycles.samples = samples | |
# Set output file format and path | |
bpy.context.scene.render.image_settings.file_format = 'PNG' | |
bpy.context.scene.render.filepath = output_png | |
# Render the animation | |
bpy.ops.render.render(write_still=True) | |
if __name__ == "__main__": | |
# Check if the correct number of command line arguments is provided | |
if '--' not in sys.argv: | |
print("Usage: blender -b -P gpu-render.py -- <blend_file> <output_png> <samples>") | |
sys.argv = sys.argv[sys.argv.index("--") + 1:] | |
if len(sys.argv) != 3: | |
print("Usage: blender -b -P gpu-render.py -- <blend_file> <output_png> <samples>") | |
sys.exit(1) | |
# Extract command line arguments | |
blend_file = os.path.abspath(sys.argv[0]) | |
output_png = os.path.abspath(sys.argv[1]) | |
samples = int(sys.argv[2]) | |
print('blend_file', blend_file) | |
print('output_png', output_png) | |
print('samples', samples) | |
# Call the rendering function | |
render_blend_to_png(blend_file, output_png, samples) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this works as of blender 4.0