Skip to content

Instantly share code, notes, and snippets.

@ShaoxiongYao
Last active June 30, 2025 05:49
Show Gist options
  • Save ShaoxiongYao/8259cf495e1776b42579bead812ba44e to your computer and use it in GitHub Desktop.
Save ShaoxiongYao/8259cf495e1776b42579bead812ba44e to your computer and use it in GitHub Desktop.
Automatic Tree Model Generation Using `tree-gen` in Blender
"""
Generate procedural tree models in Blender using the tree-gen add-on.
Author: Shaoxiong Yao
Created: 06/29/2025
"""
import bpy
import sys
import os
import math
import random
import argparse
from typing import Union
def parse_args():
"""
Parse command line arguments for tree generation.
Returns:
argparse.Namespace: Parsed arguments containing tree type,
output directory, and number of trees.
"""
parser = argparse.ArgumentParser(description="Generate procedural trees in Blender and export as GLB.")
parser.add_argument("--tree_type", type=str, default="tree-gen.parametric.tree_params.quaking_aspen",
help="The full tree preset ID (e.g., tree-gen.parametric.tree_params.bamboo)")
parser.add_argument("--output_dir", type=str, default="outputs",
help="Directory to save exported .glb files")
parser.add_argument("--num_trees", type=int, default=1,
help="Number of trees to generate (each with different seed)")
args, _ = parser.parse_known_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
return args
def generate_tree(tree_type: str, output_dir: str, index: int,
seed: Union[None, int] = None):
"""Generate a single tree and export it."""
# Clear selection and remove previous tree parts
for obj in bpy.data.objects:
obj.select_set(False)
for obj in bpy.data.objects:
if obj.name.startswith(("Tree", "Branches", "Leaves", "Trunk")):
bpy.data.objects.remove(obj, do_unlink=True)
# Store existing objects
existing_objects = set(bpy.data.objects.keys())
# Set parameters
bpy.context.scene.custom_tree_load_params_input = tree_type
bpy.context.scene.tree_gen_convert_to_mesh_input = False
if seed is None:
seed = random.randint(0, 10_000_000)
bpy.context.scene.seed_input = seed
print(f"[{index}] Generating tree type: {tree_type}, seed: {bpy.context.scene.seed_input}")
bpy.ops.object.tree_gen()
# Find new tree objects
new_objects = [
obj for obj in bpy.data.objects
if obj.name not in existing_objects and obj.type in {'CURVE', 'MESH'}
]
if not new_objects:
raise RuntimeError("No new tree objects were generated.")
# Convert to mesh
converted_objects = []
for obj in new_objects:
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
if obj.type == 'CURVE':
bpy.ops.object.convert(target='MESH')
converted_objects.append(obj)
# Export to GLB
filename = f"{tree_type.split('.')[-1]}_{index:02d}.glb"
output_path = os.path.join(output_dir, filename)
bpy.ops.export_scene.gltf(
filepath=output_path,
export_format='GLB',
use_selection=True,
export_apply=True
)
print(f"[{index}] Exported tree to: {output_path}")
if __name__ == "__main__":
args = parse_args()
os.makedirs(args.output_dir, exist_ok=True)
for i in range(args.num_trees):
generate_tree(args.tree_type, args.output_dir, i)

This script provides an automated way to generate procedural tree models using the tree-gen GitHub repository, which is originally a Blender GUI add-on. Instead of manually interacting with the Blender interface, this script enables command-line control using Python.


Prerequisites

1. Install Blender

Download and install the latest version of Blender from the official site: https://www.blender.org/download/

Make sure blender is accessible from your terminal. If not, add it to your system PATH.

2. Install tree-gen Add-on

  1. Download the latest .zip release from the tree-gen GitHub Releases page.
  2. Open Blender GUI.
  3. Go to EditPreferencesAdd-ons.
  4. Click Install... and select the .zip file.
  5. Enable the checkbox for tree-gen.

Usage

You can now run the script from the command line without launching the Blender GUI:

blender --background --python auto_gen_tree.py -- \
    --tree_type tree-gen.parametric.tree_params.quaking_aspen \
    --output_dir ./outputs \
    --num_trees 3

Command Line Arguments

Argument Type Default Description
--tree_type string tree-gen.parametric.tree_params.quaking_aspen The preset ID of the tree to generate (must match an enabled preset from the add-on).
--output_dir string outputs Directory to save the generated .glb files.
--num_trees int 1 Number of trees to generate. Each will use a different random seed.

Output

The script will generate .glb (GLTF binary) files named like:

outputs/tree_000.glb
outputs/tree_001.glb
...

These files can be opened with any GLB viewer or imported into 3D engines like Unity, Unreal, or Three.js.

Example generation result with default quaking_aspen parameters:

example_quaking_aspen


Notes

  • This script must be run inside Blender using --python, not as a regular Python script.
  • Ensure the tree_type string matches a valid preset exposed by the add-on (check in the Blender UI or console).
  • Blender may take a few seconds per tree due to procedural geometry generation.

TODOs

  • Find or assign a default material so that the generated plant looks visually reasonable (e.g., green leaves, brown stems).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment