├── parametric ├── __init__.py ├── tree_params │ ├── lombardy_poplar.py │ ├── bamboo.py │ ├── european_larch.py │ ├── acer.py │ ├── sassafras.py │ ├── douglas_fir.py │ ├── quaking_aspen.py │ ├── fan_palm.py │ ├── palm.py │ ├── black_oak.py │ ├── balsam_fir.py │ ├── small_pine.py │ ├── black_tupelo.py │ ├── silver_birch.py │ ├── apple.py │ ├── hill_cherry.py │ ├── sphere_tree.py │ ├── cambridge_oak.py │ ├── weeping_willow.py │ ├── weeping_willow_o.py │ └── tree_param.py └── gen.py ├── README.md ├── __init__.py ├── .gitignore ├── chturtle.py ├── leaf.py ├── utilities.py ├── leaf_shapes.py ├── LICENSE └── gui.py /parametric/__init__.py: -------------------------------------------------------------------------------- 1 | from . import gen -------------------------------------------------------------------------------- /parametric/tree_params/lombardy_poplar.py: -------------------------------------------------------------------------------- 1 | """ LOMBARDY POPLAR """ 2 | params = { 3 | 'shape': 2, 4 | 'g_scale': 25, 5 | 'g_scale_v': 5, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.2, 9 | 'flare': 0.8, 10 | 'base_size': [0.01, 0.1, 0.02, 0.02], 11 | 'down_angle': [-0, 30, 30, 30], 12 | 'down_angle_v': [-0, 0, 10, 10], 13 | 'rotate': [-0, 77, 77, 77], 14 | 'rotate_v': [-0, 15, 15, 15], 15 | 'branches': [1, 60, 35, 10], 16 | 'length': [1, 0.3, 0.4, 0], 17 | 'length_v': [0, 0, 0.1, 0], 18 | 'taper': [1, 1, 1, 1], 19 | 'curve_res': [1, 3, 3, 1], 20 | 'curve': [0, -20, -20, 0], 21 | 'curve_back': [0, 0, 0, 0], 22 | 'curve_v': [0, 0, 40, 0], 23 | 'leaves': 30, 24 | 'leaf_shape': 8, 25 | 'leaf_scale': 0.3, 26 | 'leaf_scale_x': 1, 27 | 'leaf_bend': 0.7, 28 | 'tropism': [0, 0, 0.5] 29 | } 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tree-gen 2 | 3 | Blender plugin produced as part of my undergraduate dissertation: [Procedural generation of tree models for use in computer graphics](https://chewitt.me/Papers/CTH-Dissertation-2017.pdf). 4 | 5 | ![Tree Sample Image](http://chewitt.me/Folio/Trees.jpg) 6 | 7 | Thanks to the awesome work of [Sami Pflibsen-Jones](https://github.com/samipfjo) you can install the zip through the Blender addon UI (or drop the extracted folder into your blender addons directory) and enable the plugin in user settings to start generating trees - now with a complete customisation UI! 8 | 9 | Download the latest version from [here](https://github.com/friggog/tree-gen/releases). 10 | 11 | (WIP) Docmentation is available on the [Wiki](https://github.com/friggog/tree-gen/wiki). 12 | 13 | The code is under GPL-3.0 License, any models generated using the tool are free for use without restriction in any context apart from direct sale as assets. 14 | -------------------------------------------------------------------------------- /parametric/tree_params/bamboo.py: -------------------------------------------------------------------------------- 1 | """ BAMBOO """ 2 | params = { 3 | 'shape': 7, 4 | 'g_scale': 10, 5 | 'g_scale_v': 2, 6 | 'levels': 2, 7 | 'ratio': 0.005, 8 | 'ratio_power': 1, 9 | 'flare': 0, 10 | 'base_size': [0.4, 0.4, 0, 0], 11 | 'down_angle': [-0, 30, 30, 30], 12 | 'down_angle_v': [-0, 10, 10, 10], 13 | 'rotate': [-0, 77, 77, 77], 14 | 'rotate_v': [-0, 30, 0, 0], 15 | 'branches': [50, 25, 0, 10], 16 | 'length': [1, 0.2, 0, 0], 17 | 'length_v': [0, 0.05, 0, 0], 18 | 'taper': [1, 1, 1, 1], 19 | 'seg_splits': [0, 0, 0, 0], 20 | 'split_angle': [0, 0, 0, 0], 21 | 'split_angle_v': [0, 0, 0, 0], 22 | 'curve_res': [10, 5, 0, 1], 23 | 'curve': [50, 30, 0, 0], 24 | 'curve_back': [0, 0, 0, 0], 25 | 'curve_v': [70, 0, 0, 0], 26 | 'leaves': 20, 27 | 'leaf_shape': 0, 28 | 'leaf_scale': 0.3, 29 | 'leaf_scale_x': 0.3, 30 | 'leaf_bend': 0.1, 31 | 'tropism': [0, 0, 0] 32 | } 33 | -------------------------------------------------------------------------------- /parametric/tree_params/european_larch.py: -------------------------------------------------------------------------------- 1 | """ EUROPEAN LARCH """ 2 | params = { 3 | 'shape': 0, 4 | 'g_scale': 15, 5 | 'g_scale_v': 7, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.3, 9 | 'flare': 0.3, 10 | 'base_size': [0.25, 0.02, 0.02, 0.02], 11 | 'down_angle': [-0, 60, 70, 30], 12 | 'down_angle_v': [-0, -50, 30, 15], 13 | 'rotate': [-0, 70, 70, 120], 14 | 'rotate_v': [-0, 30, 30, 30], 15 | 'branches': [1, 60, 50, 0], 16 | 'length': [1, 0.25, 0.3, 0], 17 | 'length_v': [0, 0, 0.1, 0], 18 | 'taper': [1, 1, 1, 1], 19 | 'seg_splits': [0, 0, 0.15, 0], 20 | 'split_angle': [0, 0, 40, 0], 21 | 'split_angle_v': [0, 0, 10, 0], 22 | 'curve_res': [20, 17, 7, 1], 23 | 'curve': [0, 20, 0, 0], 24 | 'curve_back': [0, -100, 0, 0], 25 | 'curve_v': [60, 120, 0, 0], 26 | 'leaf_blos_num': 200, 27 | 'leaf_shape': 2, 28 | 'leaf_scale': 0.07, 29 | 'leaf_scale_x': 0.5, 30 | 'leaf_bend': 0.1, 31 | 'tropism': [0, 0, -3.0] 32 | } 33 | -------------------------------------------------------------------------------- /parametric/tree_params/acer.py: -------------------------------------------------------------------------------- 1 | """ ACER """ 2 | params = { 3 | 'shape': 4, 4 | 'g_scale': 10, 5 | 'g_scale_v': 1, 6 | 'levels': 3, 7 | 'ratio': 0.025, 8 | 'ratio_power': 1.5, 9 | 'flare': 0.6, 10 | 'base_splits': -2, 11 | 'base_size': [0.1, 0.4, 0.02, 0.02], 12 | 'down_angle': [-0, 50, 50, 45], 13 | 'down_angle_v': [-0, 5, 5, 10], 14 | 'rotate': [-0, 140, 140, 77], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 6, 20, 5], 17 | 'length': [1, 0.7, 0.3, 0], 18 | 'length_v': [0, 0.05, 0.05, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [1.5, 1.5, 0, 0], 21 | 'split_angle': [50, 50, 0, 0], 22 | 'split_angle_v': [5, 5, 0, 0], 23 | 'curve_res': [6, 5, 3, 0], 24 | 'curve': [0, 0, 0, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [200, 100, 100, 0], 27 | 'bend_v': [-0, 50, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 30, 30 | 'leaf_shape': 5, 31 | 'leaf_scale': 0.2, 32 | 'leaf_bend': 0.3 33 | } 34 | -------------------------------------------------------------------------------- /parametric/tree_params/sassafras.py: -------------------------------------------------------------------------------- 1 | """ SASSAFRAS """ 2 | params = { 3 | 'shape': 2, 4 | 'g_scale': 23, 5 | 'g_scale_v': 7, 6 | 'levels': 4, 7 | 'ratio': 0.02, 8 | 'ratio_power': 1.3, 9 | 'flare': 0.5, 10 | 'base_splits': 0, 11 | 'base_size': [0.2, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 90, 50, 45], 13 | 'down_angle_v': [-0, -10, 10, 10], 14 | 'rotate': [-0, 140, 140, 140], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 20, 20, 30], 17 | 'length': [1, 0.4, 0.7, 0.4], 18 | 'length_v': [0, 0, 0, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0, 0, 0], 21 | 'split_angle': [20, 0, 0, 0], 22 | 'split_angle_v': [5, 0, 0, 0], 23 | 'curve_res': [16, 15, 8, 3], 24 | 'curve': [0, -60, -40, 0], 25 | 'curve_back': [0, 30, 0, 0], 26 | 'curve_v': [60, 100, 150, 100], 27 | 'leaves': 15, 28 | 'leaf_shape': 0, 29 | 'leaf_scale': 0.25, 30 | 'leaf_scale_x': 0.7, 31 | 'leaf_bend': 0.3, 32 | 'tropism': [0, 0, 0.5] 33 | } 34 | -------------------------------------------------------------------------------- /parametric/tree_params/douglas_fir.py: -------------------------------------------------------------------------------- 1 | """ DOUGLAS FIR """ 2 | params = { 3 | 'shape': 0, 4 | 'g_scale': 40, 5 | 'g_scale_v': 10, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.2, 9 | 'flare': 1.0, 10 | 'base_size': [0.2, 0.1, 0.02, 0.02], 11 | 'down_angle': [-0, 100, 40, 45], 12 | 'down_angle_v': [-0, -40, 10, 10], 13 | 'rotate': [-0, 140, 140, 140], 14 | 'rotate_v': [-0, 60, 50, 0], 15 | 'branches': [1, 250, 30, 0], 16 | 'length': [1, 0.13, 0.4, 0], 17 | 'length_v': [0, 0, 0.1, 0], 18 | 'taper': [1, 1, 1, 1], 19 | 'seg_splits': [0, 0.5, 0, 0], 20 | 'split_angle': [0, 0, 0, 0], 21 | 'split_angle_v': [0, 0, 0, 0], 22 | 'curve_res': [2, 5, 3, 1], 23 | 'curve': [0, -35, 0, 0], 24 | 'curve_back': [0, 0, 0, 0], 25 | 'curve_v': [0, 90, 150, 0], 26 | 'bend_v': [-0, 50, 0, 0], 27 | 'branch_dist': [-0, 0, 0, 0], 28 | 'leaf_blos_num': 100, 29 | 'leaf_shape': 2, 30 | 'leaf_scale': 0.15, 31 | 'leaf_scale_x': 0.3, 32 | 'leaf_bend': 0 33 | } 34 | -------------------------------------------------------------------------------- /parametric/tree_params/quaking_aspen.py: -------------------------------------------------------------------------------- 1 | """ QUAKING ASPEN """ 2 | params = { 3 | 'shape': 7, 4 | 'g_scale': 13, 5 | 'g_scale_v': 3, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.2, 9 | 'flare': 0.6, 10 | 'base_splits': 0, 11 | 'base_size': [0.3, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 60, 60, 45], 13 | 'down_angle_v': [-0, -50, 20, 30], 14 | 'rotate': [-0, 140, 140, 77], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 50, 30, 1], 17 | 'length': [1, 0.3, 0.6, 0], 18 | 'length_v': [0, 0, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0, 0, 0], 21 | 'split_angle': [40, 0, 0, 0], 22 | 'split_angle_v': [5, 0, 0, 0], 23 | 'curve_res': [5, 5, 5, 0], 24 | 'curve': [0, -40, -60, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [20, 100, 100, 0], 27 | 'bend_v': [-0, 50, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 40, 30 | 'leaf_shape': 3, 31 | 'leaf_scale': 0.17, 32 | 'leaf_bend': 0.6 33 | } 34 | -------------------------------------------------------------------------------- /parametric/tree_params/fan_palm.py: -------------------------------------------------------------------------------- 1 | """ FAN PALM """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 5, 5 | 'g_scale_v': 2, 6 | 'levels': 2, 7 | 'ratio': 0.04, 8 | 'ratio_power': 1.3, 9 | 'flare': 0, 10 | 'base_size': [0.8, 0, 0, 0], 11 | 'down_angle': [-0, 20, -10, 0], 12 | 'down_angle_v': [-0, -60, 10, 0], 13 | 'rotate': [-0, 160, 260, 0], 14 | 'rotate_v': [-0, 40, 5, 0], 15 | 'branches': [1, 50, 0, 0], 16 | 'length': [1, 0.25, 0, 0], 17 | 'length_v': [0, 0.05, 0, 0], 18 | 'taper': [2.1, 1.4, 0, 0], 19 | 'seg_splits': [0, 0, 0, 0], 20 | 'split_angle': [0, 0, 0, 0], 21 | 'split_angle_v': [0, 0, 0, 0], 22 | 'curve_res': [6, 9, 0, 0], 23 | 'curve': [10, 50, 0, 0], 24 | 'curve_back': [0, -5, 0, 0], 25 | 'curve_v': [40, 30, 0, 0], 26 | 'bend_v': [-0, 0, 0, 0], 27 | 'branch_dist': [-0, 0, 0, 0], 28 | 'leaf_blos_num': -90, 29 | 'leaf_shape': 10, 30 | 'leaf_scale': 0.8, 31 | 'leaf_scale_x': 0.05, 32 | 'leaf_bend': 0, 33 | 'tropism': [0, 0, -1] 34 | } 35 | -------------------------------------------------------------------------------- /parametric/tree_params/palm.py: -------------------------------------------------------------------------------- 1 | """ PALM """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 14, 5 | 'g_scale_v': 3, 6 | 'levels': 2, 7 | 'ratio': 0.015, 8 | 'ratio_power': 2, 9 | 'flare': 0.3, 10 | 'base_size': [0.95, 0.02, 0, 0], 11 | 'down_angle': [-0, 60, 50, 0], 12 | 'down_angle_v': [-0, -80, -75, 0], 13 | 'rotate': [-0, 120, -120, 0], 14 | 'rotate_v': [-0, 60, 20, 0], 15 | 'branches': [1, 25, 0, 0], 16 | 'length': [1, 0.3, 0, 0], 17 | 'length_v': [0, 0.02, 0, 0], 18 | 'taper': [2.15, 1, 0, 0], 19 | 'seg_splits': [0, 0, 0, 0], 20 | 'split_angle': [0, 0, 0, 0], 21 | 'split_angle_v': [0, 0, 0, 0], 22 | 'curve_res': [12, 9, 0, 0], 23 | 'curve': [20, 40, 0, 0], 24 | 'curve_back': [-10, 0, 0, 0], 25 | 'curve_v': [10, 20, 0, 0], 26 | 'bend_v': [-0, 0, 0, 0], 27 | 'branch_dist': [-0, 0, 0, 0], 28 | 'leaf_blos_num': 150, 29 | 'leaf_shape': 10, 30 | 'leaf_scale': 0.8, 31 | 'leaf_scale_x': 0.12, 32 | 'leaf_bend': 0, 33 | 'tropism': [0, 0, -3] 34 | } 35 | -------------------------------------------------------------------------------- /parametric/tree_params/black_oak.py: -------------------------------------------------------------------------------- 1 | """ CA BLACK OAK """ 2 | params = { 3 | 'shape': 2, 4 | 'g_scale': 10, 5 | 'g_scale_v': 2, 6 | 'levels': 3, 7 | 'ratio': 0.018, 8 | 'ratio_power': 1.25, 9 | 'flare': 1.2, 10 | 'base_size': [0.05, 0.02, 0.02, 0.02], 11 | 'down_angle': [-0, 30, 45, 45], 12 | 'down_angle_v': [-0, -30, 10, 10], 13 | 'rotate': [-0, 80, 140, 140], 14 | 'rotate_v': [-0, 20, 20, 20], 15 | 'branches': [1, 30, 120, 0], 16 | 'length': [1, 0.8, 0.3, 0.4], 17 | 'length_v': [0, 0.1, 0.05, 0], 18 | 'taper': [0.95, 1, 1, 1], 19 | 'seg_splits': [0.1, 0.1, 0.1, 0], 20 | 'split_angle': [10, 10, 10, 0], 21 | 'split_angle_v': [0, 10, 10, 0], 22 | 'curve_res': [8, 10, 3, 1], 23 | 'curve': [0, 40, 0, 0], 24 | 'curve_back': [0, -70, 0, 0], 25 | 'curve_v': [90, 150, -30, 0], 26 | 'bend_v': [-0, 100, 0, 0], 27 | 'leaf_blos_num': 45, 28 | 'leaf_shape': 6, 29 | 'leaf_scale': 0.2, 30 | 'leaf_scale_x': 0.66, 31 | 'leaf_bend': 0.3, 32 | 'tropism': [0, 0, 0.8] 33 | } 34 | -------------------------------------------------------------------------------- /parametric/tree_params/balsam_fir.py: -------------------------------------------------------------------------------- 1 | """ BALSAM FIR """ 2 | params = { 3 | 'shape': 0, 4 | 'g_scale': 12, 5 | 'g_scale_v': 2, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.7, 9 | 'flare': 0.2, 10 | 'base_splits': 0, 11 | 'base_size': [0.05, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 50, 60, 45], 13 | 'down_angle_v': [-0, -45, 20, 30], 14 | 'rotate': [-0, 140, -125, -90], 15 | 'rotate_v': [-0, 0, 20, 20], 16 | 'branches': [1, 100, 75, 10], 17 | 'length': [1, 0.5, 0.25, 0], 18 | 'length_v': [0.2, 0, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0, 0, 0], 21 | 'split_angle': [0, 0, 0, 0], 22 | 'split_angle_v': [0, 0, 0, 0], 23 | 'curve_res': [5, 5, 2, 0], 24 | 'curve': [0, -40, 0, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [20, 10, 40, 0], 27 | 'bend_v': [-0, 10, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 100, 30 | 'leaf_shape': 2, 31 | 'leaf_scale': 0.13, 32 | 'leaf_scale_x': 0.5, 33 | 'leaf_bend': 0 34 | } 35 | -------------------------------------------------------------------------------- /parametric/tree_params/small_pine.py: -------------------------------------------------------------------------------- 1 | """ SMALL PINE """ 2 | params = { 3 | 'shape': 0, 4 | 'g_scale': 6, 5 | 'g_scale_v': 0.5, 6 | 'levels': 2, 7 | 'ratio': 0.02, 8 | 'ratio_power': 1.3, 9 | 'flare': 0.3, 10 | 'base_size': [0.05, 0.02, 0.02, 0.02], 11 | 'down_angle': [-0, 30, 30, 0], 12 | 'down_angle_v': [-0, -60, 10, 0], 13 | 'rotate': [-0, 140, 140, 0], 14 | 'rotate_v': [-0, 30, 20, 0], 15 | 'branches': [1, 70, 0, 0], 16 | 'length': [1, 0.35, 0, 0], 17 | 'length_v': [0, 0.05, 0, 0], 18 | 'taper': [1, 1, 0, 0], 19 | 'seg_splits': [0, 2, 0, 0], 20 | 'split_angle': [0, -80, 0, 0], 21 | 'split_angle_v': [0, -30, 0, 0], 22 | 'curve_res': [5, 6, 0, 0], 23 | 'curve': [0, -20, 0, 0], 24 | 'curve_back': [0, 0, 0, 0], 25 | 'curve_v': [10, 90, 0, 0], 26 | 'bend_v': [-0, 70, 0, 0], 27 | 'branch_dist': [-0, 3.5, 0, 0], 28 | 'leaf_blos_num': 400, 29 | 'leaf_shape': 2, 30 | 'leaf_scale': 0.17, 31 | 'leaf_scale_x': 0.3, 32 | 'leaf_bend': 0, 33 | 'tropism': [0, 0, 0] 34 | } 35 | -------------------------------------------------------------------------------- /parametric/tree_params/black_tupelo.py: -------------------------------------------------------------------------------- 1 | """ BLACK TUPELO """ 2 | params = { 3 | 'shape': 4, 4 | 'g_scale': 23, 5 | 'g_scale_v': 5, 6 | 'levels': 4, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.3, 9 | 'flare': 1, 10 | 'base_splits': 0, 11 | 'base_size': [0.2, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 60, 40, 45], 13 | 'down_angle_v': [-0, -40, 10, 10], 14 | 'rotate': [-0, 140, 140, 140], 15 | 'rotate_v': [-0, 60, 50, 0], 16 | 'branches': [1, 75, 25, 15], 17 | 'length': [1, 0.3, 0.6, 0.2], 18 | 'length_v': [0, 0.05, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0, 0, 0], 21 | 'split_angle': [0, 0, 0, 0], 22 | 'split_angle_v': [0, 0, 0, 0], 23 | 'curve_res': [10, 10, 10, 1], 24 | 'curve': [0, 0, -10, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [40, 90, 150, 0], 27 | 'bend_v': [-0, 100, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 20, 30 | 'leaf_shape': 0, 31 | 'leaf_scale': 0.2, 32 | 'leaf_scale_x': 1, 33 | 'leaf_bend': 0.3 34 | } 35 | -------------------------------------------------------------------------------- /parametric/tree_params/silver_birch.py: -------------------------------------------------------------------------------- 1 | """ SILVER BIRCH """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 20, 5 | 'g_scale_v': 5, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.5, 9 | 'flare': 0.5, 10 | 'base_splits': 0, 11 | 'base_size': [0.3, 0.1, 0.02, 0.02], 12 | 'down_angle': [-0, 50, 40, 45], 13 | 'down_angle_v': [-0, -20, 10, 10], 14 | 'rotate': [-0, 140, 140, 140], 15 | 'rotate_v': [-0, 60, 50, 0], 16 | 'branches': [1, 30, 60, 0], 17 | 'length': [1, 0.3, 0.4, 0], 18 | 'length_v': [0, 0.05, 0.2, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0.3, 0, 0], 21 | 'split_angle': [15, 10, 0, 0], 22 | 'split_angle_v': [0, 0, 0, 0], 23 | 'curve_res': [10, 10, 10, 0], 24 | 'curve': [0, 0, -10, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [50, 150, 200, 0], 27 | 'bend_v': [-0, 100, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 65, 30 | 'leaf_shape': 3, 31 | 'leaf_scale': 0.15, 32 | 'leaf_scale_x': 1, 33 | 'leaf_bend': 0.2, 34 | 'tropism': [0, 0, -2] 35 | } 36 | -------------------------------------------------------------------------------- /parametric/tree_params/apple.py: -------------------------------------------------------------------------------- 1 | """ APPLE """ 2 | params = { 3 | 'shape': 2, 4 | 'g_scale': 9, 5 | 'g_scale_v': 2, 6 | 'levels': 3, 7 | 'ratio': 0.02, 8 | 'ratio_power': 1.5, 9 | 'flare': 0.9, 10 | 'base_splits': 0, 11 | 'base_size': [0.15, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 60, 60, 45], 13 | 'down_angle_v': [-0, -30, 20, 30], 14 | 'rotate': [-0, 140, 140, 77], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 35, 25, 10], 17 | 'length': [1, 0.5, 0.4, 0], 18 | 'length_v': [0, 0, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0, 0.6, 0, 0], 21 | 'split_angle': [0, 20, 0, 0], 22 | 'split_angle_v': [0, 10, 0, 0], 23 | 'curve_res': [5, 10, 5, 0], 24 | 'curve': [0, -20, 0, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [70, 140, 100, 0], 27 | 'bend_v': [-0, 50, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 50, 30 | 'leaf_shape': 8, 31 | 'leaf_scale': 0.17, 32 | 'leaf_bend': 0.5, 33 | 'blossom_rate': 0.35, 34 | 'blossom_scale': 0.08, 35 | 'blossom_shape': 1, 36 | 'tropism': [0, 0, 2] 37 | } 38 | -------------------------------------------------------------------------------- /parametric/tree_params/hill_cherry.py: -------------------------------------------------------------------------------- 1 | """ HILL CHERRY """ 2 | params = { 3 | 'shape': 2, 4 | 'g_scale': 13, 5 | 'g_scale_v': 3, 6 | 'levels': 3, 7 | 'ratio': 0.015, 8 | 'ratio_power': 1.3, 9 | 'flare': 0.6, 10 | 'base_splits': -2, 11 | 'base_size': [0.15, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 70, 60, 45], 13 | 'down_angle_v': [-0, 10, 20, 30], 14 | 'rotate': [-0, 140, 140, 77], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 25, 18, 10], 17 | 'length': [0.8, 0.5, 0.6, 0], 18 | 'length_v': [0, 0, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0.5, 0.3, 0, 0], 21 | 'split_angle': [40, 40, 0, 0], 22 | 'split_angle_v': [5, 5, 0, 0], 23 | 'curve_res': [10, 5, 8, 0], 24 | 'curve': [30, -20, -40, 0], 25 | 'curve_back': [-40, 40, 0, 0], 26 | 'curve_v': [150, 150, 150, 0], 27 | 'bend_v': [150, 150, 250, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 25, 30 | 'tropism': [0, 0, -1], 31 | 'blossom_rate': 1, 32 | 'blossom_scale': 0.1, 33 | 'blossom_shape': 1, 34 | 'prune_ratio': 1, 35 | 'prune_width': 0.7, 36 | 'prune_width_peak': 0.5, 37 | 'prune_power_low': 0.2, 38 | 'prune_power_high': 0.5 39 | } 40 | -------------------------------------------------------------------------------- /parametric/tree_params/sphere_tree.py: -------------------------------------------------------------------------------- 1 | """ Default tree parameters """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 6, 5 | 'g_scale_v': 0, 6 | 'levels': 3, 7 | 'ratio': 0.025, 8 | 'ratio_power': 1.5, 9 | 'flare': 0.6, 10 | 'base_splits': 0, 11 | 'base_size': [0.5, 0.02, 0.02, 0.02], 12 | 'down_angle': [-0, 70, 45, 45], 13 | 'down_angle_v': [-0, 20, 10, 10], 14 | 'rotate': [-0, 100, 140, 77], 15 | 'rotate_v': [-0, 0, 0, 0], 16 | 'branches': [1, 70, 75, 10], 17 | 'length': [1, 1, 1, 0], 18 | 'length_v': [0, 0, 0, 0], 19 | 'taper': [2, 1, 1, 1], 20 | 'seg_splits': [0, 0, 0, 0], 21 | 'split_angle': [40, 0, 0, 0], 22 | 'split_angle_v': [5, 0, 0, 0], 23 | 'curve_res': [5, 5, 3, 1], 24 | 'curve': [0, 0, 0, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [-40, 75, 75, 0], 27 | 'bend_v': [-0, 50, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 25, 30 | 'leaf_shape': 0, 31 | 'leaf_scale': 0.17, 32 | 'leaf_scale_x': 1, 33 | 'leaf_bend': 0.3, 34 | 'tropism': [0, 0, 0], 35 | 'prune_ratio': 1, 36 | 'prune_width': 0.3, 37 | 'prune_width_peak': 0.5, 38 | 'prune_power_low': 0.5, 39 | 'prune_power_high': 0.5 40 | } 41 | -------------------------------------------------------------------------------- /parametric/tree_params/cambridge_oak.py: -------------------------------------------------------------------------------- 1 | """ CAMBRIDGE OAK """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 20, 5 | 'g_scale_v': 4, 6 | 'levels': 4, 7 | 'ratio': 0.03, 8 | 'ratio_power': 2, 9 | 'flare': 0.5, 10 | 'base_splits': 1, 11 | 'base_size': [0.2, 0, 0, 0], 12 | 'down_angle': [-0, 60, 60, 45], 13 | 'down_angle_v': [-0, -30, 30, 10], 14 | 'rotate': [-0, 110, 110, 110], 15 | 'rotate_v': [-0, 50, 50, 0], 16 | 'branches': [1, 15, 10, 50], 17 | 'length': [1, 0.4, 0.6, 0.2], 18 | 'length_v': [0, 0.1, 0.1, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0.5, 0.5, 0.2, 0], 21 | 'split_angle': [50, 50, 50, 0], 22 | 'split_angle_v': [20, 10, 10, 0], 23 | 'curve_res': [10, 10, 10, 3], 24 | 'curve': [0, 20, 0, 0], 25 | 'curve_back': [0, 0, 0, 0], 26 | 'curve_v': [100, 400, 500, 100], 27 | 'bend_v': [100, 100, 30, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'leaf_blos_num': 15, 30 | 'leaf_shape': 7, 31 | 'leaf_scale': 0.13, 32 | 'leaf_scale_x': 1, 33 | 'leaf_bend': 0, 34 | 'tropism': [0, 0, 0.5], 35 | 'prune_ratio': 1, 36 | 'prune_width': 0.6, 37 | 'prune_width_peak': 0.2, 38 | 'prune_power_low': 0.1, 39 | 'prune_power_high': 0.5 40 | } 41 | -------------------------------------------------------------------------------- /parametric/tree_params/weeping_willow.py: -------------------------------------------------------------------------------- 1 | """ WEEPING WILLOW """ 2 | params = { 3 | 'shape': 4, 4 | 'g_scale': 15, 5 | 'g_scale_v': 3, 6 | 'levels': 4, 7 | 'ratio': 0.03, 8 | 'ratio_power': 1.2, 9 | 'flare': 0.75, 10 | 'base_splits': 2, 11 | 'base_size': [0.05, 0.3, 0.05, 0.05], 12 | 'down_angle': [-0, 40, 30, 20], 13 | 'down_angle_v': [-0, 10, 10, 10], 14 | 'rotate': [-0, -120, -120, 140], 15 | 'rotate_v': [-0, 30, 30, 0], 16 | 'branches': [1, 17, 25, 75], 17 | 'length': [1, 0.35, 2.0, 0.1], 18 | 'length_v': [0, 0.1, 0, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0.2, 0.2, 0.1, 0], 21 | 'split_angle': [40, 30, 45, 0], 22 | 'split_angle_v': [5, 10, 20, 0], 23 | 'curve_res': [8, 16, 12, 2], 24 | 'curve': [0, 40, 0, 0], 25 | 'curve_back': [25, 0, 0, 0], 26 | 'curve_v': [90, 200, 0, 0], 27 | 'bend_v': [0, 160, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'radius_mod': [1, 1, 0.1, 1], 30 | 'leaf_blos_num': 20, 31 | 'leaf_shape': 0, 32 | 'leaf_scale': 0.13, 33 | 'leaf_scale_x': 0.2, 34 | 'leaf_bend': 0, 35 | 'tropism': [0, 0, -3], 36 | 'prune_ratio': 1, 37 | 'prune_width': 0.4, 38 | 'prune_width_peak': 0.6, 39 | 'prune_power_low': 0.001, 40 | 'prune_power_high': 0.5 41 | } 42 | -------------------------------------------------------------------------------- /parametric/tree_params/weeping_willow_o.py: -------------------------------------------------------------------------------- 1 | """ WEEPING WILLOW """ 2 | params = { 3 | 'shape': 3, 4 | 'g_scale': 15, 5 | 'g_scale_v': 5, 6 | 'levels': 4, 7 | 'ratio': 0.03, 8 | 'ratio_power': 2, 9 | 'flare': 0.75, 10 | 'base_splits': 2, 11 | 'base_size': [0.05, 0.3, 0.05, 0.05], 12 | 'down_angle': [-0, 20, 30, 20], 13 | 'down_angle_v': [-0, 10, 10, 10], 14 | 'rotate': [-0, -120, -120, 140], 15 | 'rotate_v': [-0, 30, 30, 0], 16 | 'branches': [1, 25, 10, 300], 17 | 'length': [0.8, 0.5, 1.5, 0.1], 18 | 'length_v': [0, 0.1, 0, 0], 19 | 'taper': [1, 1, 1, 1], 20 | 'seg_splits': [0.1, 0.2, 0.2, 0], 21 | 'split_angle': [3, 30, 45, 0], 22 | 'split_angle_v': [0, 10, 20, 0], 23 | 'curve_res': [8, 16, 12, 1], 24 | 'curve': [0, 40, 0, 0], 25 | 'curve_back': [20, 80, 0, 0], 26 | 'curve_v': [120, 90, 0, 0], 27 | 'bend_v': [0, 0, 0, 0], 28 | 'branch_dist': [-0, 0, 0, 0], 29 | 'radius_mod': [1, 1, 1, 1], 30 | 'leaf_blos_num': 15, 31 | 'leaf_shape': 0, 32 | 'leaf_scale': 0.12, 33 | 'leaf_scale_x': 0.2, 34 | 'leaf_bend': 0, 35 | 'tropism': [0, 0, -3], 36 | 'prune_ratio': 1, 37 | 'prune_width': 0.4, 38 | 'prune_width_peak': 0.6, 39 | 'prune_power_low': 0.001, 40 | 'prune_power_high': 0.5 41 | } 42 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | bl_info = { 2 | "name": "TreeGen", 3 | "category": "Object", 4 | "description": "Generate high quality tree models", 5 | "author": "Charlie Hewitt and Sami Pflibsen-Jones", 6 | "version": (0, 0, 4), 7 | "wiki_url": "https://github.com/friggog/tree-gen/wiki", 8 | "tracker_url": "https://github.com/friggog/tree-gen/issues/new/choose", 9 | 'blender': (2, 80, 0) 10 | } 11 | 12 | 13 | import bpy 14 | from . import gui 15 | 16 | 17 | def register(): 18 | bpy.utils.register_class(gui.TreeGen) 19 | bpy.utils.register_class(gui.TreeGenPanel) 20 | bpy.utils.register_class(gui.TreeGenCustomisePanel) 21 | bpy.utils.register_class(gui.TreeGenUtilitiesPanel) 22 | bpy.utils.register_class(gui.TreeGenRender) 23 | bpy.utils.register_class(gui.TreeGenConvertToMesh) 24 | bpy.utils.register_class(gui.TreeGenCreateLeafLODs) 25 | bpy.utils.register_class(gui.TreeGenMainThreadExecuter) 26 | bpy.utils.register_class(gui.TreeGenSaveFile) 27 | bpy.utils.register_class(gui.TreeGenLoadParams) 28 | 29 | 30 | def unregister(): 31 | # Reversing order is best-practice 32 | bpy.utils.unregister_class(gui.TreeGenLoadParams) 33 | bpy.utils.unregister_class(gui.TreeGenSaveFile) 34 | bpy.utils.unregister_class(gui.TreeGenMainThreadExecuter) 35 | bpy.utils.unregister_class(gui.TreeGenCreateLeafLODs) 36 | bpy.utils.unregister_class(gui.TreeGenConvertToMesh) 37 | bpy.utils.unregister_class(gui.TreeGenRender) 38 | bpy.utils.unregister_class(gui.TreeGenUtilitiesPanel) 39 | bpy.utils.unregister_class(gui.TreeGenCustomisePanel) 40 | bpy.utils.unregister_class(gui.TreeGenPanel) 41 | bpy.utils.unregister_class(gui.TreeGen) 42 | 43 | 44 | if __name__ == "__main__": 45 | register() 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # PyCharm user preferences 4 | .idea/ 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | 111 | 112 | # ======== 113 | build.bat 114 | staging/ 115 | .idea/ 116 | build_and_run.bat 117 | -------------------------------------------------------------------------------- /parametric/tree_params/tree_param.py: -------------------------------------------------------------------------------- 1 | """ Default tree parameters """ 2 | 3 | import sys 4 | import copy 5 | 6 | defaults = { 7 | 'shape': 7, 8 | 'g_scale': 13, 9 | 'g_scale_v': 3, 10 | 'levels': 3, 11 | 'ratio': 0.015, 12 | 'ratio_power': 1.2, 13 | 'flare': 0.6, 14 | 'base_splits': 0, 15 | 'base_size': [0.3, 0.02, 0.02, 0.02], 16 | 'down_angle': [-0, 60, 45, 45], 17 | 'down_angle_v': [-0, -50, 10, 10], 18 | 'rotate': [-0, 140, 140, 77], 19 | 'rotate_v': [-0, 0, 0, 0], 20 | 'branches': [1, 50, 30, 10], 21 | 'length': [1, 0.3, 0.6, 0], 22 | 'length_v': [0, 0, 0, 0], 23 | 'taper': [1, 1, 1, 1], 24 | 'seg_splits': [0, 0, 0, 0], 25 | 'split_angle': [40, 0, 0, 0], 26 | 'split_angle_v': [5, 0, 0, 0], 27 | 'bevel_res': [10, 10, 10, 10], 28 | 'curve_res': [5, 5, 3, 1], 29 | 'curve': [0, -40, -40, 0], 30 | 'curve_back': [0, 0, 0, 0], 31 | 'curve_v': [20, 50, 75, 0], 32 | 'bend_v': [-0, 50, 0, 0], 33 | 'branch_dist': [-0, 0, 0, 0], 34 | 'radius_mod': [1, 1, 1, 1], 35 | 'leaf_blos_num': 40, 36 | 'leaf_shape': 0, 37 | 'leaf_scale': 0.17, 38 | 'leaf_scale_x': 1, 39 | 'leaf_bend': 0.6, 40 | 'blossom_shape': 1, 41 | 'blossom_scale': 0, 42 | 'blossom_rate': 0, 43 | 'tropism': [0, 0, 0.5], 44 | 'prune_ratio': 0, 45 | 'prune_width': 0.5, 46 | 'prune_width_peak': 0.5, 47 | 'prune_power_low': 0.5, 48 | 'prune_power_high': 0.5 49 | } 50 | 51 | 52 | class TreeParam(object): 53 | """parameter list for default tree (aspen)""" 54 | 55 | def __init__(self, params): 56 | """initialize parameters from dictionary representation""" 57 | 58 | self.params = copy.deepcopy(defaults) 59 | 60 | filtered = {} 61 | for k, v in params.items(): 62 | if k not in self.params: 63 | sys.stdout.write('TreeGen :: Warning: Unrecognized name in configuration "{}"'.format(k)) 64 | sys.stdout.flush() 65 | else: 66 | filtered[k] = v 67 | 68 | # Copy parameters into instance 69 | self.params.update(filtered) 70 | 71 | # Specialized parameter formatting 72 | for var in ['shape', 'levels', 'leaf_shape', 'blossom_shape']: 73 | if var in filtered: 74 | self.params[var] = abs(int(filtered[var])) 75 | if 'base_splits' in filtered: 76 | self.params['base_splits'] = int(filtered['base_splits']) 77 | if 'branches' in filtered: 78 | self.params['branches'] = [int(filtered['branches'][i]) for i in range(len(filtered['branches']))] 79 | 80 | self.__dict__.update(self.params) 81 | -------------------------------------------------------------------------------- /chturtle.py: -------------------------------------------------------------------------------- 1 | """3D Turtle implementation for use in tree generation module, also extends 2 | Blender Vector class with some useful methods""" 3 | 4 | from math import radians, degrees, atan2, sqrt 5 | from random import random as random_random 6 | 7 | import mathutils 8 | from mathutils import Quaternion 9 | 10 | 11 | class Vector(mathutils.Vector): 12 | """Extension of the standard Vector class with some useful methods""" 13 | 14 | @staticmethod 15 | def random(): 16 | """Normalised vector containing random entries in all dimensions""" 17 | vec = Vector([random_random(), random_random(), random_random()]) 18 | vec.normalize() 19 | return vec 20 | 21 | def rotated(self, rotation): 22 | vec = self.copy() 23 | vec.rotate(rotation) 24 | return vec 25 | 26 | def declination(self): 27 | """Calculate declination of vector in degrees""" 28 | return degrees(atan2(sqrt(self.x ** 2 + self.y ** 2), self.z)) 29 | 30 | 31 | class CHTurtle(object): 32 | """3D turtle implementation for use in both L-Systems and Parametric tree 33 | generation schemes""" 34 | 35 | __slots__ = ( 36 | 'dir', 'pos', 'right', 'width' 37 | ) 38 | 39 | def __init__(self, other=None): 40 | """Copy Constructor""" 41 | 42 | if other is not None: 43 | self.dir = other.dir.copy() 44 | self.pos = other.pos.copy() 45 | self.right = other.right.copy() 46 | self.width = other.width 47 | 48 | else: 49 | self.dir = Vector([0.0, 0.0, 1.0]) 50 | self.pos = Vector([0.0, 0.0, 0.0]) 51 | self.right = Vector([1.0, 0.0, 0.0]) 52 | self.width = 0.0 53 | 54 | def __str__(self): 55 | return 'Turtle at %s, direction %s, right %s' % (self.pos, self.dir, self.right) 56 | 57 | def turn_right(self, angle): 58 | """Turn the turtle right about the axis perpendicular to the direction 59 | it is facing""" 60 | 61 | axis = (self.dir.cross(self.right)) 62 | axis.normalize() 63 | 64 | rot_quat = Quaternion(axis, radians(angle)) 65 | 66 | self.dir.rotate(rot_quat) 67 | self.dir.normalize() 68 | self.right.rotate(rot_quat) 69 | self.right.normalize() 70 | 71 | def turn_left(self, angle): 72 | """Turn the turtle left about the axis perpendicular to the direction it 73 | is facing""" 74 | 75 | axis = (self.dir.cross(self.right)) 76 | axis.normalize() 77 | 78 | rot_quat = Quaternion(axis, radians(-angle)) 79 | 80 | self.dir.rotate(rot_quat) 81 | self.dir.normalize() 82 | self.right.rotate(rot_quat) 83 | self.right.normalize() 84 | 85 | def pitch_up(self, angle): 86 | """Pitch the turtle up about the right axis""" 87 | self.dir.rotate(Quaternion(self.right, radians(angle))) 88 | self.dir.normalize() 89 | 90 | def pitch_down(self, angle): 91 | """Pitch the turtle down about the right axis""" 92 | self.dir.rotate(Quaternion(self.right, radians(-angle))) 93 | self.dir.normalize() 94 | 95 | def roll_right(self, angle): 96 | """Roll the turtle right about the direction it is facing""" 97 | self.right.rotate(Quaternion(self.dir, radians(angle))) 98 | self.right.normalize() 99 | 100 | def roll_left(self, angle): 101 | """Roll the turtle left about the direction it is facing""" 102 | self.right.rotate(Quaternion(self.dir, radians(-angle))) 103 | self.right.normalize() 104 | 105 | def move(self, distance): 106 | """Move the turtle in the direction it is facing by specified distance""" 107 | self.pos += self.dir * distance 108 | 109 | def set_width(self, width): 110 | """Set the width stored by the turtle""" 111 | self.width = width 112 | -------------------------------------------------------------------------------- /leaf.py: -------------------------------------------------------------------------------- 1 | """Leaf module shared by L-System and Parametric tree generators""" 2 | 3 | from math import atan2, pi 4 | 5 | from .chturtle import Vector 6 | from mathutils import Quaternion 7 | 8 | from . import leaf_shapes as leaf_geom 9 | 10 | 11 | class Leaf(object): 12 | """Class to store data for each leaf in the system""" 13 | 14 | __slots__ = ( 15 | 'position', 'direction', 'right' 16 | ) 17 | 18 | def __init__(self, pos, direction, right): 19 | """Init method for leaf with position, direction and relative x axis""" 20 | self.position = pos 21 | self.direction = direction 22 | self.right = right 23 | 24 | @classmethod 25 | def get_shape(cls, leaf_type, g_scale, scale, scale_x): 26 | """returns the base leaf shape mesh""" 27 | u_v = [] 28 | 29 | if leaf_type < 0: # blossom 30 | if leaf_type < -3: # out of range 31 | leaf_type = -1 32 | shape = leaf_geom.blossom(abs(leaf_type + 1)) 33 | 34 | else: # leaf 35 | if leaf_type < 1 or leaf_type > 10: # is out of range or explicitly default 36 | leaf_type = 8 37 | shape = leaf_geom.leaves(leaf_type - 1) 38 | 39 | verts = shape[0] 40 | faces = shape[1] 41 | if len(shape) == 3: 42 | u_v = shape[2] 43 | 44 | for vert in verts: 45 | vert *= scale * g_scale 46 | vert.x *= scale_x 47 | 48 | return verts, faces, u_v 49 | 50 | def get_mesh(self, bend, base_shape, index): 51 | """produce leaf mesh at position of this leaf given base mesh as input""" 52 | 53 | # calculate angles to transform mesh to align with desired direction 54 | trf = self.direction.to_track_quat('Z', 'Y') 55 | right_t = self.right.rotated(trf.inverted()) 56 | spin_ang = pi - right_t.angle(Vector([1, 0, 0])) 57 | spin_ang_quat = Quaternion(Vector([0, 0, 1]), spin_ang) 58 | 59 | # calculate bend transform if needed 60 | if bend > 0: 61 | bend_trf_1, bend_trf_2 = self.calc_bend_trf(bend) 62 | else: 63 | bend_trf_1 = None 64 | 65 | vertices = [] 66 | for vertex in base_shape[0]: 67 | # rotate to correct direction 68 | n_vertex = vertex.copy() 69 | n_vertex.rotate(spin_ang_quat) 70 | n_vertex.rotate(trf) 71 | 72 | # apply bend if needed 73 | if bend > 0: 74 | n_vertex.rotate(bend_trf_1) 75 | # n_vertex.rotate(bend_trf_2) 76 | 77 | # move to right position 78 | n_vertex += self.position 79 | 80 | # add to vertex array 81 | vertices.append(n_vertex) 82 | 83 | # set face to refer to vertices at correct offset in big vertex list 84 | index *= len(vertices) 85 | 86 | faces = [[elem + index for elem in face] for face in base_shape[1]] 87 | 88 | return vertices, faces 89 | 90 | def calc_bend_trf(self, bend): 91 | """calculate the transformations required to 'bend' the leaf out/up from WP""" 92 | normal = self.direction.cross(self.right) 93 | theta_pos = atan2(self.position.y, self.position.x) 94 | theta_bend = theta_pos - atan2(normal.y, normal.x) 95 | bend_trf_1 = Quaternion(Vector([0, 0, 1]), theta_bend * bend) 96 | 97 | # i think this is what the paper says but the second transform just looks stupid 98 | # so we just ignore it above 99 | 100 | self.direction.rotate(bend_trf_1) 101 | self.right.rotate(bend_trf_1) 102 | normal = self.direction.cross(self.right) 103 | phi_bend = normal.declination() 104 | 105 | if phi_bend > pi / 2: 106 | phi_bend = phi_bend - pi 107 | 108 | bend_trf_2 = Quaternion(self.right, phi_bend * bend) 109 | 110 | return bend_trf_1, bend_trf_2 111 | -------------------------------------------------------------------------------- /utilities.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bmesh 3 | import mathutils 4 | 5 | import random 6 | import sys 7 | import threading 8 | import time 9 | from queue import Queue 10 | 11 | 12 | class _LogThread(threading.Thread): 13 | # Set to run as a daemon, so this thread kills itself at program termination 14 | 15 | def __init__(self, queue): 16 | threading.Thread.__init__(self) 17 | 18 | self.queue = queue 19 | self.daemon = True 20 | self.running = False 21 | 22 | def run(self): 23 | self.running = True 24 | 25 | while True: 26 | msg = self.queue.get() 27 | sys.stdout.write(str(msg)) 28 | sys.stdout.flush() 29 | 30 | 31 | thread_queue = None 32 | log_thread = None 33 | 34 | 35 | def get_logger(logging): 36 | global log_thread, thread_queue 37 | 38 | if logging: 39 | if log_thread is None: 40 | thread_queue = Queue() 41 | log_thread = _LogThread(thread_queue) 42 | log_thread.start() 43 | 44 | def update_log(msg): 45 | global log_thread 46 | if not log_thread.running: 47 | log_thread = _LogThread(thread_queue) 48 | log_thread.start() 49 | 50 | thread_queue.put(msg) 51 | 52 | return update_log 53 | 54 | def update_log(msg): 55 | pass 56 | 57 | return lambda _: None 58 | 59 | 60 | def object_deleted(o): 61 | try: 62 | return bpy.data.objects.get(o.name, None) is not None 63 | except ReferenceError: # o is deleted, so accessing name raises an error 64 | return True 65 | 66 | 67 | def convert_to_mesh(context): 68 | """ 69 | Converts tree branches from curve to mesh 70 | """ 71 | 72 | from . import parametric 73 | update_log = parametric.gen.update_log 74 | 75 | try: 76 | tree = context.object 77 | except AttributeError: 78 | raise Exception('Could not find tree while attempting to convert to mesh') 79 | 80 | new_branches = [] 81 | old_branches = [child for child in tree.children if (child.name.startswith('Trunk') or child.name.startswith('Branches')) 82 | and str(type(child.data)) == ""] 83 | 84 | if len(old_branches) == 0: 85 | raise Exception('No branches found while converting to mesh') 86 | 87 | for old_branch in old_branches: 88 | old_branch_name = old_branch.name 89 | old_mesh_name = old_branch.data.name 90 | 91 | # Convert the branches curve to a mesh, then get an editable copy 92 | old_branch_mesh = old_branch.to_mesh() 93 | br_bmesh = bmesh.new() 94 | br_bmesh.from_mesh(old_branch_mesh) 95 | 96 | # Purge old branch data from memory 97 | old_branch.to_mesh_clear() 98 | 99 | bpy.data.curves.remove(old_branch.data) 100 | 101 | if not object_deleted(old_branch): 102 | bpy.data.objects.remove(old_branch, True) 103 | 104 | # Create a new mesh and container object 105 | new_branch = bpy.data.objects.new(old_branch_name, bpy.data.meshes.new(old_mesh_name)) 106 | br_bmesh.to_mesh(new_branch.data) 107 | 108 | # Purge bmesh from memory 109 | br_bmesh.free() 110 | 111 | # Make the mesh active in the scene, then associate it with the tree 112 | context.collection.objects.link(new_branch) 113 | new_branch.matrix_world = tree.matrix_world 114 | new_branch.parent = tree 115 | new_branches.append(new_branch) 116 | 117 | if context.scene.tree_gen_merge_verts_by_distance: 118 | update_log('Merging duplicate vertices; this will take a bit for complex trees.\n') 119 | 120 | for new_branch in new_branches: 121 | context.view_layer.objects.active = new_branch 122 | bpy.ops.object.mode_set(mode='EDIT', toggle=True) 123 | bpy.ops.mesh.select_all(action='SELECT') 124 | bpy.ops.mesh.remove_doubles(threshold=0.0001) 125 | 126 | 127 | def generate_leaf_lods(context, level_count=3): 128 | from . import parametric 129 | update_log = parametric.gen.update_log 130 | 131 | tree = context.object 132 | 133 | original = None 134 | for child in tree.children: 135 | if child.name.startswith('Leaves'): 136 | base_name = child.name 137 | child.name = child.name + '_LOD0' 138 | original = child 139 | parent = child.parent 140 | break 141 | 142 | if original is None: 143 | raise Exception('No leaves found while attempting to generate LODs') 144 | 145 | leaf_count = len(original.data.polygons) 146 | lod_reduce_amounts = [.9, .6, .4] 147 | lod_leaf_counts = [round(leaf_count * lod_reduce_amounts[0]), 148 | round(leaf_count * lod_reduce_amounts[1]), 149 | round(leaf_count * lod_reduce_amounts[2])] 150 | 151 | for level in range(level_count): 152 | new_leaf_data = bmesh.new() 153 | new_leaf_data.from_mesh(original.data) 154 | new_leaf_count = lod_leaf_counts[level] 155 | 156 | # Delete faces 157 | if new_leaf_count > 8: # Prevent infinite loops 158 | amount_to_delete = leaf_count - new_leaf_count 159 | indexes_to_delete = set(random.randint(0, leaf_count - 1) for _ in range(amount_to_delete)) 160 | while len(indexes_to_delete) < amount_to_delete: 161 | indexes_to_delete.add(random.randint(0, leaf_count - 1)) 162 | 163 | new_leaf_data.faces.ensure_lookup_table() 164 | to_delete = [new_leaf_data.faces[i] for i in indexes_to_delete] 165 | 166 | bmesh.ops.delete(new_leaf_data, geom=list(to_delete), context='FACES') 167 | 168 | # Create new leaves object and copy the new leaves data into it 169 | lod_level_name = '_LOD' + str(level + 1) 170 | new_leaves = bpy.data.objects.new(base_name + lod_level_name, bpy.data.meshes.new('leaves' + lod_level_name)) 171 | new_leaf_data.to_mesh(new_leaves.data) 172 | new_leaf_data.free() 173 | 174 | # Add new leaves object to the scene 175 | context.collection.objects.link(new_leaves) 176 | new_leaves.matrix_world = parent.matrix_world 177 | new_leaves.parent = parent 178 | new_leaves.hide_set(True) 179 | 180 | update_log('\rLeaf LOD level ' + str(level + 1) + '/' + str(level_count) + ' generated') 181 | 182 | context.view_layer.objects.active = tree 183 | 184 | update_log('\n') 185 | 186 | 187 | def render_tree(output_path): 188 | from . import parametric 189 | update_log = parametric.gen.update_log 190 | 191 | update_log('\nRendering Scene\n') 192 | 193 | targets = None 194 | for obj in bpy.context.scene.objects: 195 | bpy.context.active_object.select_set(state=False) 196 | targets = [obj] + [child for child in obj.children] if obj.name.startswith('Tree') else targets 197 | 198 | if targets is None: 199 | print('Could not find a tree to render') 200 | return 201 | 202 | for target in targets: 203 | target.select_set(state=True) 204 | 205 | bpy.ops.view3d.camera_to_view_selected() 206 | 207 | time.sleep(.2) 208 | 209 | try: 210 | camera = bpy.context.scene.camera 211 | except KeyError: 212 | print('Could not find camera to capture with') 213 | return 214 | 215 | inv = camera.matrix_world.copy() 216 | inv.invert() 217 | 218 | vec = mathutils.Vector((0.0, 0, 1.0)) # move camera back a bit 219 | vec_rot = vec @ inv # vec aligned to local axis 220 | camera.location = camera.location + vec_rot 221 | 222 | bpy.data.scenes['Scene'].render.filepath = output_path 223 | bpy.ops.render.render(write_still=True) 224 | -------------------------------------------------------------------------------- /leaf_shapes.py: -------------------------------------------------------------------------------- 1 | """Pre-defined geometries for leaf and blossom meshes""" 2 | 3 | from .chturtle import Vector 4 | 5 | # these can't be global (static) or the shared instances gets modified by other stuff 6 | # performing deepcopies is slow and causes other issues 7 | # wrapping a function around the definitions prevents external access and solves all other issues 8 | 9 | 10 | def leaves(t): 11 | return [ 12 | ( # 1 = ovate 13 | [ 14 | Vector([0.005, 0, 0]), 15 | Vector([0.005, 0, 0.1]), 16 | Vector([0.15, 0, 0.15]), 17 | Vector([0.25, 0, 0.3]), 18 | Vector([0.2, 0, 0.6]), 19 | Vector([0, 0, 1]), 20 | Vector([-0.2, 0, 0.6]), 21 | Vector([-0.25, 0, 0.3]), 22 | Vector([-0.15, 0, 0.15]), 23 | Vector([-0.005, 0, 0.1]), 24 | Vector([-0.005, 0, 0]), 25 | ], 26 | [[0, 1, 9, 10], [1, 2, 3, 4], [4, 5, 6], [6, 7, 8, 9], [4, 6, 9, 1]], 27 | ), 28 | ( # 2 = linear 29 | [ 30 | Vector([0.005, 0, 0]), 31 | Vector([0.005, 0, 0.1]), 32 | Vector([0.1, 0, 0.15]), 33 | Vector([0.1, 0, 0.95]), 34 | Vector([0, 0, 1]), 35 | Vector([-0.1, 0, 0.95]), 36 | Vector([-0.1, 0, 0.15]), 37 | Vector([-0.005, 0, 0.1]), 38 | Vector([-0.005, 0, 0]), 39 | ], 40 | [[0, 1, 7, 8], [1, 2, 3], [3, 4, 5], [5, 6, 7], [1, 3, 5, 7]], 41 | ), 42 | ( # 3 = cordate 43 | [ 44 | Vector([0.005, 0, 0]), 45 | Vector([0.01, 0, 0.2]), 46 | Vector([0.2, 0, 0.1]), 47 | Vector([0.35, 0, 0.35]), 48 | Vector([0.25, 0, 0.6]), 49 | Vector([0.1, 0, 0.8]), 50 | Vector([0, 0, 1]), 51 | Vector([-0.1, 0, 0.8]), 52 | Vector([-0.25, 0, 0.6]), 53 | Vector([-0.35, 0, 0.35]), 54 | Vector([-0.2, 0, 0.1]), 55 | Vector([-0.01, 0, 0.2]), 56 | Vector([-0.005, 0, 0]), 57 | ], 58 | [ 59 | [0, 1, 11, 12], 60 | [1, 2, 3, 4], 61 | [11, 10, 9, 8], 62 | [11, 1, 4, 8], 63 | [8, 7, 6, 5, 4], 64 | ], 65 | ), 66 | ( # 4 = maple 67 | [ 68 | Vector([0.005, 0, 0]), 69 | Vector([0.005, 0, 0.1]), 70 | Vector([0.25, 0, 0.07]), 71 | Vector([0.2, 0, 0.18]), 72 | Vector([0.5, 0, 0.37]), 73 | Vector([0.43, 0, 0.4]), 74 | Vector([0.45, 0, 0.58]), 75 | Vector([0.3, 0, 0.57]), 76 | Vector([0.27, 0, 0.67]), 77 | Vector([0.11, 0, 0.52]), 78 | Vector([0.2, 0, 0.82]), 79 | Vector([0.08, 0, 0.77]), 80 | Vector([0, 0, 1]), 81 | Vector([-0.08, 0, 0.77]), 82 | Vector([-0.2, 0, 0.82]), 83 | Vector([-0.11, 0, 0.52]), 84 | Vector([-0.27, 0, 0.67]), 85 | Vector([-0.3, 0, 0.57]), 86 | Vector([-0.45, 0, 0.58]), 87 | Vector([-0.43, 0, 0.4]), 88 | Vector([-0.5, 0, 0.37]), 89 | Vector([-0.2, 0, 0.18]), 90 | Vector([-0.25, 0, 0.07]), 91 | Vector([-0.005, 0, 0.1]), 92 | Vector([-0.005, 0, 0]), 93 | ], 94 | [ 95 | [0, 1, 23, 24], 96 | [1, 2, 3, 4, 5], 97 | [23, 22, 21, 20, 19], 98 | [1, 5, 6, 7, 8], 99 | [23, 19, 18, 17, 16], 100 | [1, 8, 9, 10, 11], 101 | [23, 16, 15, 14, 13], 102 | [1, 11, 12, 13, 23], 103 | ], 104 | ), 105 | ( # 5 = palmate 106 | [ 107 | Vector([0.005, 0, 0]), 108 | Vector([0.005, 0, 0.1]), 109 | Vector([0.25, 0, 0.1]), 110 | Vector([0.5, 0, 0.3]), 111 | Vector([0.2, 0, 0.45]), 112 | Vector([0, 0, 1]), 113 | Vector([-0.2, 0, 0.45]), 114 | Vector([-0.5, 0, 0.3]), 115 | Vector([-0.25, 0, 0.1]), 116 | Vector([-0.005, 0, 0.1]), 117 | Vector([-0.005, 0, 0]), 118 | ], 119 | [[0, 1, 9, 10], [1, 2, 3, 4], [1, 4, 5, 6, 9], [9, 8, 7, 6]], 120 | ), 121 | ( # 6 = spiky oak 122 | [ 123 | Vector([0.005, 0, 0]), 124 | Vector([0.005, 0, 0.1]), 125 | Vector([0.16, 0, 0.17]), 126 | Vector([0.11, 0, 0.2]), 127 | Vector([0.23, 0, 0.33]), 128 | Vector([0.15, 0, 0.34]), 129 | Vector([0.32, 0, 0.55]), 130 | Vector([0.16, 0, 0.5]), 131 | Vector([0.27, 0, 0.75]), 132 | Vector([0.11, 0, 0.7]), 133 | Vector([0.18, 0, 0.9]), 134 | Vector([0.07, 0, 0.86]), 135 | Vector([0, 0, 1]), 136 | Vector([-0.07, 0, 0.86]), 137 | Vector([-0.18, 0, 0.9]), 138 | Vector([-0.11, 0, 0.7]), 139 | Vector([-0.27, 0, 0.75]), 140 | Vector([-0.16, 0, 0.5]), 141 | Vector([-0.32, 0, 0.55]), 142 | Vector([-0.15, 0, 0.34]), 143 | Vector([-0.23, 0, 0.33]), 144 | Vector([-0.11, 0, 0.2]), 145 | Vector([-0.16, 0, 0.17]), 146 | Vector([-0.005, 0, 0.1]), 147 | Vector([-0.005, 0, 0]), 148 | ], 149 | [ 150 | [0, 1, 23, 24], 151 | [1, 2, 3], 152 | [3, 4, 5], 153 | [5, 6, 7], 154 | [7, 8, 9], 155 | [9, 10, 11], 156 | [1, 3, 5, 7, 9, 11, 12, 13, 15, 17, 19, 21, 23], 157 | [23, 22, 21], 158 | [21, 20, 19], 159 | [19, 18, 17], 160 | [17, 16, 15], 161 | [15, 14, 13], 162 | ], 163 | ), 164 | ( # 7 = round oak 165 | [ 166 | Vector([0.005, 0, 0]), 167 | Vector([0.005, 0, 0.1]), 168 | Vector([0.11, 0, 0.16]), 169 | Vector([0.11, 0, 0.2]), 170 | Vector([0.22, 0, 0.26]), 171 | Vector([0.23, 0, 0.32]), 172 | Vector([0.15, 0, 0.34]), 173 | Vector([0.25, 0, 0.45]), 174 | Vector([0.23, 0, 0.53]), 175 | Vector([0.16, 0, 0.5]), 176 | Vector([0.23, 0, 0.64]), 177 | Vector([0.2, 0, 0.72]), 178 | Vector([0.11, 0, 0.7]), 179 | Vector([0.16, 0, 0.83]), 180 | Vector([0.12, 0, 0.87]), 181 | Vector([0.06, 0, 0.85]), 182 | Vector([0.07, 0, 0.95]), 183 | Vector([0, 0, 1]), 184 | Vector([-0.07, 0, 0.95]), 185 | Vector([-0.06, 0, 0.85]), 186 | Vector([-0.12, 0, 0.87]), 187 | Vector([-0.16, 0, 0.83]), 188 | Vector([-0.11, 0, 0.7]), 189 | Vector([-0.2, 0, 0.72]), 190 | Vector([-0.23, 0, 0.64]), 191 | Vector([-0.16, 0, 0.5]), 192 | Vector([-0.23, 0, 0.53]), 193 | Vector([-0.25, 0, 0.45]), 194 | Vector([-0.15, 0, 0.34]), 195 | Vector([-0.23, 0, 0.32]), 196 | Vector([-0.22, 0, 0.26]), 197 | Vector([-0.11, 0, 0.2]), 198 | Vector([-0.11, 0, 0.16]), 199 | Vector([-0.005, 0, 0.1]), 200 | Vector([-0.005, 0, 0]), 201 | ], 202 | [ 203 | [0, 1, 33, 34], 204 | [1, 2, 3], 205 | [3, 4, 5, 6], 206 | [6, 7, 8, 9], 207 | [9, 10, 11, 12], 208 | [12, 13, 14, 15], 209 | [15, 16, 17], 210 | [1, 3, 6, 9, 12, 15, 17, 19, 22, 25, 28, 31, 33], 211 | [33, 32, 31], 212 | [31, 30, 29, 28], 213 | [28, 27, 26, 25], 214 | [25, 24, 23, 22], 215 | [22, 21, 20, 19], 216 | [19, 18, 17], 217 | ], 218 | ), 219 | ( # 8 = elliptic (default) 220 | [ 221 | Vector([0.005, 0, 0]), 222 | Vector([0.005, 0, 0.1]), 223 | Vector([0.15, 0, 0.2]), 224 | Vector([0.25, 0, 0.45]), 225 | Vector([0.2, 0, 0.75]), 226 | Vector([0, 0, 1]), 227 | Vector([-0.2, 0, 0.75]), 228 | Vector([-0.25, 0, 0.45]), 229 | Vector([-0.15, 0, 0.2]), 230 | Vector([-0.005, 0, 0.1]), 231 | Vector([-0.005, 0, 0]), 232 | ], 233 | [[0, 1, 9, 10], [1, 2, 3, 4], [4, 5, 6], [6, 7, 8, 9], [4, 6, 9, 1]], 234 | ), 235 | ( # 9 = rectangle 236 | [ 237 | Vector([-0.5, 0, 0]), 238 | Vector([-0.5, 0, 1]), 239 | Vector([0.5, 0, 1]), 240 | Vector([0.5, 0, 0]), 241 | ], 242 | [[0, 1, 2, 3]], 243 | [(0, 0), (0, 1), (1, 1), (1, 0)], 244 | ), 245 | ( # 10 = triangle 246 | [Vector([-0.5, 0, 0]), Vector([0, 0, 1]), Vector([0.5, 0, 0])], 247 | [[0, 1, 2]], 248 | [(0, 0), (0.5, 1), (1, 0)], 249 | ), 250 | ][t] 251 | 252 | 253 | def blossom(t): 254 | return [ 255 | ( # 1 = cherry 256 | [ 257 | Vector([0, 0, 0]), 258 | Vector([0.33, 0.45, 0.45]), 259 | Vector([0.25, 0.6, 0.6]), 260 | Vector([0, 0.7, 0.7]), 261 | Vector([-0.25, 0.6, 0.6]), 262 | Vector([-0.33, 0.45, 0.45]), 263 | Vector([0.49, 0.42, 0.6]), 264 | Vector([0.67, 0.22, 0.7]), 265 | Vector([0.65, -0.05, 0.6]), 266 | Vector([0.53, -0.17, 0.45]), 267 | Vector([0.55, -0.33, 0.6]), 268 | Vector([0.41, -0.57, 0.7]), 269 | Vector([0.15, -0.63, 0.6]), 270 | Vector([0, -0.55, 0.45]), 271 | Vector([-0.15, -0.63, 0.6]), 272 | Vector([-0.41, -0.57, 0.7]), 273 | Vector([-0.55, -0.33, 0.6]), 274 | Vector([-0.53, -0.17, 0.45]), 275 | Vector([-0.65, -0.05, 0.6]), 276 | Vector([-0.67, 0.22, 0.7]), 277 | Vector([-0.49, 0.42, 0.6]), 278 | ], 279 | [ 280 | [0, 1, 2, 3], 281 | [0, 3, 4, 5], 282 | [0, 1, 6, 7], 283 | [0, 7, 8, 9], 284 | [0, 9, 10, 11], 285 | [0, 11, 12, 13], 286 | [0, 13, 14, 15], 287 | [0, 15, 16, 17], 288 | [0, 17, 18, 19], 289 | [0, 19, 20, 5], 290 | ], 291 | ), 292 | ( # 2 = orange 293 | [ 294 | Vector([0, 0, 0]), 295 | Vector([-0.055, 0.165, 0.11]), 296 | Vector([-0.125, 0.56, 0.365]), 297 | Vector([0, 0.7, 0.45]), 298 | Vector([0.125, 0.56, 0.365]), 299 | Vector([0.055, 0.165, 0.11]), 300 | Vector([0.14, 0.10, 0.11]), 301 | Vector([0.495, 0.29, 0.365]), 302 | Vector([0.665, 0.215, 0.45]), 303 | Vector([0.57, 0.055, 0.36]), 304 | Vector([0.175, 0, 0.11]), 305 | Vector([0.14, -0.1, 0.11]), 306 | Vector([0.43, -0.38, 0.365]), 307 | Vector([0.41, -0.565, 0.45]), 308 | Vector([0.23, -0.53, 0.365]), 309 | Vector([0.05, -0.165, 0.11]), 310 | Vector([-0.14, -0.1, 0.11]), 311 | Vector([-0.43, -0.38, 0.365]), 312 | Vector([-0.41, -0.565, 0.45]), 313 | Vector([-0.23, -0.53, 0.365]), 314 | Vector([-0.05, -0.165, 0.11]), 315 | Vector([-0.14, 0.10, 0.11]), 316 | Vector([-0.495, 0.29, 0.365]), 317 | Vector([-0.665, 0.215, 0.45]), 318 | Vector([-0.57, 0.055, 0.36]), 319 | Vector([-0.175, 0, 0.11]), 320 | Vector([0.1, -0.1, 0.4]), 321 | Vector([-0.1, -0.1, 0.4]), 322 | Vector([-0.1, 0.1, 0.4]), 323 | Vector([0.1, 0.1, 0.4]), 324 | ], 325 | [ 326 | [0, 1, 2, 3], 327 | [0, 3, 4, 5], 328 | [0, 6, 7, 8], 329 | [0, 8, 9, 10], 330 | [0, 11, 12, 13], 331 | [0, 13, 14, 15], 332 | [0, 16, 17, 18], 333 | [0, 18, 19, 20], 334 | [0, 21, 22, 23], 335 | [0, 23, 24, 25], 336 | [0, 26, 27], 337 | [0, 27, 28], 338 | [0, 28, 29], 339 | [0, 29, 26], 340 | ], 341 | ), 342 | ( # 3 = magnolia 343 | [ 344 | Vector([0, 0, 0]), 345 | Vector([0.19, -0.19, 0.06]), 346 | Vector([0.19, -0.04, 0.06]), 347 | Vector([0.34, -0.11, 0.35]), 348 | Vector([0.3, -0.3, 0.6]), 349 | Vector([0.11, -0.34, 0.35]), 350 | Vector([0.04, -0.19, 0.06]), 351 | Vector([0.19, 0.19, 0.06]), 352 | Vector([0.19, 0.04, 0.06]), 353 | Vector([0.34, 0.11, 0.35]), 354 | Vector([0.3, 0.3, 0.6]), 355 | Vector([0.11, 0.34, 0.35]), 356 | Vector([0.04, 0.19, 0.06]), 357 | Vector([-0.19, -0.19, 0.06]), 358 | Vector([-0.19, -0.04, 0.06]), 359 | Vector([-0.34, -0.11, 0.35]), 360 | Vector([-0.3, -0.3, 0.6]), 361 | Vector([-0.11, -0.34, 0.35]), 362 | Vector([-0.04, -0.19, 0.06]), 363 | Vector([-0.19, 0.19, 0.06]), 364 | Vector([-0.19, 0.04, 0.06]), 365 | Vector([-0.34, 0.11, 0.35]), 366 | Vector([-0.3, 0.3, 0.6]), 367 | Vector([-0.11, 0.34, 0.35]), 368 | Vector([-0.04, 0.19, 0.06]), 369 | Vector([0, -0.39, 0.065]), 370 | Vector([0.15, -0.23, 0.065]), 371 | Vector([0.23, -0.46, 0.39]), 372 | Vector([0, -0.62, 0.65]), 373 | Vector([-0.23, -0.46, 0.39]), 374 | Vector([-0.15, -0.23, 0.065]), 375 | Vector([0, 0.39, 0.065]), 376 | Vector([0.15, 0.23, 0.065]), 377 | Vector([0.23, 0.46, 0.39]), 378 | Vector([0, 0.62, 0.65]), 379 | Vector([-0.23, 0.46, 0.39]), 380 | Vector([-0.15, 0.23, 0.065]), 381 | Vector([-0.39, 0, 0.065]), 382 | Vector([-0.23, 0.15, 0.065]), 383 | Vector([-0.46, 0.23, 0.39]), 384 | Vector([-0.62, 0, 0.65]), 385 | Vector([-0.46, -0.23, 0.39]), 386 | Vector([-0.23, -0.15, 0.065]), 387 | Vector([0.39, 0, 0.065]), 388 | Vector([0.23, 0.15, 0.065]), 389 | Vector([0.46, 0.23, 0.39]), 390 | Vector([0.62, 0, 0.65]), 391 | Vector([0.46, -0.23, 0.39]), 392 | Vector([0.23, -0.15, 0.065]), 393 | ], 394 | [ 395 | [0, 1, 2], 396 | [1, 2, 3], 397 | [1, 3, 4], 398 | [1, 4, 5], 399 | [1, 5, 6], 400 | [1, 6, 0], 401 | [0, 7, 8], 402 | [7, 8, 9], 403 | [7, 9, 10], 404 | [7, 10, 11], 405 | [7, 11, 12], 406 | [7, 12, 0], 407 | [0, 13, 14], 408 | [13, 14, 15], 409 | [13, 15, 16], 410 | [13, 16, 17], 411 | [13, 17, 18], 412 | [13, 18, 0], 413 | [0, 19, 20], 414 | [19, 20, 21], 415 | [19, 21, 22], 416 | [19, 22, 23], 417 | [19, 23, 24], 418 | [19, 24, 0], 419 | [0, 25, 26], 420 | [25, 26, 27], 421 | [25, 27, 28], 422 | [25, 28, 29], 423 | [25, 29, 30], 424 | [25, 30, 0], 425 | [0, 31, 32], 426 | [31, 32, 33], 427 | [32, 33, 34], 428 | [31, 34, 35], 429 | [31, 35, 36], 430 | [31, 36, 0], 431 | [0, 37, 38], 432 | [37, 38, 39], 433 | [37, 39, 40], 434 | [37, 40, 41], 435 | [37, 41, 42], 436 | [37, 42, 0], 437 | [0, 43, 44], 438 | [43, 44, 45], 439 | [43, 45, 46], 440 | [43, 46, 47], 441 | [43, 47, 48], 442 | [43, 48, 0], 443 | ], 444 | ), 445 | ][t] 446 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /gui.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | import traceback 4 | import sys 5 | import importlib 6 | import os 7 | import time 8 | import pprint 9 | import queue 10 | from copy import deepcopy 11 | 12 | from . import parametric, utilities 13 | from .parametric.gen import update_log 14 | from .parametric.tree_params import tree_param 15 | 16 | 17 | main_thread_callback_queue = queue.Queue() 18 | 19 | 20 | def _get_addon_path_details(): 21 | addon_path_parts = __file__.split(os.path.sep)[:-1] 22 | addon_name = addon_path_parts[-1] 23 | addon_path = os.path.sep.join(addon_path_parts) 24 | return addon_path_parts, addon_name, addon_path 25 | 26 | 27 | def _get_tree_types(self=None, context=None): 28 | # Scan the the ch_trees addon folder for parameters and definitions, 29 | # then return two EnumProperty objects for use as the drop-down tree selector 30 | addon_path_parts, addon_name, addon_path = _get_addon_path_details() 31 | module_parts = ['parametric', 'tree_params'] 32 | # Build the drop-down menus 33 | path = os.path.join(addon_path, *module_parts) 34 | files = [f.split('.')[0] for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 35 | files.remove('tree_param') 36 | # ex: ['ch_trees.parametric.tree_params.quaking_aspen', ...] 37 | modules = ['{}.{}.{}'.format(addon_name, '.'.join(module_parts), f) for f in files] 38 | # ex: 'Quaking Aspen' 39 | titles = [f.replace('_', ' ').title() for f in files] 40 | enum_options = [(module, title, title) for module, title in zip(modules, titles)] 41 | return enum_options 42 | 43 | 44 | class TreeGen(bpy.types.Operator): 45 | """Generate a tree""" 46 | 47 | bl_idname = "object.tree_gen" 48 | bl_category = "TreeGen" 49 | bl_label = "Generate Tree" 50 | bl_options = {'REGISTER'} 51 | 52 | # --- 53 | # Note: an empty-string 'name' parameter removes the default label from inputs 54 | 55 | _scene = bpy.types.Scene 56 | _props = bpy.props 57 | 58 | # Drop-down containing tree options 59 | parametric_items = _get_tree_types() 60 | _, addon_name, _ = _get_addon_path_details() 61 | _scene.custom_tree_load_params_input = _props.EnumProperty(name="", 62 | default="{}.parametric.tree_params.quaking_aspen".format(addon_name), 63 | items=parametric_items) 64 | 65 | # Nothing exciting here. Seed and leaf toggle 66 | _scene.seed_input = _props.IntProperty(name="", default=0, min=0, max=9999999) 67 | _scene.last_seed = _props.IntProperty(name="", default=0, min=0, max=9999999) 68 | _scene.generate_leaves_input = _props.BoolProperty(name="Generate Leaves/Blossom", default=True) 69 | 70 | # ====================== 71 | # Tree customizer inputs 72 | 73 | # Tree Shape 74 | tree_shape_options = ( 75 | ('0', 'Conical', 'Conical'), ('1', 'Spherical', 'Spherical'), ('2', 'Hemispherical', 'Hemispherical'), 76 | ('3', 'Cylindrical', 'Cylindrical'), ('4', 'Tapered Cylindrical', 'Tapered Cylindrical'), 77 | ('5', 'Flame', 'Flame'), ('6', 'Inverse Conical', 'Inverse Conical'), ('7', 'Tend Flame', 'Tend Flame'), ('8', 'Custom', 'Custom') 78 | ) 79 | _scene.tree_shape_input = _props.EnumProperty(name="", description="Controls shape of the tree by altering the first level branch length. Custom uses the envelope defined by the pruning parameters to control the tree shape directly rather than through pruning", items=tree_shape_options, default='7') 80 | 81 | _scene.tree_prune_ratio_input = _props.FloatProperty(name="", description="Fractional amount by which the effect of pruning is applied", default=0, min=0, max=1) 82 | _scene.tree_prune_width_input = _props.FloatProperty(name="", description="Width of the pruning envelope as a fraction of its height (the maximum height of the tree)", default=.5, min=.000001, max=200) 83 | _scene.tree_prune_width_peak_input = _props.FloatProperty(name="", description="The fractional distance from the bottom of the pruning up at which the peak width occurs", default=.5, min=0, max=200) 84 | _scene.tree_prune_power_low_input = _props.FloatProperty(name="", description="The curvature of the lower section of the pruning envelope. < 1 results in a convex shape, > 1 in concave", default=.5, min=-200, max=200) # <1 convex, >1 concave 85 | _scene.tree_prune_power_high_input = _props.FloatProperty(name="", description="The curvature of the upper section of the pruning envelope. < 1 results in a convex shape, > 1 in concave", default=.5, min=-200, max=200) # <1 convex, >1 concave 86 | 87 | # Size of base 88 | _scene.tree_base_size_input = _props.FloatVectorProperty(name="", description="Proportion of branch on which no child branches/leaves are spawned", default=(0.3, 0.02, 0.02, 0.02), size=4, min=.001) 89 | 90 | # Base split count 91 | _scene.tree_base_splits_input = _props.IntProperty(name="", description="Number of splits at base height on trunk, if negative then the number of splits will be randomly chosen up to a maximum of |base splits|", default=0, min=-5, max=5) 92 | 93 | # Overall tree scale and scale variation 94 | _scene.tree_g_scale_input = _props.FloatProperty(name="", description="Scale of the entire tree", default=13, min=.000001, max=150) 95 | _scene.tree_g_scale_v_input = _props.FloatProperty(name="", description="Maximum variation in size of the entire tree", default=3, min=0, max=149.99) 96 | 97 | # Level count 98 | _scene.tree_levels_input = _props.IntProperty(name="", description="Number of levels of branching, typically 3 or 4", default=3, min=1, max=4) 99 | 100 | # Ratio and ratio power 101 | _scene.tree_ratio_input = _props.FloatProperty(name="", description="Ratio of the stem length to radius", default=.015, min=.000001, max=1) 102 | _scene.tree_ratio_power_input = _props.FloatProperty(name="", description="How drastically the branch radius is reduced between branching levels", default=1.2, min=0, max=5) 103 | 104 | # Flare 105 | _scene.tree_flare_input = _props.FloatProperty(name="", description="How much the radius at the base of the trunk increases", default=.6, min=0, max=10) 106 | 107 | # Branch appearance 108 | _scene.tree_branches_input = _props.IntVectorProperty(name="", description="The maximum number of child branches at a given level on each parent branch. The first level parameter indicates the number of trunks coming from the floor, positioned in a rough circle facing outwards (see bamboo). If <0 then all branches are placed in a 'fan' at end of the parent branch", default=(1, 50, 30, 1), size=4, min=-500, max=500) 109 | 110 | _scene.tree_length_input = _props.FloatVectorProperty(name="", description="The length of branches at a given level as a fraction of their parent branch’s length", default=(1, 0.3, 0.6, 0), size=4, min=0, max=1) 111 | _scene.tree_length_v_input = _props.FloatVectorProperty(name="", description="Maximum variation in branch length", default=(0, 0, 0, 0), size=4, min=-0, max=1) 112 | 113 | _scene.tree_branch_dist_input = _props.FloatVectorProperty(name="", description="Controls the distribution of branches along their parent stem. 0 indicates fully alternate branching, interpolating to fully opposite branching at 1. Values > 1 indicate whorled branching (as on fir trees) with n + 1 branches in each whorl. Fractional values result in a rounded integer number of branches in each whorl with rounding error distributed along the trunk", default=(0, 0, 0, 0), size=4, min=0, max=1) 114 | 115 | _scene.tree_taper_input = _props.FloatVectorProperty(name="", description="Controls the tapering of the radius of each branch along its length. If < 1 then the branch tapers to that fraction of its base radius at its end, so a value 1 results in conical tapering. If =2 the radius remains uniform until the end of the stem where the branch is rounded off in a hemisphere, fractional values between 1 and 2 interpolate between conical tapering and this rounded end. Values > 2 result in periodic tapering with a maximum variation in radius equal to the value − 2 of the base radius - so a value of 3 results in a series of adjacent spheres (see palm trunk)", default=(1, 1, 1, 1), size=4, min=-0, max=3) 116 | _scene.tree_radius_mod_input = _props.FloatVectorProperty(name="", description="", default=(1, 1, 1, 1), size=4, min=0, max=1) 117 | 118 | _scene.tree_bend_v_input = _props.FloatVectorProperty(name="", description="Maximum angle by which the direction of the branch may change from start to end, rotating about the branch’s local y-axis. Applied randomly at each segment", default=(0, 50, 0, 0), size=4, min=0, max=360) 119 | 120 | _scene.tree_bevel_res_input = _props.IntVectorProperty(name="", description="Resolution of curve bevels", default=(10, 10, 10, 10), size=4, min=1, max=10) 121 | _scene.tree_curve_res_input = _props.IntVectorProperty(name="", description="Number of segments in each branch", default=(5, 5, 3, 1), size=4, min=1, max=10) 122 | _scene.tree_curve_input = _props.FloatVectorProperty(name="", description="Angle by which the direction of the branch will change from start to end, rotating about the branch’s local x-axis", default=(0, -40, -40, 0), size=4, min=-360, max=360) 123 | _scene.tree_curve_v_input = _props.FloatVectorProperty(name="", description="Maximum variation in curve angle of a branch. Applied randomly at each segment", default=(20, 50, 75, 0), size=4, min=-360, max=360) 124 | _scene.tree_curve_back_input = _props.FloatVectorProperty(name="", description="Angle in the opposite direction to the curve that the branch will curve back from half way along, creating S shaped branches", default=(0, 0, 0, 0), size=4, min=-360, max=360) 125 | 126 | _scene.tree_seg_splits_input = _props.FloatVectorProperty(name="", description="Maximum number of dichotomous branches (splits) at each segment of a branch, fractional values are distributed along the branches semi-randomly", default=(0, 0, 0, 0), size=4, min=0, max=2) 127 | _scene.tree_split_angle_input = _props.FloatVectorProperty(name="", description="Angle between dichotomous branches", default=(40, 0, 0, 0), size=4, min=0, max=360) 128 | _scene.tree_split_angle_v_input = _props.FloatVectorProperty(name="", description="Maximum variation in angle between dichotomous branches", default=(5, 0, 0, 0), size=4, min=0, max=360) 129 | 130 | # "the turning of all or part of an organism in a particular direction in response to an external stimulus" 131 | _scene.tree_tropism_input = _props.FloatVectorProperty(name="", description="Influence upon the growth direction of the tree in the x, y and z directions, the z element only applies to branches in the second level and above. Useful for simulating the effects of gravity, sunlight and wind", default=(0, 0, 0.5), size=3, min=-10, max=10) 132 | 133 | _scene.tree_down_angle_input = _props.FloatVectorProperty(name="", description="Controls the angle of the direction of a child branch away from that of its parent", default=(0, 60, 45, 45), size=4, min=0, max=360) 134 | _scene.tree_down_angle_v_input = _props.FloatVectorProperty(name="", description="Maximum variation in down angle, if < 0 then the value of down angle is distributed along the parent stem", default=(0, -50, 10, 10), size=4, min=-360, max=360) 135 | 136 | _scene.tree_rotate_input = _props.FloatVectorProperty(name="", description="Angle around the parent branch between each child branch. If < 0 then child branches are directed this many degrees away from the downward direction in their parent's local basis (see palm leaves). For fanned branches, the fan will spread by this angle and for whorled branches, each whorl will rotate by this angle", default=(0, 140, 140, 77), size=4, min=-360, max=360) 137 | _scene.tree_rotate_v_input = _props.FloatVectorProperty(name="", description="Maximum variation in angle between branches. For fanned and whorled branches, each branch will vary in angle by this much", default=(0, 0, 0, 0), size=4, min=0) 138 | 139 | # ---- 140 | # Cumulative count of leaves and blossoms on each of the deepest level of branches 141 | _scene.tree_leaf_blos_num_input = _props.IntProperty(name="", description="Number of leaves or blossom on each of the deepest level of branches. If <0 then all leaves are placed in a fan the end of the branch", default=40, min=-1000, max=3000) 142 | 143 | # Leaf shape 144 | leaf_shape_options = ( 145 | ('1', 'Ovate', 'Ovate'), ('2', 'Linear', 'Linear'), ('3', 'Cordate', 'Cordate'), ('4', 'Maple', 'Maple'), 146 | ('5', 'Palmate', 'Palmate'), ('6', 'Spiky Oak', 'Spiky Oak'), ('7', 'Rounded Oak', 'Rounded Oak'), 147 | ('8', 'Elliptic', 'Elliptic'), ('9', 'Rectangle', 'Rectangle'), ('10', 'Triangle', 'Triangle') 148 | ) 149 | _scene.tree_leaf_shape_input = _props.EnumProperty(name="", description="Predefined leaf shapes, rectangle is easiest if wishing to use an image texture", items=leaf_shape_options, default='3') 150 | 151 | # Leaf scale 152 | _scene.tree_leaf_scale_input = _props.FloatProperty(name="", description="Overall leaf scale", default=.17, min=.0001, max=1000) 153 | 154 | # Leaf scale in x-direction 155 | _scene.tree_leaf_scale_x_input = _props.FloatProperty(name="", description="Leaf scale in the x-direction (width)", default=1, min=.0001, max=1000) 156 | 157 | # Amount of leaf bend towards sunlight 158 | _scene.tree_leaf_bend_input = _props.FloatProperty(name="", description="Fractional amount by which leaves are reoriented to face the light (upwards and outwards)", default=.6, min=0, max=1) 159 | 160 | # ---- 161 | # Blossom configuration 162 | # _scene.tree_generate_blossoms_input = _props.BoolProperty(name="Generate blossoms", default=False) 163 | 164 | blossom_shape_options = (('1', 'Cherry', 'Cherry'), ('2', 'Orange', 'Orange'), ('3', 'Magnolia', 'Magnolia')) 165 | _scene.tree_blossom_shape_input = _props.EnumProperty(name="", description="Predefined blossom shapes", items=blossom_shape_options, default='1') 166 | 167 | # Blossom scale 168 | _scene.tree_blossom_scale_input = _props.FloatProperty(name="", description="Overall blossom scale", default=0.1, min=.0001, max=1) 169 | 170 | # Rate at which blossoms occur relative to leaves 171 | _scene.tree_blossom_rate_input = _props.FloatProperty(name="", description="Fractional rate at which blossom occurs relative to leaves", default=0, min=0, max=1) 172 | 173 | # Save location for custom tree params 174 | _scene.custom_tree_save_overwrite_input = _props.BoolProperty(name="Overwrite If File Exists", default=False) 175 | tree_save_location = os.path.sep.join((_get_addon_path_details()[2], 'parametric', 'tree_params', 'my_custom_tree.py')) 176 | _scene.custom_tree_save_location_input = _props.StringProperty(name="", default=tree_save_location) 177 | 178 | # ---- 179 | # Utilities 180 | 181 | # Render inputs; auto-fill path input with user's home directory 182 | _scene.render_input = _props.BoolProperty(name="Render After Generation", default=False) 183 | render_output_path = os.path.sep.join((os.path.expanduser('~'), 'treegen_render.png')) 184 | _scene.render_output_path_input = _props.StringProperty(name="", default=render_output_path) 185 | 186 | # Convert selected tree to mesh 187 | _scene.tree_gen_convert_to_mesh_input = _props.BoolProperty(name="Convert to Mesh After Generation", default=False, 188 | description="After generation, automatically convert the branches from a curve to a mesh") 189 | _scene.tree_gen_merge_verts_by_distance = _props.BoolProperty(name="Merge Nearby Vertices", default=False, 190 | description="After mesh conversion, merge nearby vertices together") 191 | 192 | # Create LODs 193 | _scene.tree_gen_create_leaf_lods_input = _props.BoolProperty(name="Create Leaf LODs After Generation", default=False, 194 | description="After generation, create three copies of the leaves of increasing sparsity.") 195 | 196 | # --- 197 | def execute(self, context): 198 | # "Generate Tree" button callback 199 | 200 | # Run the main thread executer modal 201 | bpy.ops.object.treegen_main_thread_executer() 202 | 203 | params = TreeGen.get_params_from_customizer(context) 204 | self._construct(context, params, main_thread_callback_queue) 205 | 206 | return {'FINISHED'} 207 | 208 | # --- 209 | def _construct(self, context, params, callback_queue): 210 | # Thread target that handles most of the addon's operations 211 | 212 | scene = context.scene 213 | update_log('\n** Generating Tree **\n') 214 | 215 | success = False 216 | 217 | try: 218 | # Find the highest valid level 219 | while scene.tree_levels_input > 0: 220 | level_length = scene.tree_length_input[scene.tree_levels_input - 1] 221 | 222 | if float(level_length) == 0.0: 223 | update_log('Hint: tree level ' + str(scene.tree_levels_input) + ' was ignored due to having a length of 0.0\n') 224 | scene.tree_levels_input -= 1 225 | 226 | else: 227 | params['levels'] = scene.tree_levels_input 228 | break 229 | 230 | if scene.tree_levels_input == 0: 231 | update_log('All levels have a length of zero!\n') 232 | return 233 | 234 | start_time = time.time() 235 | tree = parametric.gen.construct(params, scene.seed_input, scene.generate_leaves_input) 236 | for o in context.view_layer.objects: 237 | o.select_set(False) 238 | tree.select_set(True) 239 | context.view_layer.objects.active = tree 240 | 241 | if scene.render_input: 242 | callback_queue.put(bpy.ops.object.tree_gen_render_tree) 243 | 244 | # This task has to be run on the main thread, so it gets queued instead of called 245 | if scene.tree_gen_create_leaf_lods_input: 246 | callback_queue.put(bpy.ops.object.tree_gen_create_leaf_lods) 247 | 248 | # Tree is converted to mesh via LOD generation, so this needs to be secondary 249 | if scene.tree_gen_convert_to_mesh_input: 250 | callback_queue.put(bpy.ops.object.tree_gen_convert_to_mesh) 251 | 252 | success = True 253 | 254 | # Reduce chance of Blender crashing when generation fails or the user does something ill-advised 255 | except Exception: 256 | update_log('\n{}\n'.format(traceback.format_exc())) 257 | update_log('Tree generation failed\n\n') 258 | 259 | if success: 260 | update_log('\nTree generated in {:.6f} seconds\n\n'.format(time.time() - start_time)) 261 | 262 | callback_queue.put('KILL') # Kill modal used for running tasks in main thread 263 | 264 | # ---- 265 | @staticmethod 266 | def get_params_from_customizer(context): 267 | scene = context.scene 268 | 269 | param_names = ['shape', 'g_scale', 'g_scale_v', 'levels', 'ratio', 'flare', 'ratio_power', 270 | 'base_size', 'down_angle', 'down_angle_v', 'rotate', 'rotate_v', 'branches', 271 | 'length', 'length_v', 'taper', 'seg_splits', 'split_angle', 'split_angle_v', 'bevel_res', 272 | 'curve_res', 'curve', 'curve_back', 'curve_v', 'bend_v', 'branch_dist', 'radius_mod', 273 | 'leaf_blos_num', 'leaf_shape', 'leaf_scale', 'leaf_scale_x', 'leaf_bend', 'blossom_shape', 274 | 'blossom_scale', 'blossom_rate', 'tropism', 'prune_ratio', 'prune_width', 'prune_width_peak', 275 | 'prune_power_low', 'prune_power_high', 'base_splits'] 276 | 277 | params = {} 278 | for name in param_names: 279 | try: 280 | p = getattr(scene, 'tree_{}_input'.format(name)) 281 | if str(type(p)) == "": 282 | p = list(p) 283 | if p is not None: 284 | params[name] = deepcopy(p) 285 | else: 286 | print('Error while parsing input: {} = {}'.format(name, p)) 287 | except AttributeError: 288 | pass # Skip missing attributes, reverting to default 289 | 290 | return params 291 | 292 | 293 | class TreeGenRender(bpy.types.Operator): 294 | """Create a render of the selected tree""" 295 | 296 | bl_idname = "object.tree_gen_render_tree" 297 | bl_category = "TreeGen" 298 | bl_label = "Render Tree" 299 | bl_options = {'REGISTER', 'UNDO'} 300 | 301 | def execute(self, context): 302 | utilities.render_tree(context.scene.render_output_path_input) 303 | return {'FINISHED'} 304 | 305 | 306 | class TreeGenConvertToMesh(bpy.types.Operator): 307 | """Convert the selected tree's branches curve to mesh""" 308 | 309 | bl_idname = "object.tree_gen_convert_to_mesh" 310 | bl_category = "TreeGen" 311 | bl_label = "Convert To Mesh" 312 | bl_options = {'REGISTER', 'UNDO'} 313 | 314 | def execute(self, context): 315 | from . import utilities 316 | 317 | # update_log doesn't get a chance to print before Blender locks up, so a direct print is necessary 318 | sys.stdout.write('\nConverting tree to mesh. Blender will appear to crash; be patient.\n') 319 | sys.stdout.flush() 320 | 321 | # Catch exceptions and print them as strings 322 | # This will hopefully reduce random crashes 323 | try: 324 | utilities.convert_to_mesh(context) 325 | update_log('Conversion to mesh complete\n') 326 | 327 | except Exception: 328 | update_log('\n{}\n'.format(traceback.format_exc())) 329 | update_log('Conversion to mesh failed\n') 330 | 331 | return {'FINISHED'} 332 | 333 | 334 | class TreeGenCreateLeafLODs(bpy.types.Operator): 335 | """Generate 3 leaf LODs for the selected tree""" 336 | 337 | bl_idname = "object.tree_gen_create_leaf_lods" 338 | bl_category = "TreeGen" 339 | bl_label = "Create LODs" 340 | bl_options = {'REGISTER', 'UNDO'} 341 | 342 | def execute(self, context): 343 | from . import utilities 344 | 345 | # update_log doesn't get a chance to print before Blender locks up, so a direct print is necessary 346 | sys.stdout.write('\nCreating leaf LODs. Blender will appear to crash; be patient.\n') 347 | sys.stdout.flush() 348 | 349 | # Catch exceptions and print them as strings 350 | # This will hopefully reduce random crashes 351 | try: 352 | utilities.generate_leaf_lods(context, 3) 353 | update_log('Leaf LOD creation complete\n\n') 354 | 355 | except Exception: 356 | update_log('\n{}\n'.format(traceback.format_exc())) 357 | update_log('Leaf LOD creation failed\n\n') 358 | 359 | return {'FINISHED'} 360 | 361 | 362 | class TreeGenSaveFile(bpy.types.Operator): 363 | """Save custom tree parameters""" 364 | 365 | bl_idname = "object.tree_gen_custom_save" 366 | bl_category = "TreeGen" 367 | bl_label = "Save Custom Tree" 368 | bl_options = {'REGISTER', 'UNDO'} 369 | 370 | def execute(self, context): 371 | save_location = context.scene.custom_tree_save_location_input 372 | params = TreeGen.get_params_from_customizer(context) 373 | 374 | if not context.scene.custom_tree_save_overwrite_input: 375 | counter = 0 376 | save_location_no_ext = save_location[:-3] 377 | while os.path.isfile(save_location): 378 | save_location = '{}_{}.py'.format(save_location_no_ext, counter) 379 | counter += 1 380 | 381 | with open(save_location, 'w') as output_file: 382 | print('params = ' + pprint.pformat(params), file=output_file) 383 | 384 | parametric_items = _get_tree_types() 385 | bpy.types.Scene.custom_tree_load_params_input = bpy.props.EnumProperty(name="", items=parametric_items) 386 | 387 | return {'FINISHED'} 388 | 389 | 390 | class TreeGenLoadParams(bpy.types.Operator): 391 | """Load custom tree parameters""" 392 | 393 | bl_idname = "object.tree_gen_custom_load" 394 | bl_category = "TreeGen" 395 | bl_label = "Load Tree Parameters" 396 | bl_options = {'REGISTER', 'UNDO'} 397 | 398 | def execute(self, context): 399 | mod_name = context.scene.custom_tree_load_params_input 400 | 401 | # Delete old module if it exists, forcing Python to load the new file 402 | if mod_name in sys.modules: 403 | del sys.modules[mod_name] 404 | 405 | importlib.invalidate_caches() # Make sure Python doesn't import from __pycache__ 406 | mod = importlib.import_module(mod_name) 407 | 408 | params = tree_param.TreeParam(mod.params).params 409 | 410 | scene = context.scene 411 | for name, value in params.items(): 412 | if name in ['leaf_shape', 'shape', 'blossom_shape']: 413 | if value == 0 and name == 'leaf_shape': 414 | value = 8 # default 415 | value = str(value) 416 | try: 417 | setattr(scene, 'tree_{}_input'.format(name), value) 418 | except TypeError as ex: 419 | exception = str(ex).replace('TypeError: bpy_struct: item.attr = val: ', '') 420 | print('TreeGen :: Error while loading preset "{}": {}'.format(name, exception)) 421 | 422 | # Pre-fill render output path with relevant name 423 | scene.render_output_path_input = os.path.sep.join((_get_addon_path_details()[2], 'parametric', 'tree_params', mod_name.split('.')[-1].replace('.py', '') + '_render.png')) 424 | 425 | return {'FINISHED'} 426 | 427 | 428 | class TreeGenMainThreadExecuter(bpy.types.Operator): 429 | # Internal utility that handles executing tasks on the main thread. 430 | # Necessary for LOD creation 431 | 432 | bl_idname = 'object.treegen_main_thread_executer' 433 | bl_label = 'TreeGen internal executer utility' 434 | bl_options = {'REGISTER', 'UNDO'} 435 | 436 | _updating = False 437 | _calcs_done = False 438 | _timer = None 439 | 440 | def run_tasks(self): 441 | try: 442 | queue_item = main_thread_callback_queue.get(False) 443 | 444 | if type(queue_item) == str and queue_item == 'KILL': 445 | self._calcs_done = True 446 | else: 447 | queue_item() 448 | 449 | except queue.Empty: 450 | pass 451 | 452 | def modal(self, context, event): 453 | if event.type == 'TIMER' and not self._updating: 454 | self._updating = True 455 | self.run_tasks() 456 | self._updating = False 457 | 458 | if self._calcs_done: 459 | self.cancel(context) 460 | return {'CANCELLED'} 461 | 462 | return {'PASS_THROUGH'} 463 | 464 | def execute(self, context): 465 | context.window_manager.modal_handler_add(self) 466 | self._updating = False 467 | self._timer = context.window_manager.event_timer_add(0.5, window=context.window) 468 | 469 | return {'RUNNING_MODAL'} 470 | 471 | def cancel(self, context): 472 | # If timer is None, we're already canceling 473 | if self._timer is not None: 474 | context.window_manager.event_timer_remove(self._timer) 475 | self._timer = None 476 | 477 | return None # Appease Blender gods 478 | 479 | 480 | class TreeGenCustomisePanel(bpy.types.Panel): 481 | """Provides the main user interface for TreeGen""" 482 | 483 | bl_label = "TreeGen Customisation" 484 | bl_idname = "OBJECT_PT_treegen_c" 485 | bl_space_type = 'VIEW_3D' 486 | bl_region_type = 'UI' 487 | bl_category = 'TreeGen' 488 | bl_context = "objectmode" 489 | bl_options = {'DEFAULT_CLOSED'} 490 | 491 | def draw(self, context): 492 | layout = self.layout 493 | scene = context.scene 494 | 495 | def label_row(label, prop, checkbox=False, dropdown=False, container=None): 496 | # Helper method to shorten the UI code 497 | if container is None: 498 | container = layout 499 | if dropdown: 500 | col = container.column() 501 | cont = col.split(factor=0.5, align=True) 502 | cont.label(text=label + ':') 503 | else: 504 | cont = container.row() 505 | 506 | if checkbox or dropdown: 507 | cont.prop(scene, prop) 508 | else: 509 | cont.prop(scene, prop, text=label) 510 | 511 | row = layout.row() 512 | row.label(text="Leaf Parameters:") 513 | box = layout.box() 514 | box.row() 515 | label_row('', 'generate_leaves_input', checkbox=True, container=box) 516 | if scene.generate_leaves_input: 517 | label_row('Leaf Shape', 'tree_leaf_shape_input', dropdown=True, container=box) 518 | label_row('Leaf Count', 'tree_leaf_blos_num_input', container=box) 519 | label_row('Leaf Scale', 'tree_leaf_scale_input', container=box) 520 | label_row('Leaf Width', 'tree_leaf_scale_x_input', container=box) 521 | label_row('Leaf Bend', 'tree_leaf_bend_input', container=box) 522 | box.separator() 523 | label_row('Blossom Shape', 'tree_blossom_shape_input', dropdown=True, container=box) 524 | label_row('Blossom Rate', 'tree_blossom_rate_input', container=box) 525 | label_row('Blossom Scale', 'tree_blossom_scale_input', container=box) 526 | box.row() 527 | 528 | layout.separator() 529 | row = layout.row() 530 | row.label(text="Tree Parameters:") 531 | box = layout.box() 532 | box.row() 533 | label_row('Tree Shape', 'tree_shape_input', dropdown=True, container=box) 534 | box.separator() 535 | label_row('Level Count', 'tree_levels_input', container=box) 536 | box.separator() 537 | label_row('Prune Ratio', 'tree_prune_ratio_input', container=box) 538 | label_row('Prune Width', 'tree_prune_width_input', container=box) 539 | label_row('Prune Width Peak', 'tree_prune_width_peak_input', container=box) 540 | label_row('Prune Power (low)', 'tree_prune_power_low_input', container=box) 541 | label_row('Prune Power (high)', 'tree_prune_power_high_input', container=box) 542 | box.separator() 543 | label_row('Trunk Splits', 'tree_base_splits_input', container=box) 544 | label_row('Trunk Flare', 'tree_flare_input', container=box) 545 | box.separator() 546 | label_row('Height', 'tree_g_scale_input', container=box) 547 | label_row('Height Variation', 'tree_g_scale_v_input', container=box) 548 | box.separator() 549 | label_row('Tropism', 'tree_tropism_input', container=box) 550 | box.separator() 551 | label_row('Branch Thickness Ratio', 'tree_ratio_input', container=box) 552 | label_row('Branch Thickness Ratio Power', 'tree_ratio_power_input', container=box) 553 | box.row() 554 | 555 | layout.separator() 556 | row = layout.row() 557 | row.label(text="Branch Parameters:") 558 | box = layout.box() 559 | box.row() 560 | box.label(text="Number") 561 | label_row('', 'tree_branches_input', container=box) 562 | box.label(text="Length") 563 | label_row('', 'tree_length_input', container=box) 564 | box.label(text="Length Variation") 565 | label_row('', 'tree_length_v_input', container=box) 566 | box.label(text="Base Size") 567 | label_row('', 'tree_base_size_input', container=box) 568 | box.label(text="Distribution") 569 | label_row('', 'tree_branch_dist_input', container=box) 570 | box.label(text="Taper") 571 | label_row('', 'tree_taper_input', container=box) 572 | box.label(text="Radius Modifier") 573 | label_row('', 'tree_radius_mod_input', container=box) 574 | box.separator() 575 | box.label(text="Curve Bevel Resolution") 576 | label_row('', 'tree_bevel_res_input', container=box) 577 | box.label(text="Curve Resolution") 578 | label_row('', 'tree_curve_res_input', container=box) 579 | box.label(text="Curve") 580 | label_row('', 'tree_curve_input', container=box) 581 | box.label(text="Curve Variation") 582 | label_row('', 'tree_curve_v_input', container=box) 583 | box.label(text="Curve Back") 584 | label_row('', 'tree_curve_back_input', container=box) 585 | box.separator() 586 | box.label(text="Segment Splits") 587 | label_row('', 'tree_seg_splits_input', container=box) 588 | box.label(text="Split Angle") 589 | label_row('', 'tree_split_angle_input', container=box) 590 | box.label(text="Split Angle Variation") 591 | label_row('', 'tree_split_angle_v_input', container=box) 592 | box.separator() 593 | box.label(text="Bend Variation") 594 | label_row('', 'tree_bend_v_input', container=box) 595 | box.separator() 596 | box.label(text="Down Angle") 597 | label_row('', 'tree_down_angle_input', container=box) 598 | box.label(text="Down Angle Variation") 599 | label_row('', 'tree_down_angle_v_input', container=box) 600 | box.separator() 601 | box.label(text="Rotation") 602 | label_row('', 'tree_rotate_input', container=box) 603 | box.label(text="Rotation Variation") 604 | label_row('', 'tree_rotate_v_input', container=box) 605 | box.row() 606 | 607 | layout.separator() 608 | box = layout.box() 609 | box.row() 610 | label_row('Save Location', 'custom_tree_save_location_input', container=box) 611 | label_row('Overwrite If File Exists', 'custom_tree_save_overwrite_input', checkbox=True, container=box) 612 | box.row() 613 | box.operator(TreeGenSaveFile.bl_idname) 614 | box.row() 615 | 616 | 617 | class TreeGenPanel(bpy.types.Panel): 618 | """Provides the main user interface for TreeGen""" 619 | 620 | bl_label = "TreeGen" 621 | bl_idname = "OBJECT_PT_treegen" 622 | bl_space_type = 'VIEW_3D' 623 | bl_region_type = 'UI' 624 | bl_category = 'TreeGen' 625 | bl_context = "objectmode" 626 | 627 | def draw(self, context): 628 | layout = self.layout 629 | scene = context.scene 630 | 631 | def label_row(label, prop, checkbox=False, dropdown=False, container=None): 632 | # Helper method to shorten the UI code 633 | 634 | if container is None: 635 | container = layout 636 | 637 | if dropdown: 638 | col = container.column() 639 | cont = col.split(factor=0.5, align=True) 640 | cont.label(text=label) 641 | else: 642 | cont = container.row() 643 | 644 | if checkbox or dropdown: 645 | cont.prop(scene, prop) 646 | else: 647 | cont.prop(scene, prop, text=label) 648 | 649 | box = layout.box() 650 | box.row() 651 | label_row('Load from file', 'custom_tree_load_params_input', container=box) 652 | box.row() 653 | box.operator(TreeGenLoadParams.bl_idname) 654 | box.row() 655 | 656 | layout.separator() 657 | 658 | box = layout.box() 659 | box.row() 660 | label_row('Seed', 'seed_input', container=box) 661 | row = box.row() 662 | if scene.seed_input == 0: 663 | if scene.last_seed != 0: 664 | row.label(text='Last seed: ' + str(scene.last_seed)) 665 | box.row() 666 | else: 667 | row.label(text='0 = random') 668 | box.row() 669 | box.operator(TreeGen.bl_idname) 670 | box.row() 671 | 672 | layout.separator() 673 | 674 | 675 | class TreeGenUtilitiesPanel(bpy.types.Panel): 676 | """Provides interface for TreeGen-related utilities""" 677 | 678 | bl_label = "TreeGen Utilities" 679 | bl_idname = "OBJECT_PT_treegen_utilities" 680 | bl_space_type = 'VIEW_3D' 681 | bl_region_type = 'UI' 682 | bl_category = 'TreeGen' 683 | bl_context = "objectmode" 684 | bl_options = {'DEFAULT_CLOSED'} 685 | 686 | def draw(self, context): 687 | layout = self.layout 688 | scene = context.scene 689 | 690 | def label_row(label, prop, checkbox=False, dropdown=False, container=None): 691 | # Helper method to shorten the UI code 692 | 693 | if container is None: 694 | container = layout 695 | 696 | if dropdown: 697 | col = container.column() 698 | cont = col.split(factor=0.5, align=True) 699 | cont.label(text=label) 700 | else: 701 | cont = container.row() 702 | 703 | if checkbox or dropdown: 704 | cont.prop(scene, prop) 705 | else: 706 | cont.prop(scene, prop, text=label) 707 | 708 | box = layout.box() 709 | box.row() 710 | label_row('', 'render_input', checkbox=True, container=box) 711 | label_row('Filepath', 'render_output_path_input', container=box) 712 | box.row() 713 | box.operator(TreeGenRender.bl_idname) 714 | box.row() 715 | 716 | layout.separator() 717 | 718 | box = layout.box() 719 | box.row() 720 | label_row('', 'tree_gen_convert_to_mesh_input', checkbox=True, container=box) 721 | label_row('', 'tree_gen_merge_verts_by_distance', checkbox=True, container=box) 722 | box.row() 723 | box.operator(TreeGenConvertToMesh.bl_idname) 724 | box.row() 725 | 726 | layout.separator() 727 | 728 | box = layout.box() 729 | box.row() 730 | label_row('', 'tree_gen_create_leaf_lods_input', checkbox=True, container=box) 731 | box.row() 732 | box.operator(TreeGenCreateLeafLODs.bl_idname) 733 | box.row() 734 | 735 | layout.separator() 736 | -------------------------------------------------------------------------------- /parametric/gen.py: -------------------------------------------------------------------------------- 1 | """ Parametric tree generation system for Blender based on the paper by Weber and Penn """ 2 | 3 | # standard imports 4 | from collections import namedtuple 5 | from copy import copy 6 | from math import ceil, sqrt, degrees, radians, tan, sin, cos, pow, pi 7 | import time 8 | 9 | # Import random functions into a closer namespace to alleviate some lookup costs 10 | import random 11 | from random import random as random_random 12 | from random import getstate as random_getstate 13 | from random import setstate as random_setstate 14 | from random import uniform as random_uniform 15 | 16 | # blender imports 17 | import bpy 18 | from enum import Enum 19 | from mathutils import Quaternion 20 | 21 | from .. import utilities 22 | from ..chturtle import Vector, CHTurtle 23 | from ..leaf import Leaf 24 | from .tree_params.tree_param import TreeParam 25 | 26 | __console_logging__ = True 27 | 28 | # ----- GENERAL FUNCTIONS ----- # 29 | 30 | update_log = utilities.get_logger(__console_logging__) 31 | 32 | 33 | def rand_in_range(lower, upper): 34 | """Generate random number between lower and upper""" 35 | 36 | return (random_random() * (upper - lower)) + lower 37 | 38 | 39 | def calc_point_on_bezier(offset, start_point, end_point): 40 | """Evaluate Bezier curve at offset between bezier_spline_points start_point and end_point""" 41 | if offset < 0 or offset > 1: 42 | raise Exception('Offset out of range: %s not between 0 and 1' % offset) 43 | 44 | one_minus_offset = 1 - offset 45 | 46 | res = one_minus_offset ** 3 * start_point.co + 3 * one_minus_offset ** 2 * offset * start_point.handle_right + 3 *\ 47 | one_minus_offset * offset ** 2 * end_point.handle_left + offset ** 3 * end_point.co 48 | 49 | # initialize new vector to add subclassed methods 50 | return Vector(res) 51 | 52 | 53 | def calc_tangent_to_bezier(offset, start_point, end_point): 54 | """Calculate tangent to Bezier curve at offset between bezier_spline_points start_point and end_point""" 55 | if offset < 0 or offset > 1: 56 | raise Exception('Offset out of range: %s not between 0 and 1' % offset) 57 | 58 | one_minus_offset = 1 - offset 59 | 60 | start_handle_right = start_point.handle_right 61 | end_handle_left = end_point.handle_left 62 | 63 | res = 3 * one_minus_offset ** 2 * (start_handle_right - start_point.co) + 6 * one_minus_offset * offset *\ 64 | (end_handle_left - start_handle_right) + 3 * offset ** 2 * (end_point.co - end_handle_left) 65 | 66 | # initialize new vector to add subclassed methods 67 | return Vector(res) 68 | 69 | 70 | def calc_helix_points(turtle, rad, pitch): 71 | """ calculates required points to produce helix bezier curve with given radius and pitch in direction of turtle""" 72 | # alpha = radians(90) 73 | # pit = pitch/(2*pi) 74 | # a_x = rad*cos(alpha) 75 | # a_y = rad*sin(alpha) 76 | # a = pit*alpha*(rad - a_x)*(3*rad - a_x)/(a_y*(4*rad - a_x)*tan(alpha)) 77 | # b_0 = Vector([a_x, -a_y, -alpha*pit]) 78 | # b_1 = Vector([(4*rad - a_x)/3, -(rad - a_x)*(3*rad - a_x)/(3*a_y), -a]) 79 | # b_2 = Vector([(4*rad - a_x)/3, (rad - a_x)*(3*rad - a_x)/(3*a_y), a]) 80 | # b_3 = Vector([a_x, a_y, alpha*pit]) 81 | # axis = Vector([0, 0, 1]) 82 | 83 | # simplifies greatly for case inc_angle = 90 84 | points = [Vector([0, -rad, -pitch / 4]), 85 | Vector([(4 * rad) / 3, -rad, 0]), 86 | Vector([(4 * rad) / 3, rad, 0]), 87 | Vector([0, rad, pitch / 4])] 88 | 89 | # align helix points to turtle direction and randomize rotation around axis 90 | trf = turtle.dir.to_track_quat('Z', 'Y') 91 | spin_ang = rand_in_range(0, 2 * pi) 92 | rot_quat = Quaternion(Vector([0, 0, 1]), spin_ang) 93 | 94 | for p in points: 95 | p.rotate(rot_quat) 96 | p.rotate(trf) 97 | 98 | return points[1] - points[0], points[2] - points[0], points[3] - points[0], turtle.dir.copy() 99 | 100 | 101 | def point_in_cube(point): 102 | size = 2 103 | return abs(point.x) < size and abs(point.y) < size and abs(point.z - size) < size 104 | 105 | 106 | # ----- MAIN CLASSES ----- # 107 | 108 | class BranchMode(Enum): 109 | """Enum to refer to branching modes""" 110 | alt_opp = 1 111 | whorled = 2 112 | fan = 3 113 | 114 | 115 | class Stem(object): 116 | """Class to store data for each stem (branch) in the system, primarily to 117 | be accessed by its children in calculating their own parameters""" 118 | 119 | __slots__ = ( 120 | 'depth', 'curve', 'parent', 'offset', 'radius_limit', 'children', 'length', 'radius', 121 | 'length_child_max' 122 | ) 123 | 124 | def __init__(self, depth, curve, parent=None, offset=0, radius_limit=-1): 125 | """Init with at depth with curve, possibly parent and offset (for depth > 0)""" 126 | 127 | self.depth = depth 128 | self.curve = curve 129 | self.parent = parent 130 | self.offset = offset 131 | self.radius_limit = radius_limit 132 | 133 | self.children = [] 134 | self.length = 0 135 | self.radius = 0 136 | self.length_child_max = 0 137 | 138 | def copy(self): 139 | """Copy method for stems""" 140 | new_stem = Stem(self.depth, self.curve, self.parent, self.offset, self.radius_limit) 141 | new_stem.length = self.length 142 | new_stem.radius = self.radius 143 | new_stem.length_child_max = self.length_child_max 144 | return new_stem 145 | 146 | def __str__(self): 147 | return '%s %s %s' % (self.length, self.offset, self.radius) 148 | 149 | 150 | class Tree(object): 151 | """Class to store data for the tree""" 152 | 153 | __slots__ = ( 154 | 'param', 'generate_leaves', 'leaves_array', 'stem_index', 'tree_scale', 'branch_curves', 155 | 'base_length', 'split_num_error', 'tree_obj', 'trunk_length' 156 | ) 157 | 158 | def __init__(self, param, generate_leaves=True): 159 | """initialize tree with specified parameters""" 160 | 161 | self.param = param 162 | self.generate_leaves = generate_leaves 163 | self.leaves_array = [] 164 | 165 | self.stem_index = 0 166 | self.tree_scale = 0 167 | self.branch_curves = [] 168 | self.base_length = 0 169 | self.split_num_error = [0, 0, 0, 0, 0, 0, 0] 170 | self.tree_obj = None 171 | self.trunk_length = 0 172 | 173 | # Disable leaf generation 174 | if not generate_leaves: 175 | self.param.leaf_blos_num = 0 176 | 177 | def make(self): 178 | """make the tree""" 179 | 180 | # create parent object 181 | self.tree_obj = bpy.data.objects.new('Tree', None) 182 | bpy.context.collection.objects.link(self.tree_obj) 183 | bpy.context.view_layer.objects.active = self.tree_obj 184 | 185 | # create branches 186 | self.create_branches() 187 | 188 | # Create leaf mesh if needed and enabled 189 | if self.generate_leaves: 190 | self.create_leaf_mesh() 191 | 192 | def points_for_floor_split(self): 193 | """Calculate Poissonly distributed points for stem start points""" 194 | array = [] 195 | 196 | # calculate approx spacing radius for dummy stem 197 | self.tree_scale = self.param.g_scale + self.param.g_scale_v 198 | stem = Stem(0, None) 199 | stem.length = self.calc_stem_length(stem) 200 | rad = 2.5 * self.calc_stem_radius(stem) 201 | 202 | # generate points 203 | for _ in range(self.param.branches[0]): 204 | point_ok = False 205 | while not point_ok: 206 | # distance from center proportional for number of splits, tree scale and stem radius 207 | dis = sqrt(random_random() * self.param.branches[0] / 2.5 * self.param.g_scale * self.param.ratio) 208 | # angle random in circle 209 | theta = rand_in_range(0, 2 * pi) 210 | pos = Vector([dis * cos(theta), dis * sin(theta), 0]) 211 | # test point against those already in array to ensure it will not intersect 212 | point_m_ok = True 213 | for point in array: 214 | if (point[0] - pos).magnitude < rad: 215 | point_m_ok = False 216 | break 217 | if point_m_ok: 218 | point_ok = True 219 | array.append((pos, theta)) 220 | return array 221 | 222 | def create_branches(self): 223 | """Create branches for tree""" 224 | 225 | update_log('\nMaking Stems\n') 226 | start_time = time.time() 227 | 228 | # Set up container objects and curves for each level 229 | for level_depth, level_name in enumerate(['Trunk'] + ['Branches' + str(_) for _ in range(1, self.param.levels)]): 230 | level_curve = bpy.data.curves.new(level_name.lower(), type='CURVE') 231 | level_curve.dimensions = '3D' 232 | level_curve.resolution_u = self.param.curve_res[level_depth] 233 | level_curve.fill_mode = 'FULL' 234 | level_curve.bevel_depth = 1 235 | level_curve.bevel_resolution = self.param.bevel_res[level_depth] 236 | 237 | # Removed in Blender 2.82+ 238 | if hasattr(level_curve, 'use_uv_as_generated'): 239 | level_curve.use_uv_as_generated = True 240 | 241 | level_obj = bpy.data.objects.new(level_name, level_curve) 242 | bpy.context.collection.objects.link(level_obj) 243 | level_obj.parent = self.tree_obj 244 | 245 | self.branch_curves.append(level_curve) 246 | 247 | # actually make the branches 248 | if self.param.branches[0] > 0: 249 | points = self.points_for_floor_split() 250 | 251 | for ind in range(self.param.branches[0]): 252 | self.tree_scale = self.param.g_scale + random_uniform(-1, 1) * self.param.g_scale_v 253 | turtle = CHTurtle() 254 | turtle.pos = Vector([0, 0, 0]) 255 | turtle.dir = Vector([0, 0, 1]) 256 | turtle.right = Vector([1, 0, 0]) 257 | 258 | if self.param.branches[0] > 1: 259 | # position randomly at base and rotate to face out 260 | point = points[ind] 261 | turtle.roll_right(degrees(point[1] - 90)) 262 | turtle.pos = point[0] 263 | else: 264 | # start at random rotation 265 | turtle.roll_right(rand_in_range(0, 360)) 266 | 267 | trunk = self.branch_curves[0].splines.new('BEZIER') 268 | trunk.radius_interpolation = 'CARDINAL' 269 | trunk.resolution_u = self.param.curve_res[0] 270 | 271 | self.make_stem(turtle, Stem(0, trunk)) 272 | 273 | b_time = time.time() - start_time 274 | update_log('\nStems made: %i in %f seconds\n' % (self.stem_index, b_time)) 275 | 276 | curve_points = 0 277 | for branch_level in self.branch_curves: 278 | for spline in branch_level.splines: 279 | curve_points += len(spline.bezier_points) 280 | 281 | update_log('Curve points: %i\n' % curve_points) 282 | 283 | return b_time 284 | 285 | def create_leaf_mesh(self): 286 | """Create leaf mesh for tree""" 287 | 288 | if len(self.leaves_array) <= 0: 289 | return 290 | 291 | update_log('\nMaking Leaves\n') 292 | start_time = time.time() 293 | 294 | # Start loading spinner 295 | windman = bpy.context.window_manager 296 | windman.progress_begin(0, len(self.leaves_array)) 297 | 298 | # go through global leaf array populated in branch making phase and add polygons to mesh 299 | base_leaf_shape = Leaf.get_shape(self.param.leaf_shape, self.tree_scale / self.param.g_scale, 300 | self.param.leaf_scale, self.param.leaf_scale_x) 301 | 302 | base_blossom_shape = Leaf.get_shape(-self.param.blossom_shape, self.tree_scale / self.param.g_scale, 303 | self.param.blossom_scale, 1) 304 | leaf_verts = [] 305 | leaf_faces = [] 306 | leaf_index = 0 307 | blossom_verts = [] 308 | blossom_faces = [] 309 | blossom_index = 0 310 | 311 | counter = 0 312 | for leaf in self.leaves_array: 313 | # Update loading spinner periodically 314 | if counter % 500 == 0: 315 | windman.progress_update(counter / 100) 316 | update_log('\r-> {} leaves made, {} blossoms made'.format(leaf_index, blossom_index)) 317 | if self.param.blossom_rate and random_random() < self.param.blossom_rate: 318 | verts, faces = leaf.get_mesh(self.param.leaf_bend, base_blossom_shape, blossom_index) 319 | blossom_verts.extend(verts) 320 | blossom_faces.extend(faces) 321 | blossom_index += 1 322 | else: 323 | verts, faces = leaf.get_mesh(self.param.leaf_bend, base_leaf_shape, leaf_index) 324 | leaf_verts.extend(verts) 325 | leaf_faces.extend(faces) 326 | leaf_index += 1 327 | counter += 1 328 | 329 | # set up mesh object 330 | if leaf_index > 0: 331 | leaves = bpy.data.meshes.new('leaves') 332 | leaves_obj = bpy.data.objects.new('Leaves', leaves) 333 | bpy.context.collection.objects.link(leaves_obj) 334 | leaves_obj.parent = self.tree_obj 335 | leaves.from_pydata(leaf_verts, (), leaf_faces) 336 | # set up UVs for leaf polygons 337 | leaf_uv = base_leaf_shape[2] 338 | 339 | if leaf_uv: 340 | leaves.uv_layers.new(name="leavesUV") 341 | uv_layer = leaves.uv_layers.active.data 342 | 343 | for seg_ind in range(int(len(leaf_faces) / len(base_leaf_shape[1]))): 344 | vert_ind = 0 345 | for vert in leaf_uv: 346 | uv_layer[seg_ind * len(leaf_uv) + vert_ind].uv = vert 347 | vert_ind += 1 348 | # leaves.validate() 349 | 350 | if blossom_index > 0: 351 | blossom = bpy.data.meshes.new('blossom') 352 | blossom_obj = bpy.data.objects.new('Blossom', blossom) 353 | bpy.context.collection.objects.link(blossom_obj) 354 | blossom_obj.parent = self.tree_obj 355 | blossom.from_pydata(blossom_verts, (), blossom_faces) 356 | # blossom.validate() 357 | 358 | l_time = time.time() - start_time 359 | update_log('\nMade %i leaves and %i blossoms in %f seconds\n' % (leaf_index, blossom_index, l_time)) 360 | windman.progress_end() 361 | 362 | def make_leaf(self, leaf, base_leaf_shape, index, verts_array, faces_array): 363 | """get vertices and faces for leaf and append to appropriate arrays""" 364 | verts, faces = leaf.get_mesh(self.param.leaf_bend, base_leaf_shape, index) 365 | verts_array.extend(verts) 366 | faces_array.extend(faces) 367 | 368 | def make_stem(self, turtle, stem, start=0, split_corr_angle=0, num_branches_factor=1, clone_prob=1, 369 | pos_corr_turtle=None, cloned_turtle=None): 370 | """Generate stem given parameters, as well as all children (branches, splits and leaves) via 371 | recursion""" 372 | 373 | # if the stem is so thin as to be invisible then don't bother to make it 374 | if 0 <= stem.radius_limit < 0.0001: 375 | return 376 | 377 | if self.stem_index % 100 == 0: 378 | update_log('\r-> {} stems made'.format(self.stem_index)) 379 | 380 | # use level 3 parameters for any depth greater than this 381 | depth = stem.depth 382 | d_plus_1 = depth + 1 383 | if d_plus_1 > 3: 384 | d_plus_1 = 3 385 | 386 | # calc length and radius for this stem (only applies for non clones) 387 | if start == 0: 388 | stem.length_child_max = self.param.length[d_plus_1] + random_uniform(-1, 1) * self.param.length_v[d_plus_1] 389 | stem.length = self.calc_stem_length(stem) 390 | stem.radius = self.calc_stem_radius(stem) 391 | if depth == 0: 392 | self.base_length = stem.length * self.param.base_size[0] 393 | 394 | # if the branch origin needs to be repositioned so bevel doesnt sit outside parent 395 | if pos_corr_turtle: 396 | # pos_corr_turtle currently positioned on circumference so subtract this branch radius 397 | # to ensure open ends are never visible 398 | pos_corr_turtle.move(-min(stem.radius, stem.radius_limit)) 399 | turtle.pos = pos_corr_turtle.pos 400 | 401 | # apply pruning, not required if is a clone, as this will have been tested already 402 | if cloned_turtle is None and self.param.prune_ratio > 0: 403 | # save start length and random state 404 | start_length = stem.length 405 | r_state = random_getstate() 406 | split_err_state = copy(self.split_num_error) 407 | 408 | # iteratively scale length by 0.9 until it fits, or remove entirely if we get to 80% 409 | # reduction 410 | in_pruning_envelope = self.test_stem(CHTurtle(turtle), stem, start, split_corr_angle, clone_prob) 411 | while not in_pruning_envelope: 412 | stem.length *= 0.9 413 | if stem.length < 0.15 * start_length: 414 | # too short to look good so remove allow for semi prune with 0 length 415 | if self.param.prune_ratio < 1: 416 | stem.length = 0 417 | break 418 | else: 419 | return 420 | 421 | random_setstate(r_state) 422 | self.split_num_error = split_err_state 423 | in_pruning_envelope = self.test_stem(CHTurtle(turtle), stem, start, split_corr_angle, clone_prob) 424 | 425 | fitting_length = stem.length 426 | # apply reduction scaled by prune ratio 427 | stem.length = start_length * (1 - self.param.prune_ratio) + fitting_length * self.param.prune_ratio 428 | # recalculate stem radius for new length 429 | stem.radius = self.calc_stem_radius(stem) 430 | # restore random state 431 | random_setstate(r_state) 432 | self.split_num_error = split_err_state 433 | 434 | # get parameters 435 | curve_res = int(self.param.curve_res[depth]) 436 | seg_splits = self.param.seg_splits[depth] 437 | seg_length = stem.length / curve_res 438 | 439 | # calc base segment 440 | base_seg_ind = ceil(self.param.base_size[0] * int(self.param.curve_res[0])) 441 | 442 | leaf_count = 0 443 | branch_count = 0 444 | if depth == self.param.levels - 1 and depth > 0 and self.param.leaf_blos_num != 0: 445 | # calc base leaf count 446 | leaf_count = self.calc_leaf_count(stem) 447 | # correct leaf count for start position along stem 448 | leaf_count *= 1 - start / curve_res 449 | # divide by curve_res to get no per seg 450 | f_leaves_on_seg = leaf_count / curve_res 451 | 452 | else: 453 | # calc base branch count 454 | branch_count = self.calc_branch_count(stem) 455 | # correct branch Count for start position along stem 456 | branch_count *= 1 - start / curve_res 457 | # correct for reduced number on clone branches 458 | branch_count *= num_branches_factor 459 | # divide by curve_res to get no per seg 460 | f_branches_on_seg = branch_count / curve_res 461 | 462 | # higher point resolution for flared based 463 | max_points_per_seg = ceil(max(1.0, 100 / curve_res)) 464 | 465 | # set up FS error values 466 | branch_num_error = 0 467 | leaf_num_error = 0 468 | 469 | # decide on start rotation for branches/leaves 470 | # use array to allow other methods to modify the value (otherwise passed by value) 471 | prev_rotation_angle = [0] 472 | if self.param.rotate[d_plus_1] >= 0: 473 | # start at random rotation 474 | prev_rotation_angle[0] = rand_in_range(0, 360) 475 | else: 476 | # on this case prev_rotation_angle used as multiplier to alternate side of branch 477 | prev_rotation_angle[0] = 1 478 | 479 | # calc helix parameters if needed 480 | hel_p_0 = hel_p_1 = hel_p_2 = hel_axis = None 481 | if self.param.curve_v[depth] < 0: 482 | tan_ang = tan(radians(90 - abs(self.param.curve_v[depth]))) 483 | hel_pitch = 2 * stem.length / curve_res * rand_in_range(0.8, 1.2) 484 | hel_radius = 3 * hel_pitch / (16 * tan_ang) * rand_in_range(0.8, 1.2) 485 | 486 | # apply full tropism if not trunk/main branch and horizontal tropism if is 487 | if depth > 1: 488 | apply_tropism(turtle, self.param.tropism) 489 | else: 490 | apply_tropism(turtle, Vector([self.param.tropism[0], self.param.tropism[1], 0])) 491 | 492 | hel_p_0, hel_p_1, hel_p_2, hel_axis = calc_helix_points(turtle, hel_radius, hel_pitch) 493 | 494 | # point resolution for this seg, max_points_per_seg if base, 1 otherwise 495 | if depth == 0 or self.param.taper[depth] > 1: 496 | points_per_seg = max_points_per_seg 497 | else: 498 | points_per_seg = 2 499 | 500 | for seg_ind in range(start, curve_res + 1): 501 | remaining_segs = curve_res + 1 - seg_ind 502 | 503 | # set up next bezier point 504 | if self.param.curve_v[depth] < 0: 505 | # negative curve_v so helix branch 506 | pos = turtle.pos 507 | if seg_ind == 0: 508 | new_point = stem.curve.bezier_points[0] 509 | new_point.co = pos.copy() 510 | new_point.handle_right = hel_p_0 + pos 511 | new_point.handle_left = pos.copy() 512 | 513 | else: 514 | stem.curve.bezier_points.add(1) 515 | new_point = stem.curve.bezier_points[-1] 516 | 517 | if seg_ind == 1: 518 | new_point.co = hel_p_2 + pos 519 | new_point.handle_left = hel_p_1 + pos 520 | new_point.handle_right = 2 * new_point.co - new_point.handle_left 521 | 522 | else: 523 | prev_point = stem.curve.bezier_points[-2] 524 | new_point.co = hel_p_2.rotated(Quaternion(hel_axis, (seg_ind - 1) * pi)) 525 | new_point.co += prev_point.co 526 | dif_p = (hel_p_2 - hel_p_1).rotated(Quaternion(hel_axis, (seg_ind - 1) * pi)) 527 | new_point.handle_left = new_point.co - dif_p 528 | new_point.handle_right = 2 * new_point.co - new_point.handle_left 529 | 530 | turtle.pos = new_point.co.copy() 531 | turtle.dir = new_point.handle_right.copy().normalized() 532 | 533 | else: 534 | # normal curved branch 535 | # get/make new point to be modified 536 | if seg_ind == start: 537 | new_point = stem.curve.bezier_points[0] 538 | else: 539 | turtle.move(seg_length) 540 | stem.curve.bezier_points.add(1) 541 | new_point = stem.curve.bezier_points[-1] 542 | 543 | # set position and handles of new point 544 | # if this is a clone then correct initial direction to match original to make 545 | # split smoother 546 | new_point.co = turtle.pos.copy() 547 | if cloned_turtle and seg_ind == start: 548 | new_point.handle_left = turtle.pos - cloned_turtle.dir * (stem.length / (curve_res * 3)) 549 | new_point.handle_right = turtle.pos + cloned_turtle.dir * (stem.length / (curve_res * 3)) 550 | else: 551 | new_point.handle_left = turtle.pos - turtle.dir * stem.length / (curve_res * 3) 552 | new_point.handle_right = turtle.pos + turtle.dir * stem.length / (curve_res * 3) 553 | 554 | # set radius of new point 555 | actual_radius = self.radius_at_offset(stem, seg_ind / curve_res) 556 | new_point.radius = actual_radius 557 | 558 | if seg_ind > start: 559 | # calc number of splits at this seg (N/A for helix) 560 | if self.param.curve_v[depth] >= 0: 561 | num_of_splits = 0 562 | 563 | if self.param.base_splits > 0 and depth == 0 and seg_ind == base_seg_ind: 564 | # if base_seg_ind and has base splits then override with base split number 565 | # take random number of splits up to max of base_splits if negative 566 | if self.param.base_splits < 0: 567 | num_of_splits = int(random_random() * (abs(self.param.base_splits) + 0.5)) 568 | else: 569 | num_of_splits = int(self.param.base_splits) 570 | elif seg_splits > 0 and seg_ind < curve_res and (depth > 0 or seg_ind > base_seg_ind): 571 | # otherwise get number of splits from seg_splits and use floyd-steinberg to 572 | # fix non-integer values only clone with probability clone_prob 573 | if random_random() <= clone_prob: 574 | num_of_splits = int(seg_splits + self.split_num_error[depth]) 575 | self.split_num_error[depth] -= num_of_splits - seg_splits 576 | 577 | # reduce clone/branch propensity 578 | clone_prob /= num_of_splits + 1 579 | num_branches_factor /= num_of_splits + 1 580 | num_branches_factor = max(0.8, num_branches_factor) 581 | 582 | # TODO do this better? 583 | # if depth != self.param.levels - 1: 584 | branch_count *= num_branches_factor 585 | f_branches_on_seg = branch_count / curve_res 586 | 587 | # add branches/leaves for this seg 588 | # if below max level of recursion then draw branches, otherwise draw leaves 589 | r_state = random_getstate() 590 | if abs(branch_count) > 0 and depth < self.param.levels - 1: 591 | if branch_count < 0: 592 | # fan branches 593 | if seg_ind == curve_res: 594 | branches_on_seg = int(branch_count) 595 | else: 596 | branches_on_seg = 0 597 | 598 | else: 599 | # get FS corrected branch number 600 | branches_on_seg = int(f_branches_on_seg + branch_num_error) 601 | branch_num_error -= branches_on_seg - f_branches_on_seg 602 | 603 | # add branches 604 | if abs(branches_on_seg) > 0: 605 | self.make_branches(turtle, stem, seg_ind, branches_on_seg, prev_rotation_angle) 606 | 607 | elif abs(leaf_count) > 0 and depth > 0: 608 | if leaf_count < 0: 609 | # fan leaves 610 | if seg_ind == curve_res: 611 | leaves_on_seg = leaf_count 612 | else: 613 | leaves_on_seg = 0 614 | else: 615 | # get FS corrected number of leaves 616 | leaves_on_seg = int(f_leaves_on_seg + leaf_num_error) 617 | leaf_num_error -= leaves_on_seg - f_leaves_on_seg 618 | 619 | # add leaves 620 | if abs(leaves_on_seg) > 0: 621 | self.make_leaves(turtle, stem, seg_ind, leaves_on_seg, prev_rotation_angle) 622 | 623 | random_setstate(r_state) 624 | 625 | # perform cloning if needed, not allowed for helix (also don't curve/apply tropism as irrelevant) 626 | if self.param.curve_v[depth] >= 0: 627 | if num_of_splits > 0: 628 | # calc angles for split 629 | is_base_split = (self.param.base_splits > 0 and depth == 0 and seg_ind == base_seg_ind) 630 | using_direct_split = self.param.split_angle[depth] < 0 631 | 632 | if using_direct_split: 633 | spr_angle = abs(self.param.split_angle[depth]) + random_uniform(-1, 1) * \ 634 | self.param.split_angle_v[depth] 635 | spl_angle = 0 636 | split_corr_angle = 0 637 | else: 638 | declination = turtle.dir.declination() 639 | spl_angle = self.param.split_angle[depth] + random_uniform(-1, 1) * self.param.split_angle_v[ 640 | depth] - declination 641 | spl_angle = max(0, spl_angle) 642 | split_corr_angle = spl_angle / remaining_segs 643 | spr_angle = - (20 + 0.75 * (30 + abs(declination - 90) * random_random() ** 2)) 644 | 645 | # make clone branches 646 | r_state = random_getstate() 647 | self.make_clones(turtle, seg_ind, split_corr_angle, num_branches_factor, clone_prob, stem, 648 | num_of_splits, spl_angle, spr_angle, is_base_split) 649 | random_setstate(r_state) 650 | 651 | # apply split to base stem 652 | turtle.pitch_down(spl_angle / 2) 653 | 654 | # apply spread if splitting to 2 and not base split 655 | if not is_base_split and num_of_splits == 1: 656 | if using_direct_split: 657 | turtle.turn_right(spr_angle / 2) 658 | else: 659 | turtle.dir.rotate(Quaternion(Vector([0, 0, 1]), radians(-spr_angle / 2))) 660 | turtle.dir.normalize() 661 | turtle.right.rotate(Quaternion(Vector([0, 0, 1]), radians(-spr_angle / 2))) 662 | turtle.right.normalize() 663 | else: 664 | # just apply curve and split correction 665 | turtle.turn_left(random_uniform(-1, 1) * self.param.bend_v[depth] / curve_res) 666 | curve_angle = self.calc_curve_angle(depth, seg_ind) 667 | turtle.pitch_down(curve_angle - split_corr_angle) 668 | 669 | # apply full tropism if not trunk/main branch and horizontal tropism if is 670 | if depth > 1: 671 | apply_tropism(turtle, Vector(self.param.tropism)) 672 | else: 673 | apply_tropism(turtle, Vector([self.param.tropism[0], self.param.tropism[1], 0])) 674 | 675 | # increase point resolution at base of trunk and apply flaring effect 676 | if points_per_seg > 2: 677 | self.increase_bezier_point_res(stem, seg_ind, points_per_seg) 678 | 679 | # scale down bezier point handles for flared base of trunk 680 | if points_per_seg > 2: 681 | scale_bezier_handles_for_flare(stem, max_points_per_seg) 682 | 683 | self.stem_index += 1 684 | 685 | def test_stem(self, turtle, stem, start=0, split_corr_angle=0, clone_prob=1): 686 | """Test if stem is inside pruning envelope""" 687 | # use level 3 parameters for any depth greater than this 688 | depth = stem.depth 689 | d_plus_1 = depth + 1 690 | if d_plus_1 > 3: 691 | d_plus_1 = 3 692 | 693 | # get parameters 694 | curve_res = int(self.param.curve_res[depth]) 695 | seg_splits = self.param.seg_splits[depth] 696 | seg_length = stem.length / curve_res 697 | 698 | # calc base segment 699 | base_seg_ind = ceil(self.param.base_size[0] * int(self.param.curve_res[0])) 700 | 701 | # decide on start rotation for branches/leaves 702 | # use array to allow other methods to modify the value (otherwise passed by value) 703 | prev_rotation_angle = [0] 704 | if self.param.rotate[d_plus_1] >= 0: 705 | # start at random rotation 706 | prev_rotation_angle[0] = rand_in_range(0, 360) 707 | else: 708 | # on this case prev_rotation_angle used as multiplier to alternate side of branch 709 | prev_rotation_angle[0] = 1 710 | 711 | # calc helix parameters if needed 712 | hel_p_2 = hel_axis = previous_helix_point = None 713 | if self.param.curve_v[depth] < 0: 714 | tan_ang = tan(radians(90 - abs(self.param.curve_v[depth]))) 715 | hel_pitch = 2 * stem.length / curve_res * rand_in_range(0.8, 1.2) 716 | hel_radius = 3 * hel_pitch / (16 * tan_ang) * rand_in_range(0.8, 1.2) 717 | # apply full tropism if not trunk/main branch and horizontal tropism if is 718 | if depth > 1: 719 | apply_tropism(turtle, self.param.tropism) 720 | else: 721 | apply_tropism(turtle, Vector([self.param.tropism[0], self.param.tropism[1], 0])) 722 | _, _, hel_p_2, hel_axis = calc_helix_points(turtle, hel_radius, hel_pitch) 723 | 724 | for seg_ind in range(start, curve_res + 1): 725 | remaining_segs = curve_res + 1 - seg_ind 726 | 727 | # set up next bezier point 728 | if self.param.curve_v[depth] < 0: 729 | # negative curve_v so helix branch 730 | pos = turtle.pos.copy() 731 | if seg_ind == 0: 732 | turtle.pos = pos 733 | else: 734 | if seg_ind == 1: 735 | turtle.pos = hel_p_2 + pos 736 | else: 737 | hel_p_2.rotate(Quaternion(hel_axis, (seg_ind - 1) * pi)) 738 | turtle.pos = hel_p_2 + previous_helix_point 739 | previous_helix_point = turtle.pos.copy() 740 | else: 741 | # normal curved branch 742 | # move turtle 743 | if seg_ind != start: 744 | turtle.move(seg_length) 745 | if not (stem.depth == 0 and start < base_seg_ind) and not self.point_inside(turtle.pos): 746 | return False 747 | 748 | if seg_ind > start: 749 | # calc number of splits at this seg (N/A for helix) 750 | if self.param.curve_v[depth] >= 0: 751 | num_of_splits = 0 752 | if self.param.base_splits > 0 and depth == 0 and seg_ind == base_seg_ind: 753 | # if base_seg_ind and has base splits then override with base split number 754 | # take random number of splits up to max of base_splits 755 | num_of_splits = int(random_random() * (self.param.base_splits + 0.5)) 756 | elif seg_splits > 0 and seg_ind < curve_res and (depth > 0 or seg_ind > base_seg_ind): 757 | # otherwise get number of splits from seg_splits and use Floyd-Steinberg to 758 | # fix non-integer values only clone with probability clone_prob 759 | if random_random() <= clone_prob: 760 | num_of_splits = int(seg_splits + self.split_num_error[depth]) 761 | self.split_num_error[depth] -= num_of_splits - seg_splits 762 | # reduce clone/branch propensity 763 | clone_prob /= num_of_splits + 1 764 | 765 | # perform cloning if needed, not allowed for helix (also don't curve/apply tropism as irrelevant) 766 | if num_of_splits > 0: 767 | # calc angles for split 768 | is_base_split = (self.param.base_splits > 0 and depth == 0 and seg_ind == base_seg_ind) 769 | using_direct_split = self.param.split_angle[depth] < 0 770 | if using_direct_split: 771 | spr_angle = abs(self.param.split_angle[depth]) + random_uniform(-1, 1) * \ 772 | self.param.split_angle_v[depth] 773 | spl_angle = 0 774 | split_corr_angle = 0 775 | else: 776 | declination = turtle.dir.declination() 777 | spl_angle = self.param.split_angle[depth] + random_uniform(-1, 1) * self.param.split_angle_v[ 778 | depth] - declination 779 | spl_angle = max(0, spl_angle) 780 | split_corr_angle = spl_angle / remaining_segs 781 | spr_angle = - (20 + 0.75 * (30 + abs(declination - 90) * random_random() ** 2)) 782 | 783 | # apply split to base stem 784 | turtle.pitch_down(spl_angle / 2) 785 | # apply spread if splitting to 2 and not base split 786 | if not is_base_split and num_of_splits == 1: 787 | if using_direct_split: 788 | turtle.turn_left(spr_angle / 2) 789 | else: 790 | turtle.dir.rotate(Quaternion(Vector([0, 0, 1]), radians(-spr_angle / 2))) 791 | turtle.dir.normalize() 792 | turtle.right.rotate(Quaternion(Vector([0, 0, 1]), radians(-spr_angle / 2))) 793 | turtle.right.normalize() 794 | else: 795 | # just apply curve and split correction 796 | turtle.turn_left(random_uniform(-1, 1) * self.param.bend_v[depth] / curve_res) 797 | curve_angle = self.calc_curve_angle(depth, seg_ind) 798 | turtle.pitch_down(curve_angle - split_corr_angle) 799 | 800 | # apply full tropism if not trunk/main branch and horizontal tropism if is 801 | if depth > 1: 802 | apply_tropism(turtle, Vector(self.param.tropism)) 803 | else: 804 | apply_tropism(turtle, Vector([self.param.tropism[0], self.param.tropism[1], 0])) 805 | 806 | return self.point_inside(turtle.pos) 807 | 808 | def make_clones(self, turtle, seg_ind, split_corr_angle, num_branches_factor, clone_prob, 809 | stem, num_of_splits, spl_angle, spr_angle, is_base_split): 810 | """make clones of branch used if seg_splits or base_splits > 0""" 811 | 812 | using_direct_split = self.param.split_angle[stem.depth] < 0 813 | stem_depth = self.param.split_angle_v[stem.depth] 814 | 815 | if not is_base_split and num_of_splits > 2 and using_direct_split: 816 | raise Exception('Only splitting up to 3 branches is supported') 817 | 818 | for split_index in range(num_of_splits): 819 | # copy turtle for new branch 820 | n_turtle = CHTurtle(turtle) 821 | # tip branch down away from axis of stem 822 | n_turtle.pitch_down(spl_angle / 2) 823 | 824 | # spread out clones 825 | if is_base_split and not using_direct_split: 826 | eff_spr_angle = (split_index + 1) * (360 / (num_of_splits + 1)) + random_uniform(-1, 1) * stem_depth 827 | 828 | else: 829 | if split_index == 0: 830 | eff_spr_angle = spr_angle / 2 831 | else: 832 | eff_spr_angle = -spr_angle / 2 833 | 834 | if using_direct_split: 835 | n_turtle.turn_left(eff_spr_angle) 836 | 837 | else: 838 | quat = Quaternion(Vector([0, 0, 1]), radians(eff_spr_angle)) 839 | 840 | n_turtle.dir.rotate(quat) 841 | turtle.dir.normalize() 842 | n_turtle.right.rotate(quat) 843 | turtle.right.normalize() 844 | 845 | # create new clone branch and set up then recurse 846 | split_stem = self.branch_curves[stem.depth].splines.new('BEZIER') 847 | split_stem.resolution_u = stem.curve.resolution_u 848 | split_stem.radius_interpolation = 'CARDINAL' 849 | new_stem = stem.copy() 850 | new_stem.curve = split_stem 851 | 852 | if self.param.split_angle_v[stem.depth] >= 0: 853 | cloned = turtle 854 | else: 855 | cloned = None 856 | 857 | self.make_stem(n_turtle, new_stem, seg_ind, split_corr_angle, num_branches_factor, clone_prob, 858 | cloned_turtle=cloned) 859 | 860 | def make_branches(self, turtle, stem, seg_ind, branches_on_seg, prev_rotation_angle, is_leaves=False): 861 | """Make the required branches for a segment of the stem""" 862 | start_point = stem.curve.bezier_points[-2] 863 | end_point = stem.curve.bezier_points[-1] 864 | branches_array = [] 865 | d_plus_1 = min(3, stem.depth + 1) 866 | 867 | if branches_on_seg < 0: # fan branches 868 | for branch_ind in range(abs(int(branches_on_seg))): 869 | stem_offset = 1 870 | branches_array.append(self.set_up_branch(turtle, stem, BranchMode.fan, 1, start_point, end_point, stem_offset, 871 | branch_ind, prev_rotation_angle, abs(branches_on_seg))) 872 | else: 873 | base_length = stem.length * self.param.base_size[stem.depth] 874 | branch_dist = self.param.branch_dist[d_plus_1] 875 | curve_res = int(self.param.curve_res[stem.depth]) 876 | 877 | if branch_dist > 1: # whorled branches 878 | # calc number of whorls, will result in a rounded number of branches rather than the 879 | # exact amount specified by branches_on_seg 880 | num_of_whorls = int(branches_on_seg / (branch_dist + 1)) 881 | branches_per_whorl = branch_dist + 1 882 | branch_whorl_error = 0 883 | 884 | for whorl_num in range(num_of_whorls): 885 | # calc whorl offset in segment and on stem 886 | offset = min(max(0.0, whorl_num / num_of_whorls), 1.0) 887 | stem_offset = (((seg_ind - 1) + offset) / curve_res) * stem.length 888 | 889 | # if not in base area then make the branches 890 | if stem_offset > base_length: 891 | # calc FS corrected num of branches this whorl 892 | branches_this_whorl = int(branches_per_whorl + branch_whorl_error) 893 | branch_whorl_error -= branches_this_whorl - branches_per_whorl 894 | 895 | # set up these branches 896 | for branch_ind in range(branches_this_whorl): 897 | branches_array.append(self.set_up_branch(turtle, stem, BranchMode.whorled, offset, start_point, 898 | end_point, stem_offset, branch_ind, prev_rotation_angle, 899 | branches_this_whorl)) 900 | 901 | # rotate start angle for next whorl 902 | prev_rotation_angle[0] += self.param.rotate[d_plus_1] 903 | else: # alternating or opposite branches 904 | # ensure even number of branches on segment if near opposite 905 | for branch_ind in range(branches_on_seg): 906 | # calc offset in segment and on stem 907 | if branch_ind % 2 == 0: 908 | offset = min(max(0, branch_ind / branches_on_seg), 1) 909 | else: 910 | offset = min(max(0, (branch_ind - branch_dist) / branches_on_seg), 1) 911 | 912 | stem_offset = (((seg_ind - 1) + offset) / curve_res) * stem.length 913 | # if not in base area then set up the branch 914 | if stem_offset > base_length: 915 | branches_array.append(self.set_up_branch(turtle, stem, BranchMode.alt_opp, offset, 916 | start_point, end_point, stem_offset, branch_ind, 917 | prev_rotation_angle)) 918 | 919 | # make all new branches from branches_array, passing pos_corr_turtle which will be used to 920 | # set the position of branch_turtle in this call 921 | if is_leaves: 922 | for pos_tur, dir_tur, _, _ in branches_array: 923 | self.leaves_array.append(Leaf(pos_tur.pos, dir_tur.dir, dir_tur.right)) 924 | else: 925 | for pos_tur, dir_tur, rad, b_offset in branches_array: 926 | new_spline = self.branch_curves[d_plus_1].splines.new('BEZIER') 927 | new_spline.resolution_u = self.param.curve_res[d_plus_1] 928 | new_spline.radius_interpolation = 'CARDINAL' 929 | self.make_stem(dir_tur, Stem(d_plus_1, new_spline, stem, b_offset, rad), pos_corr_turtle=pos_tur) 930 | 931 | def make_leaves(self, turtle, stem, seg_ind, leaves_on_seg, prev_rotation_angle): 932 | """Make the required leaves for a segment of the stem""" 933 | self.make_branches(turtle, stem, seg_ind, leaves_on_seg, 934 | prev_rotation_angle, True) 935 | 936 | def set_up_branch(self, turtle, stem, branch_mode, offset, start_point, 937 | end_point, stem_offset, branch_ind, prev_rot_ang, branches_in_group=0): 938 | """Set up a new branch, creating the new direction and position turtle and orienting them 939 | correctly and adding the required info to the list of branches to be made""" 940 | 941 | d_plus_1 = min(3, stem.depth + 1) 942 | 943 | # make branch direction turtle 944 | branch_dir_turtle = make_branch_dir_turtle(turtle, self.param.curve_v[stem.depth] < 0, offset, start_point, 945 | end_point) 946 | 947 | # calc rotation angle 948 | if branch_mode is BranchMode.fan: 949 | if branches_in_group == 1: 950 | t_angle = 0 951 | else: 952 | t_angle = (self.param.rotate[d_plus_1] * ( 953 | (branch_ind / (branches_in_group - 1)) - 1 / 2)) + random_uniform(-1, 1) * self.param.rotate_v[ 954 | d_plus_1] 955 | branch_dir_turtle.turn_right(t_angle) 956 | radius_limit = 0 957 | else: 958 | if branch_mode is BranchMode.whorled: 959 | r_angle = prev_rot_ang[0] + (360 * branch_ind / branches_in_group) + random_uniform(-1, 1) * \ 960 | self.param.rotate_v[d_plus_1] 961 | else: 962 | r_angle = self.calc_rotate_angle(d_plus_1, prev_rot_ang[0]) 963 | if self.param.rotate[d_plus_1] >= 0: 964 | prev_rot_ang[0] = r_angle 965 | else: 966 | prev_rot_ang[0] = -prev_rot_ang[0] 967 | 968 | # orient direction turtle to correct rotation 969 | branch_dir_turtle.roll_right(r_angle) 970 | radius_limit = self.radius_at_offset(stem, stem_offset / stem.length) 971 | 972 | # make branch position turtle in appropriate position on circumference 973 | branch_pos_turtle = make_branch_pos_turtle(branch_dir_turtle, offset, start_point, 974 | end_point, radius_limit) 975 | 976 | # calc down angle 977 | d_angle = self.calc_down_angle(stem, stem_offset) 978 | 979 | # orient direction turtle to correct declination 980 | branch_dir_turtle.pitch_down(d_angle) 981 | 982 | # return branch info 983 | return branch_pos_turtle, branch_dir_turtle, radius_limit, stem_offset 984 | 985 | def calc_stem_length(self, stem): 986 | """Calculate length of this stem as defined in paper""" 987 | if stem.depth == 0: # trunk 988 | result = self.tree_scale * (self.param.length[0] + random_uniform(-1, 1) * self.param.length_v[0]) 989 | self.trunk_length = result 990 | elif stem.depth == 1: # first level 991 | result = stem.parent.length * stem.parent.length_child_max * self.shape_ratio( 992 | self.param.shape, (stem.parent.length - stem.offset) / ( 993 | stem.parent.length - self.base_length)) 994 | else: # other 995 | result = stem.parent.length_child_max * (stem.parent.length - 0.7 * stem.offset) 996 | return max(0, result) 997 | 998 | def calc_stem_radius(self, stem): 999 | """Calculate radius of this stem as defined in paper""" 1000 | if stem.depth == 0: # trunk 1001 | result = stem.length * self.param.ratio * self.param.radius_mod[0] 1002 | else: # other 1003 | result = self.param.radius_mod[stem.depth] * stem.parent.radius * pow(( 1004 | stem.length / stem.parent.length), self.param.ratio_power) 1005 | result = max(0.005, result) 1006 | result = min(stem.radius_limit, result) 1007 | return result 1008 | 1009 | def calc_curve_angle(self, depth, seg_ind): 1010 | """Calculate curve angle for segment number seg_ind on a stem""" 1011 | curve = self.param.curve[depth] 1012 | curve_v = self.param.curve_v[depth] 1013 | curve_back = self.param.curve_back[depth] 1014 | curve_res = int(self.param.curve_res[depth]) 1015 | if curve_back == 0: 1016 | curve_angle = curve / curve_res 1017 | else: 1018 | if seg_ind < curve_res / 2.0: 1019 | curve_angle = curve / (curve_res / 2.0) 1020 | else: 1021 | curve_angle = curve_back / (curve_res / 2.0) 1022 | curve_angle += random_uniform(-1, 1) * (curve_v / curve_res) 1023 | return curve_angle 1024 | 1025 | def calc_down_angle(self, stem, stem_offset): 1026 | """calc down angle as defined in paper""" 1027 | d_plus_1 = min(stem.depth + 1, 3) 1028 | if self.param.down_angle_v[d_plus_1] >= 0: 1029 | d_angle = self.param.down_angle[d_plus_1] + random_uniform(-1, 1) * self.param.down_angle_v[d_plus_1] 1030 | else: 1031 | d_angle = self.param.down_angle[d_plus_1] + (self.param.down_angle_v[d_plus_1] * ( 1032 | 1 - 2 * self.shape_ratio(0, (stem.length - stem_offset) / (stem.length * ( 1033 | 1 - self.param.base_size[stem.depth]))))) 1034 | # introduce some variance to improve visual result 1035 | d_angle += random_uniform(-1, 1) * abs(d_angle * 0.1) 1036 | return d_angle 1037 | 1038 | def calc_rotate_angle(self, depth, prev_angle): 1039 | """calc rotate angle as defined in paper, limit to 0-360""" 1040 | if self.param.rotate[depth] >= 0: 1041 | r_angle = (prev_angle + self.param.rotate[depth] + random_uniform(-1, 1) * self.param.rotate_v[depth]) % 360 1042 | else: 1043 | r_angle = prev_angle * (180 + self.param.rotate[depth] + random_uniform(-1, 1) * self.param.rotate_v[depth]) 1044 | return r_angle 1045 | 1046 | def calc_leaf_count(self, stem): 1047 | """Calculate leaf count of this stem as defined in paper""" 1048 | if self.param.leaf_blos_num >= 0: 1049 | # scale number of leaves to match global scale and taper 1050 | leaves = self.param.leaf_blos_num * self.tree_scale / self.param.g_scale 1051 | result = leaves * (stem.length / (stem.parent.length_child_max * stem.parent.length)) 1052 | else: # fan leaves 1053 | return self.param.leaf_blos_num 1054 | return result 1055 | 1056 | def calc_branch_count(self, stem): 1057 | """Calculate branch count of this stem as defined in paper""" 1058 | d_p_1 = min(stem.depth + 1, 3) 1059 | if stem.depth == 0: 1060 | result = self.param.branches[d_p_1] * (random_random() * 0.2 + 0.9) 1061 | else: 1062 | if self.param.branches[d_p_1] < 0: 1063 | result = self.param.branches[d_p_1] 1064 | elif stem.depth == 1: 1065 | result = self.param.branches[d_p_1] * (0.2 + 0.8 * ( 1066 | stem.length / stem.parent.length) / stem.parent.length_child_max) 1067 | else: 1068 | result = self.param.branches[d_p_1] * (1.0 - 0.5 * stem.offset / stem.parent.length) 1069 | return result / (1 - self.param.base_size[stem.depth]) 1070 | 1071 | def shape_ratio(self, shape, ratio): 1072 | """Calculate shape ratio as defined in paper""" 1073 | if shape == 1: # spherical 1074 | result = 0.2 + 0.8 * sin(pi * ratio) 1075 | elif shape == 2: # hemispherical 1076 | result = 0.2 + 0.8 * sin(0.5 * pi * ratio) 1077 | elif shape == 3: # cylindrical 1078 | result = 1.0 1079 | elif shape == 4: # tapered cylindrical 1080 | result = 0.5 + 0.5 * ratio 1081 | elif shape == 5: # flame 1082 | if ratio <= 0.7: 1083 | result = ratio / 0.7 1084 | else: 1085 | result = (1.0 - ratio) / 0.3 1086 | elif shape == 6: # inverse conical 1087 | result = 1.0 - 0.8 * ratio 1088 | elif shape == 7: # tend flame 1089 | if ratio <= 0.7: 1090 | result = 0.5 + 0.5 * ratio / 0.7 1091 | else: 1092 | result = 0.5 + 0.5 * (1.0 - ratio) / 0.3 1093 | elif shape == 8: # envelope 1094 | if ratio < 0 or ratio > 1: 1095 | result = 0.0 1096 | elif ratio < 1 - self.param.prune_width_peak: 1097 | result = pow(ratio / (1 - self.param.prune_width_peak), 1098 | self.param.prune_power_high) 1099 | else: 1100 | result = pow((1 - ratio) / (1 - self.param.prune_width_peak), 1101 | self.param.prune_power_low) 1102 | else: # conical (0) 1103 | result = 0.2 + 0.8 * ratio 1104 | return result 1105 | 1106 | def radius_at_offset(self, stem, z_1): 1107 | """ calculate radius of stem at offset z_1 along it """ 1108 | n_taper = self.param.taper[stem.depth] 1109 | 1110 | if n_taper < 1: 1111 | unit_taper = n_taper 1112 | elif n_taper < 2: 1113 | unit_taper = 2 - n_taper 1114 | else: 1115 | unit_taper = 0 1116 | taper = stem.radius * (1 - unit_taper * z_1) 1117 | 1118 | if n_taper < 1: 1119 | radius = taper 1120 | else: 1121 | z_2 = (1 - z_1) * stem.length 1122 | if n_taper < 2 or z_2 < taper: 1123 | depth = 1 1124 | else: 1125 | depth = n_taper - 2 1126 | if n_taper < 2: 1127 | z_3 = z_2 1128 | else: 1129 | z_3 = abs(z_2 - 2 * taper * int(z_2 / (2 * taper) + 0.5)) 1130 | if n_taper < 2 and z_3 >= taper: 1131 | radius = taper 1132 | else: 1133 | radius = (1 - depth) * taper + depth * sqrt(pow(taper, 2) - pow((z_3 - taper), 2)) 1134 | if stem.depth == 0: 1135 | y_val = max(0, 1 - 8 * z_1) 1136 | flare = self.param.flare * ((pow(100, y_val) - 1) / 100) + 1 1137 | radius *= flare 1138 | return radius 1139 | 1140 | def increase_bezier_point_res(self, stem, seg_ind, points_per_seg): 1141 | """add in new points in appropriate positions along curve and modify radius for flare""" 1142 | # need a copy of the end point as it is moved during the process, but also used for 1143 | # calculations throughout 1144 | curve_res = int(self.param.curve_res[stem.depth]) 1145 | seg_end_point = stem.curve.bezier_points[-1] 1146 | FakeSplinePoint = namedtuple('FakeSplinePoint', ['co', 'handle_left', 'handle_right']) 1147 | end_point = FakeSplinePoint(seg_end_point.co.copy(), 1148 | seg_end_point.handle_left.copy(), 1149 | seg_end_point.handle_right.copy()) 1150 | seg_start_point = stem.curve.bezier_points[-2] 1151 | start_point = FakeSplinePoint(seg_start_point.co.copy(), 1152 | seg_start_point.handle_left.copy(), 1153 | seg_start_point.handle_right.copy()) 1154 | for k in range(0, points_per_seg): 1155 | # add new point and position 1156 | # at this point the normals are left over-sized in order to allow for evaluation of the 1157 | # original curve in later steps 1158 | # once the stem is entirely built we then go back and scale the handles 1159 | offset = k / (points_per_seg - 1) 1160 | if k == 0: 1161 | curr_point = seg_start_point 1162 | else: 1163 | if k == 1: 1164 | curr_point = seg_end_point 1165 | else: 1166 | stem.curve.bezier_points.add(1) 1167 | curr_point = stem.curve.bezier_points[-1] 1168 | if k == points_per_seg - 1: 1169 | curr_point.co = end_point.co 1170 | curr_point.handle_left = end_point.handle_left 1171 | curr_point.handle_right = end_point.handle_right 1172 | else: 1173 | curr_point.co = calc_point_on_bezier(offset, start_point, end_point) 1174 | # set handle to match direction of curve 1175 | tangent = calc_tangent_to_bezier(offset, start_point, end_point).normalized() 1176 | # and set the magnitude to match other control points 1177 | dir_vec_mag = (end_point.handle_left - end_point.co).magnitude 1178 | curr_point.handle_left = curr_point.co - tangent * dir_vec_mag 1179 | curr_point.handle_right = curr_point.co + tangent * dir_vec_mag 1180 | 1181 | curr_point.radius = self.radius_at_offset(stem, (offset + seg_ind - 1) / curve_res) 1182 | 1183 | def point_inside(self, point): 1184 | """Check if point == inside pruning envelope, from WP 4.6""" 1185 | # return point_in_cube(Vector([point.x, point.y, point.z - self.base_length])) 1186 | dist = sqrt(point.x ** 2 + point.y ** 2) 1187 | ratio = (self.tree_scale - point.z) / (self.tree_scale * (1 - self.param.base_size[0])) 1188 | inside = (dist / self.tree_scale) < (self.param.prune_width * self.shape_ratio(8, ratio)) 1189 | # inside = inside and (point.x > -0.7 or point.z > 5.3) 1190 | return inside 1191 | 1192 | 1193 | # ------ RELATED FUNCTIONS ------ # 1194 | 1195 | def make_branch_pos_turtle(dir_turtle, offset, start_point, end_point, radius_limit): 1196 | """Create and setup the turtle for the position of a new branch, also returning the radius 1197 | of the parent to use as a limit for the child""" 1198 | 1199 | dir_turtle.pos = calc_point_on_bezier(offset, start_point, end_point) 1200 | branch_pos_turtle = CHTurtle(dir_turtle) 1201 | branch_pos_turtle.pitch_down(90) 1202 | branch_pos_turtle.move(radius_limit) 1203 | 1204 | return branch_pos_turtle 1205 | 1206 | 1207 | def make_branch_dir_turtle(turtle, helix, offset, start_point, end_point): 1208 | """Create and setup the turtle for the direction of a new branch""" 1209 | 1210 | branch_dir_turtle = CHTurtle() 1211 | tangent = calc_tangent_to_bezier(offset, start_point, end_point) 1212 | tangent.normalize() 1213 | branch_dir_turtle.dir = tangent 1214 | 1215 | if helix: 1216 | # approximation to actual normal to preserve for helix 1217 | tan_d = calc_tangent_to_bezier(offset + 0.0001, start_point, end_point).normalized() 1218 | branch_dir_turtle.right = branch_dir_turtle.dir.cross(tan_d) 1219 | else: 1220 | # generally curve lines in plane define by turtle.right, so is fair approximation to take new right as being 1221 | # parallel to this, ie find the turtle up vector (in the plane) and cross with tangent (assumed in the plane) 1222 | # to get the new direction - this doesn't hold for the helix 1223 | branch_dir_turtle.right = turtle.dir.cross(turtle.right).cross(branch_dir_turtle.dir) 1224 | 1225 | return branch_dir_turtle 1226 | 1227 | 1228 | def apply_tropism(turtle, tropism_vector): 1229 | """Apply tropism_vector to turtle direction""" 1230 | h_cross_t = turtle.dir.cross(tropism_vector) 1231 | # calc angle to rotate by (from ABoP) multiply to achieve accurate results from WP attractionUp param 1232 | alpha = 10 * h_cross_t.magnitude 1233 | h_cross_t.normalize() 1234 | # rotate by angle about axis perpendicular to turtle direction and tropism vector 1235 | turtle.dir.rotate(Quaternion(h_cross_t, radians(alpha))) 1236 | turtle.dir.normalize() 1237 | turtle.right.rotate(Quaternion(h_cross_t, radians(alpha))) 1238 | turtle.right.normalize() 1239 | 1240 | 1241 | def scale_bezier_handles_for_flare(stem, max_points_per_seg): 1242 | """Reduce length of bezier handles to account for increased density of points on curve for 1243 | flared base of trunk""" 1244 | for point in stem.curve.bezier_points: 1245 | point.handle_left = point.co + (point.handle_left - point.co) / max_points_per_seg 1246 | point.handle_right = point.co + (point.handle_right - point.co) / max_points_per_seg 1247 | 1248 | 1249 | def construct(params, seed=0, generate_leaves=True): 1250 | """Construct the tree""" 1251 | 1252 | if seed == 0: 1253 | seed = int(random_random() * 9999999) 1254 | bpy.context.scene.last_seed = seed 1255 | 1256 | update_log('\nUsing seed: {}\n'.format(seed)) 1257 | 1258 | random.seed(seed) 1259 | 1260 | t = Tree(TreeParam(params), generate_leaves) 1261 | t.make() 1262 | 1263 | ret_obj = t.tree_obj 1264 | 1265 | # Try to get unneeded data out of memory ASAP 1266 | del t.leaves_array 1267 | del t.branch_curves 1268 | del t 1269 | 1270 | return ret_obj 1271 | --------------------------------------------------------------------------------