├── screenshot.png ├── parametric_cookie.png ├── examples ├── simple_config.json ├── config.json ├── minimal_cube.py ├── minimal_sphere.py └── LICENSE ├── .gitignore ├── README.md ├── panel └── __init__.py ├── core ├── materials.py ├── scene │ └── __init__.py ├── LICENSE ├── __init__.py └── geometry.py ├── __init__.py └── LICENSE /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/njanakiev/cookie-factory/HEAD/screenshot.png -------------------------------------------------------------------------------- /parametric_cookie.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/njanakiev/cookie-factory/HEAD/parametric_cookie.png -------------------------------------------------------------------------------- /examples/simple_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "scene": "minimal_cube", 3 | "animation": { 4 | "frames": 100 5 | }, 6 | "resolution": { 7 | "width": 800, 8 | "height": 800, 9 | "percentage": 100 10 | }, 11 | "override": false, 12 | "output_folder": "render" 13 | } 14 | -------------------------------------------------------------------------------- /examples/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "scenes": ["minimal_cube", "minimal_sphere"], 3 | "scene_idx": 1, 4 | "animation": { 5 | "frames": 40 6 | }, 7 | "resolution": { 8 | "width": 800, 9 | "height": 800, 10 | "percentage": 100 11 | }, 12 | "override": false, 13 | "threads": 1, 14 | "output_folder": "render" 15 | } 16 | -------------------------------------------------------------------------------- /examples/minimal_cube.py: -------------------------------------------------------------------------------- 1 | import core 2 | from math import pi 3 | PI, TAU = pi, 2*pi 4 | 5 | 6 | class Composition(core.scene.Scene): 7 | def setup(self): 8 | # Create a simple scene with target, camera and sun 9 | core.simple_scene((0, 0, 0), (-5, -13, 5), (-10, -10, 4)) 10 | 11 | # Create a cube object of size 5 12 | self.obj = core.geometry.cube(size=5) 13 | 14 | def draw(self): 15 | # Set t to be in the range between 0 and 1 16 | t = self.frame / self.frames 17 | 18 | # Rotate the cube for one full rotation on two rotation axis 19 | self.obj.rotation_euler = (0, t*TAU, t*TAU) 20 | -------------------------------------------------------------------------------- /examples/minimal_sphere.py: -------------------------------------------------------------------------------- 1 | import core 2 | from math import sin, cos, pi 3 | PI, TAU = pi, 2*pi 4 | 5 | 6 | class Composition(core.scene.Scene): 7 | def setup(self): 8 | # Create a simple scene with target, camera and sun 9 | core.simple_scene((0, 0, 0), (0, -13, 0), (-10, -10, 4)) 10 | 11 | # Create a list of 3 icospheres 12 | self.objects = [core.geometry.icosphere(diameter=1.5) 13 | for i in range(3)] 14 | 15 | def draw(self): 16 | t = self.frame / self.frames 17 | 18 | radius = 3 19 | for i, obj in enumerate(self.objects): 20 | k = i / len(self.objects) 21 | phi = TAU*k 22 | 23 | x = radius*sin(TAU*t + PI + phi) 24 | y = radius*sin(TAU*t + PI/2 + phi) 25 | z = radius*sin(TAU*t + PI/3 + phi) 26 | 27 | x_scale = sin(2*TAU*t + phi)*0.25 + 0.5 28 | y_scale = sin(1*TAU*t + phi)*0.25 + 0.5 29 | z_scale = sin(3*TAU*t + phi)*0.25 + 0.5 30 | 31 | obj.location = (x, y, z) 32 | obj.scale = (x_scale, y_scale, z_scale) 33 | -------------------------------------------------------------------------------- /examples/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Nikolai Janakiev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .directory 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | .spyproject 95 | 96 | # Rope project settings 97 | .ropeproject 98 | 99 | # mkdocs documentation 100 | /site 101 | 102 | # mypy 103 | .mypy_cache/ 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cookie Factory 2 | 3 | This is a [processing](https://processing.org/)-style scripting add-on for Blender, which offers configurable Python scripting with Blender. You can run scripts in the background or within Blender and it offers various helper functions and classes to make quick and more involved sketches and animations. It is particularly useful for generative animations that are fully scripted with the Blender API. This add-on evolved from the various modules and functions used to create most of the pieces in the [Parametric Cookie](https://parametriccookie.tumblr.com/) Collection. 4 | 5 | ![Parametric Cookie](parametric_cookie.png) 6 | 7 | 8 | ## Installation 9 | 10 | Download the Cookie Factory Add-on from Github as an [archive](https://github.com/njanakiev/cookie-factory/archive/master.zip). Next, open Blender and go to _File > User Preferences > Addons > Install from File_ and then choose the zip-archive and activate the flag besides the Cookie Factory Add-on. 11 | 12 | 13 | ## Getting Started 14 | 15 | There are a few examples to illustrate the functionality in the [examples](examples) folder. You can run them by extracting the examples folder from the archive, selecting the [config.json](examples/config.json) file in the file picker in the toolbar and pressing the _Import / Reload_ button below. This loads the scene defined in the configuration file. Below the button you can choose which scripted scene to choose from (which are again located in the examples folder). 16 | 17 | ![Screenshot](screenshot.png) 18 | 19 | 20 | ## Usage 21 | 22 | To start write your own script copy the [simple_config.json](examples/simple_config.json) to the folder your want your project to be in and change there the name in `"scene": "minimal_cube"` from `minimal_cube` to your python file in the folder without the extension. To run properly, import the `core` module and extend `class Composition` from `core.scene.Scene` as in the following example. 23 | 24 | ```python 25 | import core 26 | from math import pi 27 | PI, TAU = pi, 2*pi 28 | 29 | class Composition(core.scene.Scene): 30 | def setup(self): 31 | # Create a simple scene with target, camera and sun 32 | core.simple_scene((0, 0, 0), (-5, -13, 5), (-10, -10, 4)) 33 | 34 | # Create a cube object of size 5 35 | self.obj = core.geometry.cube(size=5) 36 | ``` 37 | You need to implement a `setup(self)` function which is called once. You can optionally implement a `draw(self)` function which is called for each frame change. This function can have the following form. 38 | 39 | ```python 40 | def draw(self): 41 | # Set t to be in the range between 0 and 1 42 | t = self.frame / self.frames 43 | 44 | # Rotate the cube for one full rotation on two rotation axis 45 | self.obj.rotation_euler = (0, t*TAU, t*TAU) 46 | ``` 47 | There you can access the current frame with `self.frame` and the number of frames with `self.frames`. There are many more functions to choose from within the [core](core) module and you can also access the `bpy` and `bmesh` modules, besides all the available Python modules you would have within Blender. 48 | 49 | You can run the code by loading the config file in Blender with the Cookie Factory Toolbox as previously shown or you can run it in the background by using the command 50 | 51 | ``` 52 | blender -b -a -- config.json 53 | ``` 54 | to render animations. In order to render single frames use the command 55 | 56 | ``` 57 | blender -b -f 1 -- config.json 58 | ``` 59 | When rendering animation or a single frame, the frames are rendered in the specified `output_folder` folder from the config.json and there the frames are rendered to a folder or an image with the name of the scene for animation and single frame render respectively. If you want the frames or the animation folder to be overwritten you can use the `override` option in the config.json. 60 | 61 | ## License 62 | 63 | This project uses the LGPL v3 for the code within the core folder and the code within the examples folder is licensed under the MIT license. The rest of the project is licensed under the GPL v3. 64 | -------------------------------------------------------------------------------- /panel/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This program is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation; either version 3 8 | # of the License, or (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | 21 | 22 | import bpy 23 | import logging 24 | import importlib 25 | from bpy.props import BoolProperty, StringProperty, PointerProperty, EnumProperty, CollectionProperty 26 | 27 | logger = logging.getLogger(__name__) 28 | 29 | 30 | class ConfigurationPropertyGroup(bpy.types.PropertyGroup): 31 | log = logging.getLogger('bpy.types.ConfigurationPropertyGroup') 32 | 33 | def get_items(self, context): 34 | return [(item.name, item.name, '') for item in self.scene_names] 35 | 36 | override = BoolProperty(name='Override', default=False) 37 | 38 | output_folder = StringProperty(name='', default='output') 39 | output_name = StringProperty(name='') 40 | 41 | scene_names = CollectionProperty(type=bpy.types.PropertyGroup) 42 | scene_name = EnumProperty(name='Scenes', 43 | items=get_items, 44 | update=lambda self, context : self.execute(context)) 45 | 46 | config_filepath = StringProperty(name='Configuraton', 47 | description='Path of configuraton', 48 | default='', options={'HIDDEN'}, 49 | subtype='FILE_PATH') 50 | 51 | def execute(self, context): 52 | self.log.debug('execute called') 53 | cf = context.scene.cookie_factory 54 | 55 | try: 56 | composition = importlib.import_module(cf.scene_name) 57 | if "composition" in locals(): 58 | logger.debug('reload composition') 59 | importlib.reload(composition) 60 | 61 | self.log.debug('Running ' + cf.scene_name) 62 | comp = composition.Composition(context) 63 | except ImportError as e: 64 | self.log.error(e) 65 | 66 | 67 | class CookieFactoryPanel(bpy.types.Panel): 68 | bl_space_type = 'VIEW_3D' 69 | bl_region_type = 'TOOLS' 70 | bl_label = 'Cookie Factory' 71 | bl_context = 'objectmode' 72 | bl_category = 'Cookie Factory' 73 | 74 | def draw(self, context): 75 | layout = self.layout 76 | properties = context.scene.cookie_factory 77 | 78 | layout.label('Configuration') 79 | layout.prop(properties, 'config_filepath', text='') 80 | layout.operator('cookie_factory.import_configuration') 81 | layout.prop(properties, 'scene_name', text='') 82 | 83 | col = layout.column(align=True) 84 | col.label('Output Folder') 85 | col.prop(properties, 'output_folder') 86 | col.label('Output Name') 87 | col.prop(properties, 'output_name') 88 | 89 | layout.prop(properties, 'override') 90 | 91 | row = layout.row(align=True) 92 | row.operator('cookie_factory.render') 93 | row.operator('cookie_factory.animation') 94 | 95 | 96 | def register(): 97 | bpy.utils.register_class(ConfigurationPropertyGroup) 98 | bpy.types.Scene.cookie_factory = PointerProperty(type=ConfigurationPropertyGroup) 99 | 100 | bpy.utils.register_class(CookieFactoryPanel) 101 | logger.debug('panel registered') 102 | 103 | def unregister(): 104 | bpy.utils.unregister_class(CookieFactoryPanel) 105 | 106 | del bpy.types.Scene.cookie_factory 107 | bpy.utils.unregister_class(ConfigurationPropertyGroup) 108 | logger.debug('panel unregistered') 109 | -------------------------------------------------------------------------------- /core/materials.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN LGPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 3 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this library; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END LGPL LICENSE BLOCK ##### 20 | 21 | 22 | import bpy 23 | from mathutils import Color 24 | 25 | 26 | def glass_material(diffuse_color=(0.28, 0.51, 0.8), specular_color=(0.55, 0.91, 1.0), ior=1.4): 27 | mat = bpy.data.materials.new('GlassMaterial') 28 | 29 | # Diffuse 30 | mat.diffuse_shader = 'LAMBERT' 31 | mat.diffuse_intensity = 1 32 | mat.diffuse_color = diffuse_color 33 | 34 | # Specular 35 | mat.specular_shader = 'TOON' 36 | mat.specular_intensity = 1 37 | mat.specular_toon_size = 0.2 38 | mat.specular_toon_smooth = 0 39 | mat.specular_color = specular_color 40 | 41 | # Shading 42 | mat.emit = 0.7 43 | 44 | # Transparency settings 45 | mat.use_transparency = True 46 | mat.transparency_method = 'RAYTRACE' 47 | mat.alpha = 0.1 48 | mat.raytrace_transparency.ior = ior 49 | mat.raytrace_transparency.depth = 3 50 | mat.raytrace_transparency.filter = 0 51 | mat.raytrace_transparency.falloff = 0.5 52 | mat.raytrace_transparency.depth_max = 2 53 | 54 | # Mirror settings 55 | mat.raytrace_mirror.use = True 56 | mat.raytrace_mirror.reflect_factor = 0.5 57 | mat.raytrace_mirror.fresnel = 2 58 | mat.raytrace_mirror.fresnel_factor = 1.25 59 | mat.raytrace_mirror.gloss_factor = 1 60 | 61 | return mat 62 | 63 | 64 | def glossy_falloff_material(diffuse_color): 65 | mat = bpy.data.materials.new('GlossyFalloffMaterial') 66 | 67 | # Diffuse 68 | mat.diffuse_shader = 'LAMBERT' 69 | mat.use_diffuse_ramp = True 70 | mat.diffuse_ramp.elements[0].position = 0 71 | mat.diffuse_ramp.elements[1].position = 1 72 | mat.diffuse_ramp_input = 'NORMAL' 73 | mat.diffuse_ramp_blend = 'ADD' 74 | mat.diffuse_color = diffuse_color 75 | 76 | # Specular 77 | mat.specular_shader = 'TOON' 78 | mat.specular_toon_smooth = 0 79 | mat.specular_toon_size = 0.4 80 | 81 | return mat 82 | 83 | 84 | def falloff_material_HSV(h, s=0.9, v=0.9): 85 | mat = bpy.data.materials.new('FalloffMaterial') 86 | 87 | diffuse_color = Color() 88 | diffuse_color.hsv = ((h % 1.0), s, v) 89 | 90 | # Diffuse 91 | mat.diffuse_shader = 'LAMBERT' 92 | mat.use_diffuse_ramp = True 93 | mat.diffuse_ramp_input = 'NORMAL' 94 | mat.diffuse_ramp_blend = 'ADD' 95 | mat.diffuse_ramp.elements[0].color = (1, 1, 1, 1) 96 | mat.diffuse_ramp.elements[1].color = (1, 1, 1, 0) 97 | mat.diffuse_color = diffuse_color 98 | mat.diffuse_intensity = 1.0 99 | 100 | # Specular 101 | mat.specular_intensity = 0.0 102 | 103 | # Shading 104 | mat.emit = 0.05 105 | mat.translucency = 0.2 106 | 107 | return mat 108 | 109 | 110 | def falloff_material(diffuse_color, diffuse_intensity=1.0, emit=0.05, translucency=0.2): 111 | mat = bpy.data.materials.new('FalloffMaterial') 112 | 113 | # Diffuse 114 | mat.diffuse_shader = 'LAMBERT' 115 | mat.use_diffuse_ramp = True 116 | mat.diffuse_ramp_input = 'NORMAL' 117 | mat.diffuse_ramp_blend = 'ADD' 118 | mat.diffuse_ramp.elements[0].color = (1, 1, 1, 1) 119 | mat.diffuse_ramp.elements[1].color = (1, 1, 1, 0) 120 | mat.diffuse_color = diffuse_color 121 | mat.diffuse_intensity = diffuse_intensity 122 | 123 | # Specular 124 | mat.specular_intensity = 0.0 125 | 126 | # Shading 127 | mat.emit = emit 128 | mat.translucency = translucency 129 | 130 | return mat 131 | 132 | 133 | def dark_glass_material(ior=1.3): 134 | mat = bpy.data.materials.new('DarkGlassMaterial') 135 | 136 | # Diffuse 137 | mat.diffuse_shader = 'LAMBERT' 138 | mat.diffuse_intensity = 1 139 | mat.diffuse_color = (0, 0, 0) 140 | 141 | # Specular 142 | mat.specular_intensity = 0.0 143 | 144 | # Transparency settings 145 | mat.use_transparency = True 146 | mat.transparency_method = 'RAYTRACE' 147 | mat.alpha = 0.0 148 | mat.raytrace_transparency.ior = ior 149 | 150 | return mat 151 | 152 | 153 | def material(diffuse_color, diffuse_shader='LAMBERT', diffuse_intensity=0.9, emit=0.0): 154 | mat = bpy.data.materials.new('Material') 155 | 156 | # Diffuse 157 | mat.diffuse_shader = diffuse_shader 158 | mat.diffuse_intensity = diffuse_intensity 159 | mat.diffuse_color = diffuse_color 160 | 161 | # Specular 162 | mat.specular_intensity = 0 163 | 164 | mat.emit = emit 165 | 166 | return mat 167 | -------------------------------------------------------------------------------- /core/scene/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN LGPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 3 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this library; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END LGPL LICENSE BLOCK ##### 20 | 21 | 22 | from mathutils import Vector 23 | import sys 24 | import shutil 25 | import os 26 | import subprocess 27 | import time 28 | import logging 29 | import bpy 30 | 31 | logger = logging.getLogger(__name__) 32 | 33 | 34 | class Scene(object): 35 | log = logging.getLogger('scene.Scene') 36 | 37 | def __init__(self, context): 38 | self.log.debug('__init__ called') 39 | 40 | cf = context.scene.cookie_factory 41 | self.in_blender = not bpy.app.background 42 | self.cwd = os.path.dirname(cf.config_filepath) 43 | 44 | # Set to object mode 45 | if context.active_object and context.active_object.mode == 'EDIT': 46 | bpy.ops.object.mode_set(mode='OBJECT', toggle=False) 47 | 48 | # Reset World setting 49 | world = context.scene.world 50 | world.light_settings.use_ambient_occlusion = False 51 | world.light_settings.ao_blend_type = 'ADD' 52 | world.light_settings.samples = 5 53 | world.mist_settings.use_mist = False 54 | world.horizon_color = (0.051, 0.051, 0.051) 55 | 56 | # Clear frame handlers 57 | bpy.app.handlers.frame_change_pre.clear() 58 | bpy.app.handlers.render_pre.clear() 59 | 60 | # Clear all objects and corresponding data 61 | for scene in bpy.data.scenes: 62 | for obj in scene.objects: 63 | scene.objects.unlink(obj) 64 | 65 | bpy_data_types = [bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, bpy.data.materials, bpy.data.curves] 66 | for bpy_data in bpy_data_types: 67 | for id_data in bpy_data: 68 | if id_data.users > 0: 69 | id_data.user_clear() 70 | bpy_data.remove(id_data) 71 | 72 | # Set current frame and number of frames 73 | self.frame = context.scene.frame_current 74 | self.frames = context.scene.frame_end 75 | 76 | self.setup() 77 | 78 | # Set frame_change_pre or render_pre handler 79 | if self.in_blender: 80 | bpy.app.handlers.frame_change_pre.append( 81 | self.__frameChangeHandler) 82 | else: 83 | bpy.app.handlers.render_pre.append( 84 | self.__frameChangeHandler) 85 | 86 | 87 | def __frameChangeHandler(self, scene): 88 | if (not self.in_blender) and (scene.frame_current > scene.frame_end): 89 | bpy.ops.wm.quit_blender() 90 | 91 | self.log.info("frameChangeHandler frame : {}/{}".format( 92 | scene.frame_current, scene.frame_end)) 93 | 94 | self.frame = scene.frame_current 95 | self.frames = scene.frame_end 96 | if self.frame < 1: 97 | self.frame = 1 98 | 99 | if self.frame >= self.frames: 100 | self.frame = self.frames 101 | 102 | self.draw() 103 | 104 | 105 | # Main methods of Scene 106 | def setup(self): 107 | raise NotImplementedError() 108 | 109 | def draw(self): 110 | pass 111 | 112 | 113 | class BmeshAnimation(object): 114 | log = logging.getLogger('scene.BmeshAnimation') 115 | 116 | def __init__(self, composition, frame_function=None, single_frame=True): 117 | self.bmList = None 118 | self.frame_function = frame_function 119 | self.composition = composition 120 | 121 | # Create object and mesh for scene 122 | self.mesh = bpy.data.meshes.new("AnimationObjectMesh") 123 | self.obj = bpy.data.objects.new("AnimationObject", self.mesh) 124 | bpy.context.scene.objects.link(self.obj) 125 | 126 | # Precompute all the geometry 127 | if not single_frame: 128 | self.bmList = [] 129 | for frame in range(self.composition.frames): 130 | self.log.debug("Calculating geometry for frame %03i/%03i" % \ 131 | (frame + 1, self.composition.frames)) 132 | self.bmList.append(self.frame_function(frame, self.composition.frames)) 133 | 134 | # Set frame_change_pre or render_prehandler 135 | if composition.in_blender: 136 | bpy.app.handlers.frame_change_pre.append(self.__frameChangeHandler) 137 | else: 138 | bpy.app.handlers.render_pre.append(self.__frameChangeHandler) 139 | 140 | def __frameChangeHandler(self, scene): 141 | frame = bpy.context.scene.frame_current - 1 142 | 143 | # Clip frame number 144 | if(frame < 1): 145 | frame = 1 146 | if(frame >= self.composition.frames): 147 | frame = self.composition.frames 148 | 149 | if(self.bmList): 150 | bm = self.bmList[frame] 151 | bm.to_mesh(self.mesh) 152 | self.mesh.update() 153 | else: 154 | bm = self.frame_function(frame, self.composition.frames) 155 | bm.to_mesh(self.mesh) 156 | self.mesh.update() 157 | bm.free() 158 | 159 | def append_material(self, mat): 160 | self.obj.data.materials.append(mat) 161 | -------------------------------------------------------------------------------- /core/LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This program is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation; either version 3 8 | # of the License, or (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | 21 | 22 | import os 23 | import sys 24 | import json 25 | import time 26 | import importlib 27 | import logging 28 | import random 29 | 30 | from . import panel 31 | from . import core 32 | 33 | if "bpy" in locals(): 34 | importlib.reload(panel) 35 | importlib.reload(core) 36 | 37 | import bpy 38 | from bpy_extras.io_utils import ImportHelper, ExportHelper 39 | from bpy.app.handlers import persistent 40 | 41 | logging.basicConfig(level=logging.DEBUG, 42 | format='%(levelname)s:%(name)s:%(message)s') 43 | logger = logging.getLogger(__name__) 44 | 45 | 46 | bl_info = { 47 | 'name': 'Cookie Factory', 48 | 'author': 'Nikolai Janakiev (njanakiev)', 49 | 'version': (0, 1, 0), 50 | 'blender': (2, 78, 0), 51 | 'location': 'View3D > Tool Shelf > Cookie Factory', 52 | 'description': 'Processing-style coding in Blender', 53 | 'warning': '', 54 | 'wiki_url': '', 55 | 'tracker_url': '', 56 | 'category': 'Development' 57 | } 58 | 59 | 60 | class ImportConfigurations(bpy.types.Operator): 61 | bl_label = 'Import / Reload' 62 | bl_idname = 'cookie_factory.import_configuration' 63 | log = logging.getLogger('bpy.ops.%s' % bl_idname) 64 | 65 | def execute(self, context): 66 | cf = context.scene.cookie_factory 67 | self.log.debug('Import configuraton file : {}'.format( 68 | cf.config_filepath)) 69 | 70 | import_configuration(context.scene, cf.config_filepath) 71 | 72 | return {'FINISHED'} 73 | 74 | 75 | class CookieFactoryRender(bpy.types.Operator): 76 | bl_label = 'Render' 77 | bl_idname = 'cookie_factory.render' 78 | log = logging.getLogger('bpy.ops.%s' % bl_idname) 79 | 80 | def execute(self, context): 81 | render(context.scene) 82 | return {'FINISHED'} 83 | 84 | 85 | class CookieFactoryAnimation(bpy.types.Operator): 86 | bl_label = 'Animation' 87 | bl_idname = 'cookie_factory.animation' 88 | log = logging.getLogger('bpy.ops.%s' % bl_idname) 89 | 90 | def execute(self, context): 91 | render(context.scene, animation=True) 92 | return {'FINISHED'} 93 | 94 | 95 | def import_configuration(scene, filepath): 96 | logger.debug('import_configuration called') 97 | if os.path.splitext(filepath)[1] != '.json': 98 | raise ValueError('Only JSON files allowed') 99 | 100 | with open(filepath, 'r') as f: 101 | config = json.load(f) 102 | 103 | cwd = os.path.dirname(__file__) 104 | sys.path.append(cwd) 105 | 106 | scene_folder = os.path.dirname(filepath) 107 | if scene_folder not in sys.path: 108 | sys.path.append(scene_folder) 109 | 110 | scene_names = [] 111 | if 'scene' in config: 112 | scene_name = config['scene'] 113 | scene_names.append(scene_name) 114 | else: 115 | scene_idx = 0 116 | if 'scene_idx' in config and 'scenes' in config: 117 | scene_idx = config['scene_idx'] 118 | scene_name = config['scenes'][scene_idx] 119 | scene_names = config['scenes'] 120 | elif 'scenes' in config: 121 | scene_name = config['scenes'][0] 122 | scene_names = config['scenes'] 123 | else: 124 | raise ValueError('Configuraton not valid') 125 | 126 | # Get cookie_factory configuration 127 | cf = scene.cookie_factory 128 | 129 | # Set render stamp 130 | if 'render_stamp' in config: 131 | title = "Render" 132 | detailed = False 133 | foreground, background = (0, 0, 0, 1), (1, 1, 1, 0) 134 | font_size = 10 135 | 136 | if 'title' in config['render_stamp']: 137 | title = config['render_stamp']['title'] 138 | if 'detailed' in config['render_stamp']: 139 | detailed = config['render_stamp']['detailed'] 140 | if 'background' in config['render_stamp']: 141 | background = tuple(config['render_stamp']['background']) 142 | if 'foreground' in config['render_stamp']: 143 | foreground = tuple(config['render_stamp']['foreground']) 144 | if 'font_size' in config['render_stamp']: 145 | font_size = config['render_stamp']['font_size'] 146 | core.render_stamp(title, detailed, foreground, background, font_size) 147 | else: 148 | scene.render.use_stamp = False 149 | 150 | # Set number of used threads 151 | if 'threads' in config: 152 | scene.render.threads_mode = 'FIXED' 153 | scene.render.threads = config['threads'] 154 | 155 | # Set render engine 156 | if 'cycles' in config: 157 | if config['cycles']: 158 | bpy.context.scene.render.engine = 'CYCLES' 159 | else: 160 | bpy.context.scene.render.engine = 'BLENDER_RENDER' 161 | 162 | # Set render resolution 163 | width, height, percentage = 800, 800, 100 164 | if 'resolution' in config: 165 | if 'width' in config['resolution']: 166 | width = config['resolution']['width'] 167 | if 'height' in config['resolution']: 168 | height = config['resolution']['height'] 169 | if 'percentage' in config['resolution']: 170 | percentage = config['resolution']['percentage'] 171 | rnd = scene.render 172 | rnd.resolution_x, rnd.resolution_y = width, height 173 | rnd.resolution_percentage = percentage 174 | 175 | if 'output_folder' in config: 176 | cf.output_folder = config['output_folder'] 177 | if 'output_name' in config: 178 | cf.output_name = config['output_name'] 179 | else: 180 | cf.output_name = scene_name.split('.')[-1] 181 | if 'override' in config: 182 | cf.override = config['override'] 183 | if 'animation' in config: 184 | frame_start, frame_end = 1, 100 185 | if 'frames' in config['animation']: 186 | frame_end = config['animation']['frames'] 187 | if 'frame_start' in config['animation']: 188 | frame_start = config['animation']['frame_start'] 189 | if 'frame_end' in config['animation']: 190 | frame_end = config['animation']['frame_end'] 191 | 192 | # Set number of frames 193 | scene.frame_start = frame_start 194 | scene.frame_current = frame_start 195 | scene.frame_end = frame_end 196 | scene.frame_step = 1 197 | 198 | # Add scenes 199 | cf.scene_names.clear() 200 | for name in scene_names: 201 | item = cf.scene_names.add() 202 | item.name = name 203 | 204 | # Set scene (this calls the execute function) 205 | cf.scene_name = scene_name 206 | 207 | 208 | def render(scene, animation=False): 209 | logger.debug('render called') 210 | 211 | cf = scene.cookie_factory 212 | scene_folder = os.path.dirname(cf.config_filepath) 213 | 214 | if animation: 215 | if cf.override: 216 | filepath = os.path.join(scene_folder, 217 | cf.output_name, 'frame_') 218 | else: 219 | output_folder = lambda idx : \ 220 | os.path.join(os.getcwd(), 221 | scene_folder, 222 | cf.output_folder, 223 | '{}_{:04d}'.format(cf.output_name, idx)) 224 | i = 0 225 | while(os.path.exists(output_folder(i))): i += 1 226 | filepath = os.path.join(output_folder(i), 'frame_') 227 | else: 228 | if cf.override: 229 | filepath = os.path.join(scene_folder, 230 | cf.output_folder, 'frame_') 231 | else: 232 | output_file = lambda idx : \ 233 | os.path.join(os.getcwd(), 234 | scene_folder, 235 | cf.output_folder, 236 | '{}_{:04d}.png'.format(cf.output_name, idx)) 237 | i = 0 238 | logger.debug('Filepath : {}'.format(output_file(i))) 239 | 240 | while os.path.exists(output_file(i)): 241 | logger.debug('exits') 242 | i = i + 1 243 | 244 | filepath = output_file(i) 245 | logger.debug('Filepath : {}'.format(filepath)) 246 | 247 | bpy.context.scene.render.filepath = filepath 248 | bpy.ops.render.render(animation=animation, write_still=True) 249 | 250 | 251 | @persistent 252 | def run_background(scene): 253 | logger.debug('run_background called') 254 | 255 | if run_background in bpy.app.handlers.render_pre: 256 | bpy.app.handlers.render_pre.remove(run_background) 257 | 258 | # Read arguments 259 | if "--" not in sys.argv: 260 | argv = [] # as if no args are passed 261 | else: 262 | blender_argv = sys.argv[:sys.argv.index('--')] 263 | argv = sys.argv[sys.argv.index('--') + 1:] # get args after '--' 264 | if len(argv) < 1: 265 | raise ValueError('No filepath to configuration file given') 266 | filepath = argv[0] 267 | 268 | import_configuration(scene, filepath) 269 | 270 | # Rerun render_pre handlers 271 | for handler in bpy.app.handlers.render_pre: 272 | handler(scene) 273 | 274 | if ('-a' in blender_argv) or ('--render-anim' in blender_argv): 275 | render(scene, animation=True) 276 | bpy.ops.wm.quit_blender() 277 | 278 | elif ('-f' in blender_argv) or ('--render-frame' in blender_argv): 279 | render(scene) 280 | bpy.ops.wm.quit_blender() 281 | 282 | 283 | def register(): 284 | logger.debug('register called') 285 | 286 | panel.register() 287 | bpy.utils.register_class(ImportConfigurations) 288 | bpy.utils.register_class(CookieFactoryRender) 289 | bpy.utils.register_class(CookieFactoryAnimation) 290 | 291 | # Register handler when Blender is run in background 292 | if bpy.app.background: 293 | bpy.app.handlers.render_pre.append(run_background) 294 | 295 | 296 | def unregister(): 297 | logger.debug('unregister called') 298 | 299 | panel.unregister() 300 | bpy.utils.unregister_class(ImportConfigurations) 301 | bpy.utils.unregister_class(CookieFactoryRender) 302 | bpy.utils.unregister_class(CookieFactoryAnimation) 303 | 304 | 305 | if __name__ == '__main__': 306 | register() 307 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN LGPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 3 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this library; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END LGPL LICENSE BLOCK ##### 20 | 21 | 22 | from . import geometry 23 | from . import materials 24 | from . import scene 25 | 26 | import bpy 27 | import bmesh 28 | from mathutils import Color 29 | from math import sin 30 | import logging 31 | 32 | logger = logging.getLogger(__name__) 33 | 34 | 35 | # map, constrain from: https://github.com/processing/processing/blob/master/core%2Fsrc%2Fprocessing%2Fcore%2FPApplet.java 36 | def map_range(value, start1, stop1, start2, stop2): 37 | return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)) 38 | 39 | def constrain(t, a, b): 40 | return (t if a < t else a) if t < b else b 41 | 42 | def sin_range(phi, a, b): 43 | return (0.5*sin(phi) + 0.5)*(b - a) + a 44 | 45 | 46 | def track_to_constraint(obj, name, target, track_axis='TRACK_NEGATIVE_Z', up_axis='UP_Y', owner_space='LOCAL', target_space='LOCAL'): 47 | cns = obj.constraints.new('TRACK_TO') 48 | cns.name = name 49 | cns.target = target 50 | cns.track_axis = track_axis 51 | cns.up_axis = up_axis 52 | cns.owner_space = owner_space 53 | cns.target_space = target_space 54 | 55 | 56 | def empty(location=(0,0,0)): 57 | empty = bpy.data.objects.new('Empty', None) 58 | empty.location = location 59 | bpy.context.scene.objects.link(empty) 60 | return empty 61 | 62 | 63 | def camera(location, target=None, lens=35, clip_start=0.1, clip_end=200): 64 | # Create object and camera 65 | cam = bpy.data.cameras.new("Camera") 66 | cam.lens = lens 67 | cam.clip_start = clip_start 68 | cam.clip_end = clip_end 69 | obj = bpy.data.objects.new("CameraObj", cam) 70 | obj.location = location 71 | # Link object to scene 72 | bpy.context.scene.objects.link(obj) 73 | 74 | if target: track_to_constraint(obj, 'TrackConstraint', target) 75 | 76 | # Make this the current camera 77 | bpy.context.scene.camera = obj 78 | return obj 79 | 80 | 81 | def lamp(location, type='POINT', energy=1, color=(1,1,1), target=None): 82 | # Lamp types: 'POINT', 'SUN', 'SPOT', 'HEMI', 'AREA' 83 | lamp = bpy.data.lamps.new('Lamp', type=type) 84 | lamp.energy = energy 85 | lamp.color = color 86 | 87 | obj = bpy.data.objects.new("CameraObj", lamp) 88 | obj.location = location 89 | bpy.context.scene.objects.link(obj) 90 | 91 | if target: track_to_constraint(obj, 'TrackConstraint', target) 92 | return obj 93 | 94 | 95 | def simple_scene(target_location, camera_location, sun_location, lens=35): 96 | target = empty(target_location) 97 | cam = camera(camera_location, target, lens) 98 | sun = lamp(sun_location, 'SUN', target=target) 99 | 100 | return target, cam, sun 101 | 102 | 103 | def recalc_face_normals(obj): 104 | bm = bmesh.new() 105 | bm.from_mesh(obj.data) 106 | bmesh.ops.recalc_face_normals(bm, faces=bm.faces) 107 | bm.to_mesh(obj.data) 108 | bm.free() 109 | 110 | 111 | def smooth_object(obj, smooth=True, subsurf=False, levels=2, render_levels=3): 112 | mesh = obj.data 113 | for p in mesh.polygons: 114 | p.use_smooth = smooth 115 | 116 | if subsurf: 117 | modifier = obj.modifiers.new('Subsurf', 'SUBSURF') 118 | modifier.levels = levels 119 | modifier.render_levels = render_levels 120 | 121 | 122 | def edge_split(obj, use_edge_angle=True, use_edge_sharp=True, split_angle=0.5236): 123 | modifier = obj.modifiers.new('EdgeSplit', 'EDGE_SPLIT') 124 | modifier.use_edge_angle = use_edge_angle 125 | modifier.use_edge_sharp = use_edge_sharp 126 | modifier.split_angle = split_angle 127 | 128 | 129 | def remove_object(obj): 130 | if obj.type == 'MESH': 131 | if obj.data.name in bpy.data.meshes: 132 | bpy.data.meshes.remove(obj.data) 133 | if obj.name in bpy.context.scene.objects: 134 | bpy.context.scene.objects.unlink(obj) 135 | bpy.data.objects.remove(obj) 136 | else: 137 | raise NotImplementedError('Other types not implemented yet besides \'MESH\'') 138 | 139 | 140 | def remove_all(type=None): 141 | # Possible type: ‘MESH’, ‘CURVE’, ‘SURFACE’, ‘META’, ‘FONT’, ‘ARMATURE’, ‘LATTICE’, ‘EMPTY’, ‘CAMERA’, ‘LAMP’ 142 | if type: 143 | if type == 'MESH': 144 | for obj in bpy.data.objects: 145 | if obj.type == 'MESH': 146 | if obj.name in bpy.context.scene.objects: 147 | bpy.context.scene.objects.unlink(obj) 148 | bpy.data.objects.remove(obj) 149 | for mesh in bpy.data.meshes: 150 | bpy.data.meshes.remove(mesh) 151 | elif type == 'CURVE': 152 | for obj in bpy.data.objects: 153 | if obj.type == 'CURVE': 154 | if obj.name in bpy.context.scene.objects: 155 | bpy.context.scene.objects.unlink(obj) 156 | bpy.data.objects.remove(obj) 157 | for curve in bpy.data.curves: 158 | bpy.data.curves.remove(curve) 159 | else: 160 | bpy.ops.object.select_all(action='DESELECT') 161 | bpy.ops.object.select_by_type(type=type) 162 | bpy.ops.object.delete() 163 | else: 164 | # Remove all elements in scene 165 | for obj in bpy.data.objects: 166 | if obj.name in bpy.context.scene.objects: 167 | bpy.context.scene.objects.unlink(obj) 168 | bpy.data.objects.remove(obj) 169 | 170 | for mesh in bpy.data.meshes: bpy.data.meshes.remove(mesh) 171 | for lamp in bpy.data.lamps: bpy.data.lamps.remove(lamp) 172 | for cam in bpy.data.cameras: bpy.data.cameras.remove(cam) 173 | for mat in bpy.data.materials: bpy.data.materials.remove(mat) 174 | for tex in bpy.data.textures: bpy.data.textures.remove(tex) 175 | for curve in bpy.data.curves: bpy.data.curves.remove(curve) 176 | 177 | 178 | def world_settings(ao=False, samples=5, blend_type='ADD', horizon_color=(0.051, 0.051, 0.051), use_mist=False): 179 | # TODO reset all world settings 180 | bpy.context.scene.world.light_settings.use_ambient_occlusion = ao 181 | bpy.context.scene.world.light_settings.ao_blend_type = blend_type 182 | bpy.context.scene.world.light_settings.samples = samples 183 | bpy.context.scene.world.mist_settings.use_mist = use_mist 184 | bpy.context.scene.world.horizon_color = horizon_color 185 | 186 | 187 | def ambient_occlusion(ambient_occulusion=True, samples=5, blend_type = 'ADD'): 188 | # blend_type options: 'ADD', 'MULTIPLY' 189 | bpy.context.scene.world.light_settings.use_ambient_occlusion = ambient_occulusion 190 | bpy.context.scene.world.light_settings.ao_blend_type = blend_type 191 | bpy.context.scene.world.light_settings.samples = samples 192 | 193 | 194 | def background_color(horizon_color=(0.051, 0.051, 0.051), zenith_color=(0.01, 0.01, 0.01), ambient_color=(0,0,0), paper_sky=True, blend_sky=False, real_sky=False): 195 | # Horizon Color: RGB color at the horizon 196 | # Zenith Color : RGB color at the zenith (overhead) 197 | scn = bpy.context.scene 198 | scn.world.horizon_color = horizon_color 199 | scn.world.zenith_color = zenith_color 200 | scn.world.ambient_color = ambient_color 201 | 202 | # horizon is clipped in the image 203 | scn.world.use_sky_paper = paper_sky 204 | # background color is blended from horizon to zenith 205 | scn.world.use_sky_blend = blend_sky 206 | # gradient has two transitions: nadir to horizon to zenith 207 | scn.world.use_sky_real = real_sky 208 | 209 | 210 | def background_color_HSV(horizon_color=(0.0, 0.0, 0.051), zenith_color=(0, 0, 0.01), ambient_color=(0,0,0), paper_sky=True, blend_sky=False, real_sky=False): 211 | h, z, a = Color(), Color(), Color() 212 | h.hsv = horizon_color 213 | z.hsv = zenith_color 214 | a.hsv = ambient_color 215 | background(h, z, a, paper_sky, blend_sky, real_sky) 216 | 217 | 218 | def cycles(cycles=True): 219 | if(cycles): 220 | bpy.context.scene.render.engine = 'CYCLES' 221 | else: 222 | bpy.context.scene.render.engine = 'BLENDER_RENDER' 223 | 224 | 225 | def shadow_plane(location=(0,0,0), size=10): 226 | bpy.ops.mesh.primitive_plane_add(radius=size, location=location) 227 | obj = bpy.context.object 228 | 229 | mat = bpy.data.materials.new("OnlyShadowMaterial") 230 | mat.use_transparency = True 231 | mat.use_only_shadow = True 232 | 233 | obj.data.materials.append(mat) 234 | 235 | return obj 236 | 237 | 238 | def mist(intensity=0, start=5, depth=25, height=0, falloff='QUADRATIC', mist=True): 239 | # Falloff options: 'QUADRATIC', 'LINEAR', 'INVERSE_QUADRATIC' 240 | bpy.context.scene.world.mist_settings.use_mist = mist 241 | bpy.context.scene.world.mist_settings.intensity = intensity 242 | bpy.context.scene.world.mist_settings.start = start 243 | bpy.context.scene.world.mist_settings.depth = depth 244 | bpy.context.scene.world.mist_settings.height = height 245 | bpy.context.scene.world.mist_settings.falloff = falloff 246 | 247 | 248 | def shapekey_animation(obj, data, verbose=False): 249 | # modified from http://blender.stackexchange.com/questions/36902/how-to-keyframe-mesh-vertices-in-python 250 | for i_frame in range(bpy.context.scene.frame_end): 251 | if(verbose): logger.debug("Shapekey for frame %i" % (i_frame + 1)) 252 | 253 | block = obj.shape_key_add(name=str(i_frame), from_mix=False) # returns a key_blocks member 254 | block.value = 1.0 255 | block.mute = True 256 | 257 | # Iterate for each frame 258 | for (vert, co) in zip(block.data, data[i_frame]): 259 | vert.co = co 260 | 261 | # keyframe off on frame zero 262 | block.mute = True 263 | block.keyframe_insert(data_path='mute', frame=0, index=-1) 264 | 265 | block.mute = False 266 | block.keyframe_insert(data_path='mute', frame=i_frame + 1, index=-1) 267 | 268 | block.mute = True 269 | block.keyframe_insert(data_path='mute', frame=i_frame + 2, index=-1) 270 | 271 | 272 | def gamma_correction(color, is256=False): 273 | if is256: 274 | return tuple(pow(float(c)/255, 2.2) for c in color) 275 | else: 276 | return tuple(pow(c, 2.2) for c in color) 277 | 278 | 279 | def render_stamp(text, detailed=False, foreground=(0, 0, 0, 1), background=(1, 1, 1, 0), font_size=10): 280 | scn = bpy.context.scene 281 | scn.render.use_stamp = True 282 | scn.render.use_stamp_note = True 283 | scn.render.stamp_note_text = text 284 | scn.render.stamp_font_size = font_size 285 | 286 | # Settings for all the elements which should be displayed 287 | scn.render.use_stamp_camera = False 288 | scn.render.use_stamp_time = False 289 | scn.render.use_stamp_scene = False 290 | scn.render.use_stamp_filename = False 291 | scn.render.use_stamp_frame = False 292 | scn.render.use_stamp_lens = False 293 | scn.render.use_stamp_marker = False 294 | scn.render.use_stamp_sequencer_strip = False 295 | scn.render.use_stamp_date = detailed 296 | scn.render.use_stamp_render_time = detailed 297 | 298 | # Color settings, add alpha value if missing 299 | if(len(foreground) == 3): foreground = tuple(foreground) + (1,) 300 | if(len(background) == 3): background = tuple(background) + (0,) 301 | 302 | scn.render.stamp_foreground = foreground 303 | scn.render.stamp_background = background 304 | -------------------------------------------------------------------------------- /core/geometry.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN LGPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2018 Nikolai Janakiev 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 3 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this library; if not, write to the Free Software Foundation, 17 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | # 19 | # ##### END LGPL LICENSE BLOCK ##### 20 | 21 | 22 | import bpy 23 | import bmesh 24 | from mathutils import Vector, Matrix, Color 25 | from mathutils.noise import random_unit_vector 26 | from math import sin, cos, tan, asin, acos, atan2, pi 27 | PI, TAU = pi, 2*pi 28 | import numpy as np 29 | import logging 30 | 31 | logger = logging.getLogger(__name__) 32 | 33 | 34 | def map_range(value, start1, stop1, start2, stop2): 35 | return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)) 36 | 37 | 38 | def uv_from_vector(vector): 39 | x, y, z = vector.normalized() 40 | phi, theta = atan2(y, x), asin(z) 41 | u, v = (phi + PI)/TAU, (theta + PI/2)/PI 42 | 43 | return u, v 44 | 45 | 46 | def get_frame(p, as_matrix=False): 47 | p = Vector(p) 48 | N = p.normalized() 49 | B = N.cross((0, 0, -1)) 50 | if(B.length == 0): 51 | B, T = Vector((1, 0, 0)), Vector((0, 1, 0)) 52 | else: 53 | B.normalize() 54 | T = N.cross(B).normalized() 55 | 56 | if as_matrix: 57 | return Matrix([T, B, N]).to_4x4().transposed() 58 | else: 59 | return T, N, B 60 | 61 | 62 | def random_orientation_matrix(size=4): 63 | if size == 2: 64 | V = random_unit_vector(2) 65 | N = Vector((V.y, -V.x)) 66 | return Matrix([V, N]) 67 | 68 | N, V = random_unit_vector(), random_unit_vector() 69 | E1 = N.cross(V).normalized() 70 | E2 = N.cross(E1).normalized() 71 | if(N.length == 0 or E1.length == 0 or E2.length == 0): 72 | return random_orientation_matrix() 73 | 74 | if size == 3: 75 | return Matrix([E1, E2, N]) 76 | elif size == 4: 77 | return Matrix([E1, E2, N]).to_4x4() 78 | else: 79 | raise ValueError('can only return 2x2, 3x3 or 4x4 matrix') 80 | 81 | 82 | def icosphere_mesh(bm, location=(0, 0, 0), diameter=1.0, subdivisions=1, material_index=0, smooth=False, matrix=Matrix()): 83 | M = Matrix.Translation(location) * matrix 84 | verts = bmesh.ops.create_icosphere(bm, diameter=diameter, subdivisions=subdivisions, matrix=M)['verts'] 85 | if material_index != 0 or smooth == True: 86 | for vert in verts: 87 | for face in vert.link_faces: 88 | face.material_index = material_index 89 | face.smooth = smooth 90 | 91 | 92 | def icosphere(location=(0, 0, 0), diameter=1.0, subdivisions=1, matrix=Matrix()): 93 | # Create an empty mesh and the object 94 | mesh = bpy.data.meshes.new('Icosphere') 95 | obj = bpy.data.objects.new('Icosphere', mesh) 96 | 97 | # Add the object to the scene 98 | bpy.context.scene.objects.link(obj) 99 | obj.location = location 100 | 101 | # Construct bmesh cube and assign it to blender mesh 102 | bm = bmesh.new() 103 | bmesh.ops.create_icosphere(bm, diameter=diameter, matrix=matrix) 104 | bm.to_mesh(mesh) 105 | bm.free() 106 | 107 | return obj 108 | 109 | 110 | def cube_mesh(bm, location=(0, 0, 0), size=1.0, material_index=0, matrix=Matrix()): 111 | M = Matrix.Translation(location) * matrix 112 | verts = bmesh.ops.create_cube(bm, size=size, matrix=M)['verts'] 113 | if material_index != 0: 114 | for vert in verts: 115 | for face in vert.link_faces: 116 | face.material_index = material_index 117 | 118 | 119 | def cube(location=(0, 0, 0), size=1.0, matrix=Matrix()): 120 | # Create an empty mesh and the object 121 | mesh = bpy.data.meshes.new('Cube') 122 | obj = bpy.data.objects.new('Cube', mesh) 123 | 124 | # Add the object to the scene 125 | bpy.context.scene.objects.link(obj) 126 | obj.location = location 127 | 128 | # Construct bmesh cube and assign it to blender mesh 129 | bm = bmesh.new() 130 | bmesh.ops.create_cube(bm, size=size, matrix=matrix) 131 | bm.to_mesh(mesh) 132 | bm.free() 133 | 134 | return obj 135 | 136 | 137 | def bmesh_to_object(bm, name='Object'): 138 | mesh = bpy.data.meshes.new(name+'Mesh') 139 | bm.to_mesh(mesh) 140 | bm.free() 141 | 142 | obj = bpy.data.objects.new(name, mesh) 143 | bpy.context.scene.objects.link(obj) 144 | bpy.context.scene.update() 145 | 146 | return obj 147 | 148 | 149 | def append_geometry(bm, verts, faceIndicesList, location=(0, 0, 0), smooth=False, material_index=0, matrix=Matrix()): 150 | if bm is None: bm = bmesh.new() 151 | 152 | vertList = [] 153 | for vert in verts: 154 | vertList.append(bm.verts.new(matrix * vert + Vector(location))) 155 | 156 | faces = [] 157 | for faceIndices in faceIndicesList: 158 | face = bm.faces.new(tuple(vertList[i] for i in faceIndices)) 159 | face.smooth = smooth 160 | face.material_index = material_index 161 | faces.append(face) 162 | 163 | bmesh.ops.recalc_face_normals(bm, faces=faces) 164 | 165 | return bm 166 | 167 | 168 | def geometry_to_object(points, faces, location=(0, 0, 0), name='Shape'): 169 | verts = points 170 | faces = [tuple(int(value) for value in face) for face in faces] 171 | 172 | # Create mesh and object 173 | mesh = bpy.data.meshes.new(name+'Mesh') 174 | obj = bpy.data.objects.new(name, mesh) 175 | obj.location = location 176 | # Link object to scene 177 | bpy.context.scene.objects.link(obj) 178 | # Create mesh from given verts and faces 179 | mesh.from_pydata(verts, [], faces) 180 | #Update mesh with new data 181 | mesh.update(calc_edges=True) 182 | return obj 183 | 184 | 185 | def circle_path(n, r, v1=(1,0,0), v2=(0,1,0), phi=0): 186 | points, directions, normals = [], [], [] 187 | v1, v2 = Vector(v1), Vector(v2) 188 | 189 | normal = v1.cross(v2) 190 | normal.normalize() 191 | 192 | for i in range(n): 193 | t = float(i)/float(n) 194 | # Calculate points on circle 195 | p = r*(v1*cos(TAU*t + phi) + v2*sin(TAU*t + phi)) 196 | points.append(p) 197 | 198 | # Calculate directions (tangents) 199 | d = -v1*sin(TAU*t + phi) + v2*cos(TAU*t + phi) 200 | directions.append(d) 201 | 202 | # Calculate the normals 203 | n0 = normal.cross(d) 204 | n0.normalize() 205 | normals.append(n0) 206 | 207 | return points, directions, normals 208 | 209 | 210 | def random_sphere_points(n, r=1): 211 | u = np.random.random((n, 1)) 212 | v = np.random.random((n, 1)) 213 | phiList = TAU*u 214 | thetaList = np.arccos(2*v - 1) + PI/2 # Uniform distribution on sphere 215 | 216 | return [Vector((r*np.cos(theta)*np.cos(phi), \ 217 | r*np.cos(theta)*np.sin(phi), \ 218 | r*np.sin(theta))) \ 219 | for (phi, theta) in zip(phiList, thetaList)] 220 | 221 | 222 | def parametric_surface_geometry(mapping, n=100, m=100, location=(0, 0, 0), uClosed=False, vClosed=False, quads=True): 223 | logger.debug('parametric_surface_geometry called') 224 | verts, faces = [], [] 225 | 226 | # Create uniform n by m grid 227 | for col in range(m): 228 | for row in range(n): 229 | u, v = row/n, col/m 230 | 231 | # Create surface 232 | p = mapping(u, v) 233 | verts.append(p) 234 | 235 | if(row < (n - (not uClosed)) and col < (m - (not vClosed))): 236 | # Connect first and last vertices on the u and v axis 237 | rowNext = (row + 1) % n 238 | colNext = (col + 1) % m 239 | if quads: 240 | faces.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext, (colNext*n) + row)) 241 | else: 242 | # Indices for first triangle 243 | faces.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 244 | # Indices for second triangle 245 | faces.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 246 | 247 | #logger.debug('verts : ' + str(len(verts))) 248 | #logger.debug('faces : ' + str(len(faces))) 249 | return verts, faces 250 | 251 | 252 | def parametric_surface(mapping, n, m, location=(0, 0, 0), uClosed=False, vClosed=False, quads=True, smooth=False, name='Surface'): 253 | logger.debug('parametric_surface called') 254 | verts, faces = parametric_surface_geometry(mapping, n, m, location, uClosed, vClosed, quads) 255 | 256 | # Create mesh 257 | mesh = bpy.data.meshes.new(name+'Mesh') 258 | # Create object 259 | obj = bpy.data.objects.new(name, mesh) 260 | obj.location = location 261 | # Link object to scene 262 | bpy.context.scene.objects.link(obj) 263 | # Create mesh from given verts and faces 264 | mesh.from_pydata(verts, [], faces) 265 | #Update mesh with new data 266 | mesh.update(calc_edges=True) 267 | 268 | # Make mesh smooth 269 | if smooth: 270 | for p in mesh.polygons: 271 | p.use_smooth = smooth 272 | 273 | return obj 274 | 275 | 276 | def parametric_surface_mesh(bm, surfaceMapping, n=10, m=10, location=(0, 0, 0), quads=True, uClosed=False, vClosed=False, smooth=False, material_index=0, matrix=Matrix()): 277 | location = Vector(location) 278 | verts, faces, faceIndicesList = [], [], [] 279 | for col in range(m): 280 | for row in range(n): 281 | u, v = float(row)/float(n - (not uClosed)), float(col)/float(m - (not vClosed)) 282 | #u, v = float(row)/float(n - 1), float(col)/float(m - 1) 283 | vert = Vector(surfaceMapping(u, v)) 284 | verts.append(bm.verts.new(matrix*vert + location)) 285 | 286 | if row < (n - (not uClosed)) and col < (m - (not vClosed)): 287 | rowNext = (row + 1) % n 288 | colNext = (col + 1) % m 289 | if quads: 290 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext, (colNext*n) + row)) 291 | else: 292 | faceIndicesList.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 293 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 294 | 295 | for faceIndices in faceIndicesList: 296 | face = bm.faces.new(tuple(verts[i] for i in faceIndices)) 297 | face.smooth = smooth 298 | face.material_index = material_index 299 | faces.append(face) 300 | 301 | bmesh.ops.recalc_face_normals(bm, faces=faces) 302 | 303 | 304 | def patch_mesh(bm, points, location=(0, 0, 0), quads=True, uClosed=False, vClosed=False, uCap=False, vCap=False, smooth=False, material_index=0, matrix=Matrix()): 305 | location = Vector(location) 306 | verts, faces, faceIndicesList = [], [], [] 307 | n, m = np.shape(points)[:2] 308 | 309 | for col in range(m): 310 | for row in range(n): 311 | vert = Vector(points[row][col]) 312 | verts.append(bm.verts.new(matrix*vert + location)) 313 | 314 | if row < (n - (not uClosed)) and col < (m - (not vClosed)): 315 | rowNext = (row + 1) % n 316 | colNext = (col + 1) % m 317 | if quads: 318 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext, (colNext*n) + row)) 319 | else: 320 | faceIndicesList.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 321 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 322 | 323 | if uCap: 324 | faceIndicesList.append(np.arange(0, n*m, n)) 325 | faceIndicesList.append(np.arange(n - 1, n*m, n)) 326 | if vCap: 327 | faceIndicesList.append(np.arange(n)) 328 | faceIndicesList.append(np.arange(n*(m - 1), n*m)) 329 | 330 | for faceIndices in faceIndicesList: 331 | face = bm.faces.new(tuple(verts[i] for i in faceIndices)) 332 | face.smooth = smooth 333 | face.material_index = material_index 334 | faces.append(face) 335 | 336 | bmesh.ops.recalc_face_normals(bm, faces=faces) 337 | 338 | 339 | def torus_surface(name, location, R0, r0, X): 340 | logger.debug('torus_surface called') 341 | verts, faces = [], [] 342 | (n, m) = np.shape(X) 343 | 344 | # Create uniform n by m grid 345 | for col in range(m): 346 | for row in range(n): 347 | u, v = row/n, col/m 348 | r = r0 + X[row, col] 349 | 350 | # Create surface 351 | p = ((R0 + r*cos(TAU*v))*cos(TAU*u), \ 352 | (R0 + r*cos(TAU*v))*sin(TAU*u), \ 353 | r*sin(TAU*v)) 354 | verts.append(p) 355 | 356 | # Connect first and last vertices on the u and v axis 357 | rowNext = (row + 1) % n 358 | colNext = (col + 1) % m 359 | # Indices for first triangle 360 | faces.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 361 | # Indices for second triangle 362 | faces.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 363 | 364 | logger.debug('verts : ' + str(len(verts))) 365 | logger.debug('faces : ' + str(len(faces))) 366 | # Create mesh and object 367 | mesh = bpy.data.meshes.new(name+'Mesh') 368 | obj = bpy.data.objects.new(name, mesh) 369 | obj.location = location 370 | # Link object to scene 371 | bpy.context.scene.objects.link(obj) 372 | # Create mesh from given verts and faces 373 | mesh.from_pydata(verts, [], faces) 374 | #Update mesh with new data 375 | mesh.update(calc_edges=True) 376 | return obj 377 | 378 | 379 | def torus_mesh(bm, R, r, n=40, m=20, location=(0, 0, 0), smooth=False, material_index=0, matrix=Matrix()): 380 | def torus(u, v): 381 | return ((R + r*cos(TAU*v))*cos(TAU*u), \ 382 | (R + r*cos(TAU*v))*sin(TAU*u), \ 383 | r*sin(TAU*v)) 384 | 385 | parametric_surface_mesh(bm, torus, n, m, location, uClosed=True, vClosed=True, smooth=smooth, material_index=material_index, matrix=matrix) 386 | 387 | 388 | def parametric_heightmap(X, extent=[-10,10,-10,10], location=(0, 0, 0), uClosed=False, vClosed=False, name='Shape'): 389 | logger.debug('parametric_heightmap called') 390 | verts = list() 391 | faces = list() 392 | 393 | # Create uniform n by m grid 394 | n, m = X.shape 395 | for row in range(n): 396 | for col in range(m): 397 | u = map_range(col/(m - 1), 0, 1, extent[0], extent[1]) 398 | v = map_range(row/(n - 1), 0, 1, extent[2], extent[3]) 399 | 400 | # Get vertices 401 | p = (u, v, X[row,col]) 402 | verts.append(p) 403 | 404 | if(row < (n - (not uClosed)) and col < (m - (not vClosed))): 405 | # Connect first and last vertices on the u and v axis 406 | rowNext = (row + 1) % n 407 | colNext = (col + 1) % m 408 | # Indices for first triangle 409 | faces.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 410 | # Indices for second triangle 411 | faces.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 412 | 413 | logger.debug('verts : ' + str(len(verts))) 414 | logger.debug('faces : ' + str(len(faces))) 415 | 416 | # Create mesh and object 417 | mesh = bpy.data.meshes.new(name+'Mesh') 418 | obj = bpy.data.objects.new(name, mesh) 419 | obj.location = location 420 | # Link object to scene 421 | bpy.context.scene.objects.link(obj) 422 | # Create mesh from given verts and faces 423 | mesh.from_pydata(verts, [], faces) 424 | #Update mesh with new data 425 | mesh.update(calc_edges=True) 426 | return obj 427 | 428 | 429 | def disc_geometry(location, n, r, h, v1=(1,0,0), v2=(0,1,0), phi=0): 430 | v1, v2 = Vector(v1), Vector(v2) 431 | normal = v1.cross(v2) 432 | normal.normalize() 433 | 434 | points, faces = [], [] 435 | 436 | h0 = location - h*normal 437 | h1 = location + h*normal 438 | points.append(h0) 439 | points.append(h1) 440 | 441 | for i in range(n): 442 | t = float(i)/float(n) 443 | p0 = h0 + r*(v1*cos(TAU*t + phi) + v2*sin(TAU*t + phi)) 444 | p1 = h1 + r*(v1*cos(TAU*t + phi) + v2*sin(TAU*t + phi)) 445 | points.append(p0) 446 | points.append(p1) 447 | 448 | idx0 = 2*i + 2 449 | idx1 = 2*i + 3 450 | iNext0 = (idx0 % (2*n)) + 2 451 | iNext1 = (idx1 % (2*n)) + 2 452 | 453 | faces.append((idx0, 0, iNext0)) 454 | faces.append((1, idx1, iNext1)) 455 | faces.append((idx1, idx0, iNext0, iNext1)) 456 | 457 | return points, faces 458 | 459 | 460 | def disc_mesh(bm, n, r, h, location=(0,0,0), e0=(1,0,0), e1=(0,1,0), normal=None, phi=0, smooth=False, material_index=0, matrix=Matrix()): 461 | location, e0, e1 = Vector(location), Vector(e0), Vector(e1) 462 | verts, faces, faceIndicesList = [], [], [] 463 | 464 | if normal is None: 465 | normal = e0.cross(e1) 466 | normal.normalize() 467 | else: 468 | normal = Vector(normal) 469 | 470 | h0 = -h*normal 471 | h1 = +h*normal 472 | verts.append(bm.verts.new(matrix*h0 + location)) 473 | verts.append(bm.verts.new(matrix*h1 + location)) 474 | 475 | for i in range(n): 476 | t = float(i)/float(n) 477 | p0 = h0 + r*(e0*cos(TAU*t + phi) + e1*sin(TAU*t + phi)) 478 | p1 = h1 + r*(e0*cos(TAU*t + phi) + e1*sin(TAU*t + phi)) 479 | verts.append(bm.verts.new(matrix*p0 + location)) 480 | verts.append(bm.verts.new(matrix*p1 + location)) 481 | 482 | idx0 = 2*i + 2 483 | idx1 = 2*i + 3 484 | iNext0 = (idx0 % (2*n)) + 2 485 | iNext1 = (idx1 % (2*n)) + 2 486 | 487 | faceIndicesList.append((idx0, 0, iNext0)) 488 | faceIndicesList.append((1, idx1, iNext1)) 489 | faceIndicesList.append((idx1, idx0, iNext0, iNext1)) 490 | 491 | for faceIndices in faceIndicesList: 492 | face = bm.faces.new(tuple(verts[i] for i in faceIndices)) 493 | face.smooth = smooth 494 | face.material_index = material_index 495 | faces.append(face) 496 | 497 | bmesh.ops.recalc_face_normals(bm, faces=faces) 498 | 499 | 500 | def cone_geometry(c0, c1, r, n, v0=None, v1=None): 501 | c0, c1 = Vector(c0), Vector(c1) 502 | verts, faces = [], [] 503 | verts.append(c0) 504 | verts.append(c1) 505 | if v0 is None and v1 is None: 506 | N = c0 - c1 507 | N.normalize() 508 | v0 = N.cross((0,0,1)) 509 | if(v0.length == 0): 510 | v0, v1 = Vector((1, 0, 0)), Vector((0, 1, 0)) 511 | else: 512 | v0.normalize() 513 | v1 = N.cross(v0) 514 | v1.normalize() 515 | else: 516 | v0, v1 = Vector(v0), Vector(v1) 517 | 518 | for i in range(n): 519 | t = float(i) / float(n) 520 | vert = c1 + r*(v0*cos(TAU*t) + v1*sin(TAU*t)) 521 | #vert = (c0 + c1)/2 + r*(v0*cos(TAU*t) + v1*sin(TAU*t)) 522 | verts.append(vert) 523 | 524 | iNext = (i + 1) % n 525 | faces.append((2+i, 0, 2+iNext)) 526 | faces.append((1, 2+i, 2+iNext)) 527 | 528 | return verts, faces 529 | 530 | 531 | def cone_mesh(bm, c0, c1, r, n=6, v0=None, v1=None, location=(0, 0, 0), material_index=0, smooth=False, matrix=Matrix()): 532 | if bm is None: bm = bmesh.new() 533 | 534 | verts, faces = cone_geometry(c0, c1, r, n, v0, v1) 535 | append_geometry(bm, verts, faces, location=location, smooth=smooth, material_index=material_index, matrix=matrix) 536 | 537 | return bm 538 | 539 | 540 | def pipe_geometry(A, B, n, r0, r1, closed=False, phi=0): 541 | points, faces = [], [] 542 | A, B = Vector(A), Vector(B) 543 | 544 | # Setup of vectors 545 | N = B - A 546 | N.normalize() 547 | F = N.cross((0,0,1)) 548 | if(F.length == 0): 549 | F, E = Vector((1, 0, 0)), Vector((0, 1, 0)) 550 | else: 551 | F.normalize() 552 | E = N.cross(F) 553 | E.normalize() 554 | 555 | if(closed): 556 | points.append(A) 557 | points.append(B) 558 | 559 | for i in range(n): 560 | t = float(i)/float(n) 561 | p0 = A + r0*(F*cos(TAU*t + phi) + E*sin(TAU*t + phi)) 562 | p1 = B + r1*(F*cos(TAU*t + phi) + E*sin(TAU*t + phi)) 563 | points.append(p0) 564 | points.append(p1) 565 | 566 | if(closed): 567 | idx0, idx1 = 2*i + 2, 2*i + 3 568 | iNext0, iNext1 = (idx0 % (2*n)) + 2, (idx1 % (2*n)) + 2 569 | faces.append((idx0, 0, iNext0)) 570 | faces.append((1, idx1, iNext1)) 571 | faces.append((idx1, idx0, iNext0, iNext1)) 572 | else: 573 | idx0, idx1 = 2*i, 2*i + 1 574 | iNext0, iNext1 = (idx0 + 2) % (2*n), (idx1 + 2) % (2*n) 575 | faces.append((idx1, idx0, iNext0, iNext1)) 576 | 577 | return points, faces 578 | 579 | 580 | def pipe_mesh(bm, A, B, r0, r1=None, n=6, closed=False, phi=0, location=(0, 0, 0), smooth=False, material_index=0, matrix=Matrix()): 581 | location = Vector(location) 582 | if r1 is None: r1 = r0 583 | 584 | verts = [] 585 | A, B = Vector(A), Vector(B) 586 | r0, r1, n = float(r0), float(r1), int(n) 587 | 588 | # Setup of vectors 589 | N = B - A 590 | N.normalize() 591 | F = N.cross((0,0,1)) 592 | if(F.length == 0): 593 | F, E = Vector((1, 0, 0)), Vector((0, 1, 0)) 594 | else: 595 | F.normalize() 596 | E = N.cross(F) 597 | E.normalize() 598 | 599 | if(closed): 600 | verts.append(bm.verts.new(matrix*A + location)) 601 | verts.append(bm.verts.new(matrix*B + location)) 602 | 603 | for i in range(n): 604 | t = float(i)/float(n) 605 | p0 = A + r0*(F*cos(TAU*t + phi) + E*sin(TAU*t + phi)) 606 | p1 = B + r1*(F*cos(TAU*t + phi) + E*sin(TAU*t + phi)) 607 | verts.append(bm.verts.new(matrix*p0 + location)) 608 | verts.append(bm.verts.new(matrix*p1 + location)) 609 | 610 | faces = [] 611 | for i in range(n): 612 | if(closed): 613 | idx0, idx1 = 2*i + 2, 2*i + 3 614 | iNext0, iNext1 = (idx0 % (2*n)) + 2, (idx1 % (2*n)) + 2 615 | vA, vB, v0, v1 = verts[0], verts[1], verts[idx0], verts[idx1] 616 | vNext0, vNext1 = verts[iNext0], verts[iNext1] 617 | 618 | for faceInidces in [(v0, vA, vNext0), (vB, v1, vNext1), (v1, v0, vNext0, vNext1)]: 619 | face = bm.faces.new(faceInidces) 620 | face.material_index = material_index 621 | face.smooth = smooth 622 | faces.append(face) 623 | else: 624 | idx0, idx1 = 2*i, 2*i + 1 625 | iNext0, iNext1 = (idx0 + 2) % (2*n), (idx1 + 2) % (2*n) 626 | v0, v1 = verts[idx0], verts[idx1] 627 | vNext0, vNext1 = verts[iNext0], verts[iNext1] 628 | 629 | face = bm.faces.new((v1, v0, vNext0, vNext1)) 630 | face.material_index = material_index 631 | face.smooth = smooth 632 | faces.append(face) 633 | 634 | bmesh.ops.recalc_face_normals(bm, faces=faces) 635 | 636 | 637 | def tube_mesh(bm, points, r=1, n=6, location=(0, 0, 0), quads=True, closed=False, smooth=False, material_index=0, matrix=Matrix()): 638 | location = Vector(location) 639 | verts, faces, faceIndicesList = [], [], [] 640 | m = len(points) 641 | 642 | for col in range(m): 643 | for row in range(n): 644 | u = float(row)/float(n) 645 | 646 | if(closed or (0 < col and col < (m - 1))): 647 | tangent = Vector(points[(col + 1) % m]) - Vector(points[col - 1]) 648 | tangent.normalize() 649 | else: 650 | if(col == 0): 651 | tangent = Vector(points[col + 1]) - Vector(points[col]) 652 | tangent.normalize() 653 | elif(col == (m - 1)): 654 | tangent = Vector(points[col]) - Vector(points[col - 1]) 655 | tangent.normalize() 656 | 657 | p = Vector(points[col]) 658 | e0 = Vector((tangent.y, -tangent.x, 0)) 659 | e0.normalize() 660 | e1 = e0.cross(tangent) 661 | point = p + r*(e0*cos(TAU*u) + e1*sin(TAU*u)) 662 | 663 | verts.append(bm.verts.new(matrix*point + location)) 664 | if(col < (m - (not closed))): 665 | rowNext = (row + 1) % n 666 | colNext = (col + 1) % m 667 | if(quads): 668 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext, (colNext*n) + row)) 669 | else: 670 | faceIndicesList.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 671 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 672 | 673 | for faceIndices in faceIndicesList: 674 | face = bm.faces.new(tuple(verts[i] for i in faceIndices)) 675 | face.smooth = smooth 676 | face.material_index = material_index 677 | faces.append(face) 678 | 679 | bmesh.ops.recalc_face_normals(bm, faces=faces) 680 | 681 | 682 | def parametric_heightmap_mesh(bm, X, extent=[-10,10,-10,10], location=(0, 0, 0), quads=True, smooth=False, uClosed=False, vClosed=False, material_index=0, matrix=Matrix()): 683 | location = Vector(location) 684 | verts, faces, faceIndicesList = [], [], [] 685 | 686 | n, m = X.shape 687 | for col in range(m): 688 | for row in range(n): 689 | u = map_range(col/(m - 1), 0, 1, extent[0], extent[1]) 690 | v = map_range(row/(n - 1), 0, 1, extent[2], extent[3]) 691 | 692 | point = Vector((u, v, X[row,col])) 693 | verts.append(bm.verts.new(matrix*point + location)) 694 | 695 | if(row < (n - (not uClosed)) and col < (m - (not vClosed))): 696 | rowNext = (row + 1) % n 697 | colNext = (col + 1) % m 698 | if(quads): 699 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext, (colNext*n) + row)) 700 | else: 701 | faceIndicesList.append(((col*n) + row, (colNext*n) + rowNext, (colNext*n) + row)) 702 | faceIndicesList.append(((col*n) + row, (col*n) + rowNext, (colNext*n) + rowNext)) 703 | 704 | for faceIndices in faceIndicesList: 705 | face = bm.faces.new(tuple(verts[i] for i in faceIndices)) 706 | face.smooth = smooth 707 | face.material_index = material_index 708 | faces.append(face) 709 | 710 | bmesh.ops.recalc_face_normals(bm, faces=faces) 711 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 by Nikolai Janakiev 2 | All rights reserved 3 | 4 | This project uses the LGPL v3 for the code within the core folder 5 | and the code within the examples folder is licensed under the MIT license. 6 | The rest of the project is licensed under the GPL v3. 7 | 8 | 9 | ------------------------------------------------------------------------ 10 | 11 | 12 | GNU GENERAL PUBLIC LICENSE 13 | Version 3, 29 June 2007 14 | 15 | Copyright (C) 2007 Free Software Foundation, Inc. 16 | Everyone is permitted to copy and distribute verbatim copies 17 | of this license document, but changing it is not allowed. 18 | 19 | Preamble 20 | 21 | The GNU General Public License is a free, copyleft license for 22 | software and other kinds of works. 23 | 24 | The licenses for most software and other practical works are designed 25 | to take away your freedom to share and change the works. By contrast, 26 | the GNU General Public License is intended to guarantee your freedom to 27 | share and change all versions of a program--to make sure it remains free 28 | software for all its users. We, the Free Software Foundation, use the 29 | GNU General Public License for most of our software; it applies also to 30 | any other work released this way by its authors. You can apply it to 31 | your programs, too. 32 | 33 | When we speak of free software, we are referring to freedom, not 34 | price. Our General Public Licenses are designed to make sure that you 35 | have the freedom to distribute copies of free software (and charge for 36 | them if you wish), that you receive source code or can get it if you 37 | want it, that you can change the software or use pieces of it in new 38 | free programs, and that you know you can do these things. 39 | 40 | To protect your rights, we need to prevent others from denying you 41 | these rights or asking you to surrender the rights. Therefore, you have 42 | certain responsibilities if you distribute copies of the software, or if 43 | you modify it: responsibilities to respect the freedom of others. 44 | 45 | For example, if you distribute copies of such a program, whether 46 | gratis or for a fee, you must pass on to the recipients the same 47 | freedoms that you received. You must make sure that they, too, receive 48 | or can get the source code. And you must show them these terms so they 49 | know their rights. 50 | 51 | Developers that use the GNU GPL protect your rights with two steps: 52 | (1) assert copyright on the software, and (2) offer you this License 53 | giving you legal permission to copy, distribute and/or modify it. 54 | 55 | For the developers' and authors' protection, the GPL clearly explains 56 | that there is no warranty for this free software. For both users' and 57 | authors' sake, the GPL requires that modified versions be marked as 58 | changed, so that their problems will not be attributed erroneously to 59 | authors of previous versions. 60 | 61 | Some devices are designed to deny users access to install or run 62 | modified versions of the software inside them, although the manufacturer 63 | can do so. This is fundamentally incompatible with the aim of 64 | protecting users' freedom to change the software. The systematic 65 | pattern of such abuse occurs in the area of products for individuals to 66 | use, which is precisely where it is most unacceptable. Therefore, we 67 | have designed this version of the GPL to prohibit the practice for those 68 | products. If such problems arise substantially in other domains, we 69 | stand ready to extend this provision to those domains in future versions 70 | of the GPL, as needed to protect the freedom of users. 71 | 72 | Finally, every program is threatened constantly by software patents. 73 | States should not allow patents to restrict development and use of 74 | software on general-purpose computers, but in those that do, we wish to 75 | avoid the special danger that patents applied to a free program could 76 | make it effectively proprietary. To prevent this, the GPL assures that 77 | patents cannot be used to render the program non-free. 78 | 79 | The precise terms and conditions for copying, distribution and 80 | modification follow. 81 | 82 | TERMS AND CONDITIONS 83 | 84 | 0. Definitions. 85 | 86 | "This License" refers to version 3 of the GNU General Public License. 87 | 88 | "Copyright" also means copyright-like laws that apply to other kinds of 89 | works, such as semiconductor masks. 90 | 91 | "The Program" refers to any copyrightable work licensed under this 92 | License. Each licensee is addressed as "you". "Licensees" and 93 | "recipients" may be individuals or organizations. 94 | 95 | To "modify" a work means to copy from or adapt all or part of the work 96 | in a fashion requiring copyright permission, other than the making of an 97 | exact copy. The resulting work is called a "modified version" of the 98 | earlier work or a work "based on" the earlier work. 99 | 100 | A "covered work" means either the unmodified Program or a work based 101 | on the Program. 102 | 103 | To "propagate" a work means to do anything with it that, without 104 | permission, would make you directly or secondarily liable for 105 | infringement under applicable copyright law, except executing it on a 106 | computer or modifying a private copy. Propagation includes copying, 107 | distribution (with or without modification), making available to the 108 | public, and in some countries other activities as well. 109 | 110 | To "convey" a work means any kind of propagation that enables other 111 | parties to make or receive copies. Mere interaction with a user through 112 | a computer network, with no transfer of a copy, is not conveying. 113 | 114 | An interactive user interface displays "Appropriate Legal Notices" 115 | to the extent that it includes a convenient and prominently visible 116 | feature that (1) displays an appropriate copyright notice, and (2) 117 | tells the user that there is no warranty for the work (except to the 118 | extent that warranties are provided), that licensees may convey the 119 | work under this License, and how to view a copy of this License. If 120 | the interface presents a list of user commands or options, such as a 121 | menu, a prominent item in the list meets this criterion. 122 | 123 | 1. Source Code. 124 | 125 | The "source code" for a work means the preferred form of the work 126 | for making modifications to it. "Object code" means any non-source 127 | form of a work. 128 | 129 | A "Standard Interface" means an interface that either is an official 130 | standard defined by a recognized standards body, or, in the case of 131 | interfaces specified for a particular programming language, one that 132 | is widely used among developers working in that language. 133 | 134 | The "System Libraries" of an executable work include anything, other 135 | than the work as a whole, that (a) is included in the normal form of 136 | packaging a Major Component, but which is not part of that Major 137 | Component, and (b) serves only to enable use of the work with that 138 | Major Component, or to implement a Standard Interface for which an 139 | implementation is available to the public in source code form. A 140 | "Major Component", in this context, means a major essential component 141 | (kernel, window system, and so on) of the specific operating system 142 | (if any) on which the executable work runs, or a compiler used to 143 | produce the work, or an object code interpreter used to run it. 144 | 145 | The "Corresponding Source" for a work in object code form means all 146 | the source code needed to generate, install, and (for an executable 147 | work) run the object code and to modify the work, including scripts to 148 | control those activities. However, it does not include the work's 149 | System Libraries, or general-purpose tools or generally available free 150 | programs which are used unmodified in performing those activities but 151 | which are not part of the work. For example, Corresponding Source 152 | includes interface definition files associated with source files for 153 | the work, and the source code for shared libraries and dynamically 154 | linked subprograms that the work is specifically designed to require, 155 | such as by intimate data communication or control flow between those 156 | subprograms and other parts of the work. 157 | 158 | The Corresponding Source need not include anything that users 159 | can regenerate automatically from other parts of the Corresponding 160 | Source. 161 | 162 | The Corresponding Source for a work in source code form is that 163 | same work. 164 | 165 | 2. Basic Permissions. 166 | 167 | All rights granted under this License are granted for the term of 168 | copyright on the Program, and are irrevocable provided the stated 169 | conditions are met. This License explicitly affirms your unlimited 170 | permission to run the unmodified Program. The output from running a 171 | covered work is covered by this License only if the output, given its 172 | content, constitutes a covered work. This License acknowledges your 173 | rights of fair use or other equivalent, as provided by copyright law. 174 | 175 | You may make, run and propagate covered works that you do not 176 | convey, without conditions so long as your license otherwise remains 177 | in force. You may convey covered works to others for the sole purpose 178 | of having them make modifications exclusively for you, or provide you 179 | with facilities for running those works, provided that you comply with 180 | the terms of this License in conveying all material for which you do 181 | not control copyright. Those thus making or running the covered works 182 | for you must do so exclusively on your behalf, under your direction 183 | and control, on terms that prohibit them from making any copies of 184 | your copyrighted material outside their relationship with you. 185 | 186 | Conveying under any other circumstances is permitted solely under 187 | the conditions stated below. Sublicensing is not allowed; section 10 188 | makes it unnecessary. 189 | 190 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 191 | 192 | No covered work shall be deemed part of an effective technological 193 | measure under any applicable law fulfilling obligations under article 194 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 195 | similar laws prohibiting or restricting circumvention of such 196 | measures. 197 | 198 | When you convey a covered work, you waive any legal power to forbid 199 | circumvention of technological measures to the extent such circumvention 200 | is effected by exercising rights under this License with respect to 201 | the covered work, and you disclaim any intention to limit operation or 202 | modification of the work as a means of enforcing, against the work's 203 | users, your or third parties' legal rights to forbid circumvention of 204 | technological measures. 205 | 206 | 4. Conveying Verbatim Copies. 207 | 208 | You may convey verbatim copies of the Program's source code as you 209 | receive it, in any medium, provided that you conspicuously and 210 | appropriately publish on each copy an appropriate copyright notice; 211 | keep intact all notices stating that this License and any 212 | non-permissive terms added in accord with section 7 apply to the code; 213 | keep intact all notices of the absence of any warranty; and give all 214 | recipients a copy of this License along with the Program. 215 | 216 | You may charge any price or no price for each copy that you convey, 217 | and you may offer support or warranty protection for a fee. 218 | 219 | 5. Conveying Modified Source Versions. 220 | 221 | You may convey a work based on the Program, or the modifications to 222 | produce it from the Program, in the form of source code under the 223 | terms of section 4, provided that you also meet all of these conditions: 224 | 225 | a) The work must carry prominent notices stating that you modified 226 | it, and giving a relevant date. 227 | 228 | b) The work must carry prominent notices stating that it is 229 | released under this License and any conditions added under section 230 | 7. This requirement modifies the requirement in section 4 to 231 | "keep intact all notices". 232 | 233 | c) You must license the entire work, as a whole, under this 234 | License to anyone who comes into possession of a copy. This 235 | License will therefore apply, along with any applicable section 7 236 | additional terms, to the whole of the work, and all its parts, 237 | regardless of how they are packaged. This License gives no 238 | permission to license the work in any other way, but it does not 239 | invalidate such permission if you have separately received it. 240 | 241 | d) If the work has interactive user interfaces, each must display 242 | Appropriate Legal Notices; however, if the Program has interactive 243 | interfaces that do not display Appropriate Legal Notices, your 244 | work need not make them do so. 245 | 246 | A compilation of a covered work with other separate and independent 247 | works, which are not by their nature extensions of the covered work, 248 | and which are not combined with it such as to form a larger program, 249 | in or on a volume of a storage or distribution medium, is called an 250 | "aggregate" if the compilation and its resulting copyright are not 251 | used to limit the access or legal rights of the compilation's users 252 | beyond what the individual works permit. Inclusion of a covered work 253 | in an aggregate does not cause this License to apply to the other 254 | parts of the aggregate. 255 | 256 | 6. Conveying Non-Source Forms. 257 | 258 | You may convey a covered work in object code form under the terms 259 | of sections 4 and 5, provided that you also convey the 260 | machine-readable Corresponding Source under the terms of this License, 261 | in one of these ways: 262 | 263 | a) Convey the object code in, or embodied in, a physical product 264 | (including a physical distribution medium), accompanied by the 265 | Corresponding Source fixed on a durable physical medium 266 | customarily used for software interchange. 267 | 268 | b) Convey the object code in, or embodied in, a physical product 269 | (including a physical distribution medium), accompanied by a 270 | written offer, valid for at least three years and valid for as 271 | long as you offer spare parts or customer support for that product 272 | model, to give anyone who possesses the object code either (1) a 273 | copy of the Corresponding Source for all the software in the 274 | product that is covered by this License, on a durable physical 275 | medium customarily used for software interchange, for a price no 276 | more than your reasonable cost of physically performing this 277 | conveying of source, or (2) access to copy the 278 | Corresponding Source from a network server at no charge. 279 | 280 | c) Convey individual copies of the object code with a copy of the 281 | written offer to provide the Corresponding Source. This 282 | alternative is allowed only occasionally and noncommercially, and 283 | only if you received the object code with such an offer, in accord 284 | with subsection 6b. 285 | 286 | d) Convey the object code by offering access from a designated 287 | place (gratis or for a charge), and offer equivalent access to the 288 | Corresponding Source in the same way through the same place at no 289 | further charge. You need not require recipients to copy the 290 | Corresponding Source along with the object code. If the place to 291 | copy the object code is a network server, the Corresponding Source 292 | may be on a different server (operated by you or a third party) 293 | that supports equivalent copying facilities, provided you maintain 294 | clear directions next to the object code saying where to find the 295 | Corresponding Source. Regardless of what server hosts the 296 | Corresponding Source, you remain obligated to ensure that it is 297 | available for as long as needed to satisfy these requirements. 298 | 299 | e) Convey the object code using peer-to-peer transmission, provided 300 | you inform other peers where the object code and Corresponding 301 | Source of the work are being offered to the general public at no 302 | charge under subsection 6d. 303 | 304 | A separable portion of the object code, whose source code is excluded 305 | from the Corresponding Source as a System Library, need not be 306 | included in conveying the object code work. 307 | 308 | A "User Product" is either (1) a "consumer product", which means any 309 | tangible personal property which is normally used for personal, family, 310 | or household purposes, or (2) anything designed or sold for incorporation 311 | into a dwelling. In determining whether a product is a consumer product, 312 | doubtful cases shall be resolved in favor of coverage. For a particular 313 | product received by a particular user, "normally used" refers to a 314 | typical or common use of that class of product, regardless of the status 315 | of the particular user or of the way in which the particular user 316 | actually uses, or expects or is expected to use, the product. A product 317 | is a consumer product regardless of whether the product has substantial 318 | commercial, industrial or non-consumer uses, unless such uses represent 319 | the only significant mode of use of the product. 320 | 321 | "Installation Information" for a User Product means any methods, 322 | procedures, authorization keys, or other information required to install 323 | and execute modified versions of a covered work in that User Product from 324 | a modified version of its Corresponding Source. The information must 325 | suffice to ensure that the continued functioning of the modified object 326 | code is in no case prevented or interfered with solely because 327 | modification has been made. 328 | 329 | If you convey an object code work under this section in, or with, or 330 | specifically for use in, a User Product, and the conveying occurs as 331 | part of a transaction in which the right of possession and use of the 332 | User Product is transferred to the recipient in perpetuity or for a 333 | fixed term (regardless of how the transaction is characterized), the 334 | Corresponding Source conveyed under this section must be accompanied 335 | by the Installation Information. But this requirement does not apply 336 | if neither you nor any third party retains the ability to install 337 | modified object code on the User Product (for example, the work has 338 | been installed in ROM). 339 | 340 | The requirement to provide Installation Information does not include a 341 | requirement to continue to provide support service, warranty, or updates 342 | for a work that has been modified or installed by the recipient, or for 343 | the User Product in which it has been modified or installed. Access to a 344 | network may be denied when the modification itself materially and 345 | adversely affects the operation of the network or violates the rules and 346 | protocols for communication across the network. 347 | 348 | Corresponding Source conveyed, and Installation Information provided, 349 | in accord with this section must be in a format that is publicly 350 | documented (and with an implementation available to the public in 351 | source code form), and must require no special password or key for 352 | unpacking, reading or copying. 353 | 354 | 7. Additional Terms. 355 | 356 | "Additional permissions" are terms that supplement the terms of this 357 | License by making exceptions from one or more of its conditions. 358 | Additional permissions that are applicable to the entire Program shall 359 | be treated as though they were included in this License, to the extent 360 | that they are valid under applicable law. If additional permissions 361 | apply only to part of the Program, that part may be used separately 362 | under those permissions, but the entire Program remains governed by 363 | this License without regard to the additional permissions. 364 | 365 | When you convey a copy of a covered work, you may at your option 366 | remove any additional permissions from that copy, or from any part of 367 | it. (Additional permissions may be written to require their own 368 | removal in certain cases when you modify the work.) You may place 369 | additional permissions on material, added by you to a covered work, 370 | for which you have or can give appropriate copyright permission. 371 | 372 | Notwithstanding any other provision of this License, for material you 373 | add to a covered work, you may (if authorized by the copyright holders of 374 | that material) supplement the terms of this License with terms: 375 | 376 | a) Disclaiming warranty or limiting liability differently from the 377 | terms of sections 15 and 16 of this License; or 378 | 379 | b) Requiring preservation of specified reasonable legal notices or 380 | author attributions in that material or in the Appropriate Legal 381 | Notices displayed by works containing it; or 382 | 383 | c) Prohibiting misrepresentation of the origin of that material, or 384 | requiring that modified versions of such material be marked in 385 | reasonable ways as different from the original version; or 386 | 387 | d) Limiting the use for publicity purposes of names of licensors or 388 | authors of the material; or 389 | 390 | e) Declining to grant rights under trademark law for use of some 391 | trade names, trademarks, or service marks; or 392 | 393 | f) Requiring indemnification of licensors and authors of that 394 | material by anyone who conveys the material (or modified versions of 395 | it) with contractual assumptions of liability to the recipient, for 396 | any liability that these contractual assumptions directly impose on 397 | those licensors and authors. 398 | 399 | All other non-permissive additional terms are considered "further 400 | restrictions" within the meaning of section 10. If the Program as you 401 | received it, or any part of it, contains a notice stating that it is 402 | governed by this License along with a term that is a further 403 | restriction, you may remove that term. If a license document contains 404 | a further restriction but permits relicensing or conveying under this 405 | License, you may add to a covered work material governed by the terms 406 | of that license document, provided that the further restriction does 407 | not survive such relicensing or conveying. 408 | 409 | If you add terms to a covered work in accord with this section, you 410 | must place, in the relevant source files, a statement of the 411 | additional terms that apply to those files, or a notice indicating 412 | where to find the applicable terms. 413 | 414 | Additional terms, permissive or non-permissive, may be stated in the 415 | form of a separately written license, or stated as exceptions; 416 | the above requirements apply either way. 417 | 418 | 8. Termination. 419 | 420 | You may not propagate or modify a covered work except as expressly 421 | provided under this License. Any attempt otherwise to propagate or 422 | modify it is void, and will automatically terminate your rights under 423 | this License (including any patent licenses granted under the third 424 | paragraph of section 11). 425 | 426 | However, if you cease all violation of this License, then your 427 | license from a particular copyright holder is reinstated (a) 428 | provisionally, unless and until the copyright holder explicitly and 429 | finally terminates your license, and (b) permanently, if the copyright 430 | holder fails to notify you of the violation by some reasonable means 431 | prior to 60 days after the cessation. 432 | 433 | Moreover, your license from a particular copyright holder is 434 | reinstated permanently if the copyright holder notifies you of the 435 | violation by some reasonable means, this is the first time you have 436 | received notice of violation of this License (for any work) from that 437 | copyright holder, and you cure the violation prior to 30 days after 438 | your receipt of the notice. 439 | 440 | Termination of your rights under this section does not terminate the 441 | licenses of parties who have received copies or rights from you under 442 | this License. If your rights have been terminated and not permanently 443 | reinstated, you do not qualify to receive new licenses for the same 444 | material under section 10. 445 | 446 | 9. Acceptance Not Required for Having Copies. 447 | 448 | You are not required to accept this License in order to receive or 449 | run a copy of the Program. Ancillary propagation of a covered work 450 | occurring solely as a consequence of using peer-to-peer transmission 451 | to receive a copy likewise does not require acceptance. However, 452 | nothing other than this License grants you permission to propagate or 453 | modify any covered work. These actions infringe copyright if you do 454 | not accept this License. Therefore, by modifying or propagating a 455 | covered work, you indicate your acceptance of this License to do so. 456 | 457 | 10. Automatic Licensing of Downstream Recipients. 458 | 459 | Each time you convey a covered work, the recipient automatically 460 | receives a license from the original licensors, to run, modify and 461 | propagate that work, subject to this License. You are not responsible 462 | for enforcing compliance by third parties with this License. 463 | 464 | An "entity transaction" is a transaction transferring control of an 465 | organization, or substantially all assets of one, or subdividing an 466 | organization, or merging organizations. If propagation of a covered 467 | work results from an entity transaction, each party to that 468 | transaction who receives a copy of the work also receives whatever 469 | licenses to the work the party's predecessor in interest had or could 470 | give under the previous paragraph, plus a right to possession of the 471 | Corresponding Source of the work from the predecessor in interest, if 472 | the predecessor has it or can get it with reasonable efforts. 473 | 474 | You may not impose any further restrictions on the exercise of the 475 | rights granted or affirmed under this License. For example, you may 476 | not impose a license fee, royalty, or other charge for exercise of 477 | rights granted under this License, and you may not initiate litigation 478 | (including a cross-claim or counterclaim in a lawsuit) alleging that 479 | any patent claim is infringed by making, using, selling, offering for 480 | sale, or importing the Program or any portion of it. 481 | 482 | 11. Patents. 483 | 484 | A "contributor" is a copyright holder who authorizes use under this 485 | License of the Program or a work on which the Program is based. The 486 | work thus licensed is called the contributor's "contributor version". 487 | 488 | A contributor's "essential patent claims" are all patent claims 489 | owned or controlled by the contributor, whether already acquired or 490 | hereafter acquired, that would be infringed by some manner, permitted 491 | by this License, of making, using, or selling its contributor version, 492 | but do not include claims that would be infringed only as a 493 | consequence of further modification of the contributor version. For 494 | purposes of this definition, "control" includes the right to grant 495 | patent sublicenses in a manner consistent with the requirements of 496 | this License. 497 | 498 | Each contributor grants you a non-exclusive, worldwide, royalty-free 499 | patent license under the contributor's essential patent claims, to 500 | make, use, sell, offer for sale, import and otherwise run, modify and 501 | propagate the contents of its contributor version. 502 | 503 | In the following three paragraphs, a "patent license" is any express 504 | agreement or commitment, however denominated, not to enforce a patent 505 | (such as an express permission to practice a patent or covenant not to 506 | sue for patent infringement). To "grant" such a patent license to a 507 | party means to make such an agreement or commitment not to enforce a 508 | patent against the party. 509 | 510 | If you convey a covered work, knowingly relying on a patent license, 511 | and the Corresponding Source of the work is not available for anyone 512 | to copy, free of charge and under the terms of this License, through a 513 | publicly available network server or other readily accessible means, 514 | then you must either (1) cause the Corresponding Source to be so 515 | available, or (2) arrange to deprive yourself of the benefit of the 516 | patent license for this particular work, or (3) arrange, in a manner 517 | consistent with the requirements of this License, to extend the patent 518 | license to downstream recipients. "Knowingly relying" means you have 519 | actual knowledge that, but for the patent license, your conveying the 520 | covered work in a country, or your recipient's use of the covered work 521 | in a country, would infringe one or more identifiable patents in that 522 | country that you have reason to believe are valid. 523 | 524 | If, pursuant to or in connection with a single transaction or 525 | arrangement, you convey, or propagate by procuring conveyance of, a 526 | covered work, and grant a patent license to some of the parties 527 | receiving the covered work authorizing them to use, propagate, modify 528 | or convey a specific copy of the covered work, then the patent license 529 | you grant is automatically extended to all recipients of the covered 530 | work and works based on it. 531 | 532 | A patent license is "discriminatory" if it does not include within 533 | the scope of its coverage, prohibits the exercise of, or is 534 | conditioned on the non-exercise of one or more of the rights that are 535 | specifically granted under this License. You may not convey a covered 536 | work if you are a party to an arrangement with a third party that is 537 | in the business of distributing software, under which you make payment 538 | to the third party based on the extent of your activity of conveying 539 | the work, and under which the third party grants, to any of the 540 | parties who would receive the covered work from you, a discriminatory 541 | patent license (a) in connection with copies of the covered work 542 | conveyed by you (or copies made from those copies), or (b) primarily 543 | for and in connection with specific products or compilations that 544 | contain the covered work, unless you entered into that arrangement, 545 | or that patent license was granted, prior to 28 March 2007. 546 | 547 | Nothing in this License shall be construed as excluding or limiting 548 | any implied license or other defenses to infringement that may 549 | otherwise be available to you under applicable patent law. 550 | 551 | 12. No Surrender of Others' Freedom. 552 | 553 | If conditions are imposed on you (whether by court order, agreement or 554 | otherwise) that contradict the conditions of this License, they do not 555 | excuse you from the conditions of this License. If you cannot convey a 556 | covered work so as to satisfy simultaneously your obligations under this 557 | License and any other pertinent obligations, then as a consequence you may 558 | not convey it at all. For example, if you agree to terms that obligate you 559 | to collect a royalty for further conveying from those to whom you convey 560 | the Program, the only way you could satisfy both those terms and this 561 | License would be to refrain entirely from conveying the Program. 562 | 563 | 13. Use with the GNU Affero General Public License. 564 | 565 | Notwithstanding any other provision of this License, you have 566 | permission to link or combine any covered work with a work licensed 567 | under version 3 of the GNU Affero General Public License into a single 568 | combined work, and to convey the resulting work. The terms of this 569 | License will continue to apply to the part which is the covered work, 570 | but the special requirements of the GNU Affero General Public License, 571 | section 13, concerning interaction through a network will apply to the 572 | combination as such. 573 | 574 | 14. Revised Versions of this License. 575 | 576 | The Free Software Foundation may publish revised and/or new versions of 577 | the GNU General Public License from time to time. Such new versions will 578 | be similar in spirit to the present version, but may differ in detail to 579 | address new problems or concerns. 580 | 581 | Each version is given a distinguishing version number. If the 582 | Program specifies that a certain numbered version of the GNU General 583 | Public License "or any later version" applies to it, you have the 584 | option of following the terms and conditions either of that numbered 585 | version or of any later version published by the Free Software 586 | Foundation. If the Program does not specify a version number of the 587 | GNU General Public License, you may choose any version ever published 588 | by the Free Software Foundation. 589 | 590 | If the Program specifies that a proxy can decide which future 591 | versions of the GNU General Public License can be used, that proxy's 592 | public statement of acceptance of a version permanently authorizes you 593 | to choose that version for the Program. 594 | 595 | Later license versions may give you additional or different 596 | permissions. However, no additional obligations are imposed on any 597 | author or copyright holder as a result of your choosing to follow a 598 | later version. 599 | 600 | 15. Disclaimer of Warranty. 601 | 602 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 603 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 604 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 605 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 606 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 607 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 608 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 609 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 610 | 611 | 16. Limitation of Liability. 612 | 613 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 614 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 615 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 616 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 617 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 618 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 619 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 620 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 621 | SUCH DAMAGES. 622 | 623 | 17. Interpretation of Sections 15 and 16. 624 | 625 | If the disclaimer of warranty and limitation of liability provided 626 | above cannot be given local legal effect according to their terms, 627 | reviewing courts shall apply local law that most closely approximates 628 | an absolute waiver of all civil liability in connection with the 629 | Program, unless a warranty or assumption of liability accompanies a 630 | copy of the Program in return for a fee. 631 | 632 | END OF TERMS AND CONDITIONS 633 | 634 | How to Apply These Terms to Your New Programs 635 | 636 | If you develop a new program, and you want it to be of the greatest 637 | possible use to the public, the best way to achieve this is to make it 638 | free software which everyone can redistribute and change under these terms. 639 | 640 | To do so, attach the following notices to the program. It is safest 641 | to attach them to the start of each source file to most effectively 642 | state the exclusion of warranty; and each file should have at least 643 | the "copyright" line and a pointer to where the full notice is found. 644 | 645 | 646 | Copyright (C) 647 | 648 | This program is free software: you can redistribute it and/or modify 649 | it under the terms of the GNU General Public License as published by 650 | the Free Software Foundation, either version 3 of the License, or 651 | (at your option) any later version. 652 | 653 | This program is distributed in the hope that it will be useful, 654 | but WITHOUT ANY WARRANTY; without even the implied warranty of 655 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 656 | GNU General Public License for more details. 657 | 658 | You should have received a copy of the GNU General Public License 659 | along with this program. If not, see . 660 | 661 | Also add information on how to contact you by electronic and paper mail. 662 | 663 | If the program does terminal interaction, make it output a short 664 | notice like this when it starts in an interactive mode: 665 | 666 | Copyright (C) 667 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 668 | This is free software, and you are welcome to redistribute it 669 | under certain conditions; type `show c' for details. 670 | 671 | The hypothetical commands `show w' and `show c' should show the appropriate 672 | parts of the General Public License. Of course, your program's commands 673 | might be different; for a GUI interface, you would use an "about box". 674 | 675 | You should also get your employer (if you work as a programmer) or school, 676 | if any, to sign a "copyright disclaimer" for the program, if necessary. 677 | For more information on this, and how to apply and follow the GNU GPL, see 678 | . 679 | 680 | The GNU General Public License does not permit incorporating your program 681 | into proprietary programs. If your program is a subroutine library, you 682 | may consider it more useful to permit linking proprietary applications with 683 | the library. If this is what you want to do, use the GNU Lesser General 684 | Public License instead of this License. But first, please read 685 | . 686 | --------------------------------------------------------------------------------