├── ladybug_tools
├── lib
│ └── .gitignore
├── nodes
│ ├── __init__.py
│ └── ladybug
│ │ ├── __init__.py
│ │ └── LB_Out.py
├── helper.py
├── icons
│ └── lb_out.png
├── icons.py
├── color.py
├── config.py
├── text.py
├── colorize.py
├── fromgeometry.py
├── sockets.py
├── fromobjects.py
├── togeometry.py
├── sverchok.py
└── intersect.py
├── pass_tests.py
├── setup.cfg
├── dev-requirements.txt
├── deploy.sh
├── .gitignore
├── CODE_OF_CONDUCT.md
├── .releaserc.json
├── CONTRIBUTING.md
├── .travis.yml
├── setup.py
├── .github
└── workflows
│ └── ci-ladybug-blender-build.yml
├── generate_init.py
├── Makefile
├── init.mustache
├── README.md
├── generate_nodes.py
├── generic_node.mustache
└── LICENSE
/ladybug_tools/lib/.gitignore:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ladybug_tools/nodes/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ladybug_tools/nodes/ladybug/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/pass_tests.py:
--------------------------------------------------------------------------------
1 | """Disregard test running on Travis for now."""
2 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_wheel]
2 | universal = 1
3 |
4 | [metadata]
5 | license_file = LICENSE
6 |
--------------------------------------------------------------------------------
/ladybug_tools/helper.py:
--------------------------------------------------------------------------------
1 | class Ghenv():
2 | pass
3 |
4 | ghenv = Ghenv()
5 | ghenv.Component = None
6 |
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | coverage==5.3
2 | coveralls==2.1.2
3 | pytest==6.0.2
4 | pytest-cov==2.10.1
5 | twine==3.2.0
6 |
--------------------------------------------------------------------------------
/ladybug_tools/icons/lb_out.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ladybug-tools/ladybug-blender/HEAD/ladybug_tools/icons/lb_out.png
--------------------------------------------------------------------------------
/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | echo "Building distribution"
4 | python setup.py sdist bdist_wheel
5 | echo "Pushing new version to PyPi"
6 | twine upload dist/* -u $PYPI_USERNAME -p $PYPI_PASSWORD
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | test.py
3 | .pytest_cache
4 | *__pycache__
5 | .coverage
6 | *.ipynb
7 | .ipynb_checkpoints
8 | .tox
9 | *.egg-info
10 | tox.ini
11 | /.cache
12 | /.vscode
13 | .eggs
14 | *.code-workspace
15 | init.txt
16 | dist/
17 | *.swp
18 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | Contributor Covenant Code of Conduct
2 | =========================================
3 |
4 | This project follows Ladybug Tools contributor covenant code of conduct. See our [contributor covenant code of conduct](https://github.com/ladybug-tools/contributing/blob/master/CODE-OF-CONDUCT.md).
5 |
--------------------------------------------------------------------------------
/.releaserc.json:
--------------------------------------------------------------------------------
1 | {
2 | "plugins": [
3 | "@semantic-release/commit-analyzer",
4 | "@semantic-release/release-notes-generator",
5 | "@semantic-release/github",
6 | [
7 | "@semantic-release/exec",
8 | {
9 | "publishCmd": "bash deploy.sh"
10 | }
11 | ]
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Contributing
2 | ------------
3 | We welcome contributions from anyone, even if you are new to open source we will be happy to help you to get started. Most of the Ladybug Tools developers started learning programming through developing for Ladybug Tools.
4 |
5 | ### Code contribution
6 | This project follows Ladybug Tools contributing guideline. See [contributing to Ladybug Tools projects](https://github.com/ladybug-tools/contributing/blob/master/README.md).
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | python:
4 | - "3.6"
5 |
6 | jobs:
7 | include:
8 | - stage: test
9 | install:
10 | - pip install -r dev-requirements.txt
11 | script:
12 | - python ./pass_tests.py
13 | - stage: deploy
14 | if: branch = master AND (NOT type IN (pull_request))
15 | before_install:
16 | - nvm install lts/* --latest-npm
17 | python:
18 | - "3.6"
19 | install:
20 | - pip install -r dev-requirements.txt
21 | - npm install @semantic-release/exec
22 | script:
23 | - git config --global user.email "releases@ladybug.tools"
24 | - git config --global user.name "ladybugbot"
25 | - npx semantic-release
26 |
--------------------------------------------------------------------------------
/ladybug_tools/icons.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 |
4 | from sverchok.ui.sv_icons import register_custom_icon_provider
5 |
6 | class SvExIconProvider(object):
7 | def __init__(self):
8 | pass
9 |
10 | def get_icons(self):
11 | icons_dir = os.path.join(os.path.dirname(__file__), "icons")
12 | icon_pattern = "lb_*.png"
13 | icon_path = os.path.join(icons_dir, icon_pattern)
14 | icon_files = [os.path.basename(x) for x in glob.glob(icon_path)]
15 |
16 | for icon_file in icon_files:
17 | icon_name = os.path.splitext(icon_file)[0]
18 | icon_id = icon_name.upper()
19 | yield icon_id, os.path.join(icons_dir, icon_file)
20 |
21 | def register():
22 | register_custom_icon_provider("ladybug", SvExIconProvider())
23 |
24 | def unregister():
25 | pass
26 |
--------------------------------------------------------------------------------
/ladybug_tools/color.py:
--------------------------------------------------------------------------------
1 | """Collection of methods for converting between Ladybug and .NET colors."""
2 |
3 | from ladybug.color import Color
4 |
5 | def color_to_color(color, alpha=255):
6 | """Convert a ladybug color into .NET color.
7 |
8 | Args:
9 | alpha: Optional integer betwen 1 and 255 for the alpha value of the color.
10 | """
11 | return color
12 | try:
13 | return Color.FromArgb(alpha, color.r, color.g, color.b)
14 | except AttributeError as e:
15 | raise AttributeError('Input must be of type of Color:\n{}'.format(e))
16 |
17 |
18 | def gray():
19 | """Get a .NET gray color object. Useful when you need a placeholder color."""
20 | return Color(90, 90, 90, 255)
21 |
22 |
23 | def black():
24 | """Get a .NET black color object. Useful for things like default text."""
25 | return Color(0, 0, 0, 255)
26 | return Color.Black
27 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools
2 |
3 | with open("README.md", "r") as fh:
4 | long_description = fh.read()
5 |
6 | setuptools.setup(
7 | name="ladybug-blender",
8 | use_scm_version=True,
9 | setup_requires=['setuptools_scm'],
10 | author="Ladybug Tools",
11 | author_email="info@ladybug.tools",
12 | description="Ladybug plugin for Blender.",
13 | long_description=long_description,
14 | long_description_content_type="text/markdown",
15 | url="https://github.com/ladybug-tools/ladybug-blender",
16 | packages=setuptools.find_packages(exclude=["samples"]),
17 | include_package_data=True,
18 | install_requires=[],
19 | classifiers=[
20 | "Programming Language :: Python :: 3.6",
21 | "Programming Language :: Python :: 3.7",
22 | "Programming Language :: Python :: Implementation :: CPython",
23 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
24 | "Operating System :: OS Independent"
25 | ],
26 | )
27 |
--------------------------------------------------------------------------------
/ladybug_tools/config.py:
--------------------------------------------------------------------------------
1 | """Ladybug_rhino configurations.
2 | Global variables such as tolerances and units are stored here.
3 | """
4 |
5 | # I didn't see where Blender does tolerance, until I do, let's copy Rhino
6 | # TODO: check where this is used, if at all. If not, remove.
7 | tolerance = 0.01
8 | angle_tolerance = 1.0 # default is 1 degree
9 |
10 |
11 | def conversion_to_meters():
12 | """Get the conversion factor to meters based on the current Rhino doc units system.
13 | Returns:
14 | A number for the conversion factor, which should be multiplied by all distance
15 | units taken from Rhino geometry in order to convert them to meters.
16 | """
17 | # Blender (and Sverchok) always works in meters internally
18 | return 1.0
19 |
20 |
21 | def units_system():
22 | """Get text for the current Rhino doc units system. (eg. 'Meters', 'Feet')"""
23 | return "TODO"
24 |
25 |
26 | def units_abbreviation():
27 | """Get text for the current Rhino doc units abbreviation (eg. 'm', 'ft')"""
28 | return "TODO"
29 |
--------------------------------------------------------------------------------
/.github/workflows/ci-ladybug-blender-build.yml:
--------------------------------------------------------------------------------
1 | name: Publish-ladybug-blender
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 |
7 | env:
8 | major: 0
9 | minor: 0
10 | name: ladybug-blender
11 |
12 | jobs:
13 | activate:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: Set env
17 | run: echo ok go
18 |
19 | build:
20 | needs: activate
21 | name: ladybug-blender
22 | runs-on: ubuntu-latest
23 | strategy:
24 | fail-fast: false
25 | steps:
26 | - uses: actions/checkout@v2
27 | - uses: actions/setup-python@v2 # https://github.com/actions/setup-python
28 | with:
29 | architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
30 | python-version: '3.11'
31 | - run: sudo apt install 2to3
32 | - run: echo ${{ env.DATE }}
33 | - name: Get current date
34 | id: date
35 | run: echo "::set-output name=date::$(date +'%y%m%d')"
36 | - name: Compile
37 | run: |
38 | make dist
39 | - name: Upload Zip file to release
40 | uses: svenstaro/upload-release-action@v2
41 | with:
42 | repo_token: ${{ secrets.GITHUB_TOKEN }}
43 | file: dist/ladybug-blender-${{steps.date.outputs.date}}.zip
44 | asset_name: ladybug-blender-${{steps.date.outputs.date}}.zip
45 | tag: "ladybug-blender-${{steps.date.outputs.date}}"
46 | overwrite: true
47 | body: "ladybug-blender build for ${{steps.date.outputs.date}}"
48 |
--------------------------------------------------------------------------------
/generate_init.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import pystache
4 | import subprocess
5 | from pathlib import Path
6 |
7 | class Generator():
8 | def __init__(self):
9 | self.json_dir = './dist/working/json/'
10 | self.out_dir = './dist/working/python/'
11 |
12 | def generate(self):
13 | data = {
14 | 'nodes': [],
15 | }
16 | for filename in Path(self.json_dir).glob('*.json'):
17 | if 'LB_Export_UserObject' in str(filename) \
18 | or 'LB_Sync_Grasshopper_File' in str(filename) \
19 | or 'LB_Versioner' in str(filename):
20 | continue # I think these nodes are just for Grasshopper
21 | with open(filename, 'r') as spec_f:
22 | spec = json.load(spec_f)
23 | spec['nickname'] = spec['nickname'].replace('+', 'Plus')
24 | filename = os.path.basename(filename)
25 | subcategory = spec['subcategory'].split(' :: ')[1]
26 | data['nodes'].append({
27 | 'node_module': filename[0:-5],
28 | 'node_classname': spec['nickname'],
29 | 'subcategory': subcategory
30 | })
31 |
32 | out_filepath = os.path.join(self.out_dir, '__init__.py')
33 | with open(out_filepath, 'w') as f:
34 | with open('init.mustache', 'r') as template:
35 | f.write(pystache.render(template.read(), data))
36 |
37 | generator = Generator()
38 | generator.generate()
39 |
--------------------------------------------------------------------------------
/ladybug_tools/text.py:
--------------------------------------------------------------------------------
1 | """Functions to add text to the Rhino scene and create Grasshopper text objects."""
2 | import math
3 |
4 | def text_objects(text, plane, height, font='Arial',
5 | horizontal_alignment=0, vertical_alignment=5):
6 | """Generate a Bake-able Grasshopper text object from a text string and ladybug Plane.
7 |
8 | Args:
9 | text: A text string to be converted to a a Grasshopper text object.
10 | plane: A Ladybug Plane object to locate and orient the text in the Rhino scene.
11 | height: A number for the height of the text in the Rhino scene.
12 | font: An optional text string for the font in which to draw the text.
13 | horizontal_alignment: An optional integer to specify the horizontal alignment
14 | of the text. Choose from: (0 = Left, 1 = Center, 2 = Right)
15 | vertical_alignment: An optional integer to specify the vertical alignment
16 | of the text. Choose from: (0 = Top, 1 = MiddleOfTop, 2 = BottomOfTop,
17 | 3 = Middle, 4 = MiddleOfBottom, 5 = Bottom, 6 = BottomOfBoundingBox)
18 | """
19 | # There is no standardised way to transfer text in Sverchok
20 | return LadybugText(text, plane, height, horizontal_alignment, vertical_alignment)
21 |
22 |
23 | class LadybugText():
24 | def __init__(self, text, plane, height, horizontal_alignment, vertical_alignment):
25 | self.text = text
26 | self.plane = plane
27 | self.height = height
28 | self.horizontal_alignment = horizontal_alignment
29 | self.vertical_alignment = vertical_alignment
30 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SHELL := /bin/bash
2 | VERSION:=`date '+%y%m%d'`
3 | _python_ver:=$(shell python --version | grep -Po 'Python \K[0-9].[0-9]+')
4 |
5 | .PHONY: dist
6 | dist:
7 | rm -rf dist
8 | mkdir -p dist/ladybug_tools
9 | cp -r ladybug_tools/* dist/ladybug_tools/
10 |
11 | mkdir dist/working
12 | mkdir dist/working/json
13 | mkdir dist/working/icon
14 | mkdir dist/working/python
15 | cd dist/working && wget https://github.com/ladybug-tools/ladybug-grasshopper/archive/master.zip
16 | cd dist/working && unzip master.zip
17 | cd dist/working/json && cp -r ../ladybug-grasshopper-master/ladybug_grasshopper/json/*.json ./
18 | cd dist/working/icon && cp -r ../ladybug-grasshopper-master/ladybug_grasshopper/icon/*.png ./
19 | python -m venv dist/working/env
20 | source dist/working/env/bin/activate && pip install pystache
21 | source dist/working/env/bin/activate && python generate_init.py
22 | cp -r dist/working/python/* dist/ladybug_tools/
23 | rm -rf dist/working/python/*
24 | source dist/working/env/bin/activate && python generate_nodes.py
25 | cp -r dist/working/python/* dist/ladybug_tools/nodes/ladybug/
26 | cp -r dist/working/icon/* dist/ladybug_tools/icons/
27 | rm -rf dist/working
28 |
29 | mkdir dist/working
30 | python -m venv dist/working/env
31 | source dist/working/env/bin/activate && pip install lbt-ladybug
32 | # lbt-ladybug is python version independent
33 | cp -r dist/working/env/lib/python$(_python_ver)/site-packages/ladybug dist/ladybug_tools/lib/
34 | cp -r dist/working/env/lib/python$(_python_ver)/site-packages/ladybug_comfort dist/ladybug_tools/lib/
35 | cp -r dist/working/env/lib/python$(_python_ver)/site-packages/ladybug_geometry dist/ladybug_tools/lib/
36 | rm -rf dist/working
37 |
38 | cd dist/ladybug_tools && sed -i "s/999999/$(VERSION)/" __init__.py
39 | cd dist && zip -r ladybug-blender-$(VERSION).zip ./*
40 | rm -rf dist/ladybug_tools
41 |
42 | .PHONY: clean
43 | clean:
44 | rm -rf dist
45 |
--------------------------------------------------------------------------------
/ladybug_tools/colorize.py:
--------------------------------------------------------------------------------
1 | """Classes for colorized versions of various Rhino objects like points."""
2 | from .color import black
3 |
4 | class ColoredPoint():
5 | """A Point object with a set-able color property to change its color in Grasshopper.
6 |
7 | Args:
8 | point: A Rhino Point3d object.
9 | """
10 |
11 | def __init__(self, point):
12 | """Initialize ColoredPoint."""
13 | self.point = point
14 | self.color = black()
15 |
16 | def DuplicateGeometry(self):
17 | point = rh.Geometry.Point3d(self.point.X, self.point.Y, self.point.Z)
18 | new_pt = ColoredPoint(point)
19 | new_pt.color = self.color
20 | return new_pt
21 |
22 | def get_TypeName(self):
23 | return "Colored Point"
24 |
25 | def get_TypeDescription(self):
26 | return "Colored Point"
27 |
28 | def ToString(self):
29 | return '{}, {}, {}'.format(self.color.R, self.color.G, self.color.B)
30 |
31 | def Transform(self, xform):
32 | point = rh.Geometry.Point3d(self.point.X, self.point.Y, self.point.Z)
33 | point.Transform(xform)
34 | new_pt = ColoredPoint(point)
35 | new_pt.color = self.color
36 | return new_pt
37 |
38 | def Morph(self, xmorph):
39 | return self.DuplicateGeometry()
40 |
41 | def DrawViewportWires(self, args):
42 | args.Pipeline.DrawPoint(self.point, rh.Display.PointStyle.RoundSimple, 5, self.color)
43 |
44 | def DrawViewportMeshes(self, args):
45 | # Do not draw in meshing layer.
46 | pass
47 |
48 | def BakeGeometry(self, doc, att, id):
49 | id = guid.Empty
50 | if att is None:
51 | att = doc.CreateDefaultAttributes()
52 | att.ColorSource = rh.DocObjects.ObjectColorSource.ColorFromObject
53 | att.ObjectColor = self.color
54 | id = doc.Objects.AddPoint(self.point, att)
55 | return True, id
56 |
--------------------------------------------------------------------------------
/init.mustache:
--------------------------------------------------------------------------------
1 | bl_info = {
2 | "name": "Ladybug Tools",
3 | "author": "Dion Moult",
4 | "version": (0, 0, 999999),
5 | "blender": (2, 90, 0),
6 | "location": "Node Editor",
7 | "category": "Node",
8 | "description": "Ladybug, Honeybee, Butterfly, and Dragonfly for Blender",
9 | "warning": "",
10 | "wiki_url": "https://wiki.osarch.org/",
11 | "tracker_url": "https://github.com/ladybug-tools/ladybug-blender"
12 | }
13 |
14 | import os
15 | import site
16 |
17 | cwd = os.path.dirname(os.path.realpath(__file__))
18 | site.addsitedir(os.path.join(cwd, "lib"))
19 |
20 | import sys
21 | import importlib
22 | import nodeitems_utils
23 | import sverchok
24 | from ladybug_tools import icons, sockets
25 | from sverchok.ui.nodeview_space_menu import add_node_menu
26 | import logging
27 | logger = logging.getLogger('sverchok')
28 |
29 | def nodes_index():
30 | return [("Ladybug", [
31 | ("ladybug.LB_Out", "SvLBOut", "Viz"),
32 | # Generated nodes
33 | {{#nodes}}
34 | ("ladybug.{{node_module}}", "Sv{{node_classname}}", "{{subcategory}}"),
35 | {{/nodes}}
36 | ])]
37 |
38 |
39 | def make_node_categories() -> list[dict[str, list[str]]]:
40 | node_categories = [{}]
41 | for category, nodes in nodes_index():
42 | subcategories = {}
43 | for module_name, node_name, subcategory in nodes:
44 | subcategories.setdefault(subcategory, []).append(node_name)
45 | subcategories = [{subcategory: items} for subcategory, items in subcategories.items()]
46 | node_categories[0][category] = subcategories
47 |
48 | return node_categories
49 |
50 |
51 | node_categories = make_node_categories()
52 |
53 |
54 | def make_node_list():
55 | modules = []
56 | base_name = "ladybug_tools.nodes"
57 | index = nodes_index()
58 | for category, items in index:
59 | for module_name, node_name, subcategory in items:
60 | module = importlib.import_module(f".{module_name}", base_name)
61 | modules.append(module)
62 | return modules
63 |
64 | imported_modules = make_node_list()
65 |
66 | reload_event = False
67 |
68 | import bpy
69 |
70 | def register_nodes():
71 | node_modules = make_node_list()
72 | for module in node_modules:
73 | module.register()
74 | logger.info("Registered %s nodes", len(node_modules))
75 |
76 | def unregister_nodes():
77 | global imported_modules
78 | for module in reversed(imported_modules):
79 | module.unregister()
80 |
81 |
82 | add_node_menu.append_from_config(node_categories)
83 |
84 |
85 | def register():
86 | logger.debug("Registering ladybug_tools")
87 |
88 | icons.register()
89 | sockets.register()
90 | register_nodes()
91 | add_node_menu.register()
92 |
93 | def unregister():
94 | unregister_nodes()
95 | sockets.unregister()
96 | icons.unregister()
97 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/ladybug-tools/ladybug-blender)
2 |
3 | [](https://www.python.org/downloads/release/python-360/)
4 |
5 | # ladybug-blender
6 |
7 | :beetle: :orange_book: Ladybug plugin for [Blender](https://www.blender.org/) using the
8 | [Sverchok](https://github.com/nortikin/sverchok) visual scripting interface for Blender.
9 |
10 | This package contains the interface between Blender and the Ladybug Tools core
11 | libraries as well as the Blender Sverchok nodes for the Ladybug plugin.
12 | Note that, in order to run the plugin, the core libraries must be installed
13 | in a way that they can be found by Blender (see dependencies).
14 |
15 | ## Dependencies
16 |
17 | The ladybug-blender plugin has the following dependencies:
18 |
19 | * [ladybug-core](https://github.com/ladybug-tools/ladybug)
20 | * [ladybug-geometry](https://github.com/ladybug-tools/ladybug-geometry)
21 | * [ladybug-comfort](https://github.com/ladybug-tools/ladybug-comfort)
22 |
23 | ## Installation
24 |
25 | **Warning: We're slowly releasing an incomplete, alpha state version of the Blender port of Ladybug Tools for environmental analysis. If you're really awesome, please check it out, and when you inevitably come across a bug (like, actual bugs, not ladybugs), please let us know so we can fix it. Don't say we didn't warn you.**
26 |
27 | 1. Install Sverchok (scroll down on https://blenderbim.org/download.html - download zip and install like any other add-on)
28 | 2. Install Ladybug Tools (scroll down on https://blenderbim.org/download.html - download zip and install like any other add-on)
29 | 3. Want to display coloured points? Yes you do. [Install it](https://github.com/uhlik/bpy/blob/master/space_view3d_point_cloud_visualizer.py).
30 | 4. Restart Blender
31 |
32 | If you are upgrading, uninstall the old Ladybug Tools, and restart Blender, then
33 | install the new version.
34 |
35 | Things to be aware of:
36 |
37 | 1. [Look in the console when an error occurs](https://blender.stackexchange.com/questions/23147/how-do-i-get-the-console-on-windows) for errors. If you see `WARNING: geometry <...> not yet supported in Sverchok` please ignore. However, if you see `WARNING: geometry <...> not yet supported in Blender`, please report as a high priority. You may safely ignore `TODO: interpolate this line` messages.
38 | 2. These nodes may _not_ be the same nodes you will find in Grasshopper. Most users of the Ladybug Tools on Grasshopper are using the older Ladybug Legacy nodes. Ladybug Tools have since rewritten all their nodes from scratch, and this includes node renaming and restructuring of inputs and outputs. If you are using the Ladybug Tools [+] Plus version, then you will be familiar with these nodes. If not, be prepared for a few new things.
39 | 3. These nodes are _only_ Ladybug for now. You will not find Honeybee, Dragonfly, or Butterfly. This is a work in progress.
40 | 4. Use the `LB Out` node to bake Ladybug Geometry, or to extract unbaked verts, edges, and faces for further Sverchok progressing. Right now, it bakes directly to the scene collection with no garbage collection, so it can make your scene a bit messy, but was the simplest implementation to show that things work for now.
41 | 5. Grid size will be ignored in analysis. Blender is a good mesh modeling package, and so I recommend simply using a subdivision modifier (you don't need to apply it) to set the resolution of your analysis.
42 | 6. Too many menus? Use `Alt-Space` to search.
43 | 7. Objects coming from the scene need to be nested to be used in Ladybug nodes. Use the List join node with the wrap option enabled as shown in [this screenshot](https://user-images.githubusercontent.com/88302/94118359-c9a4fc00-fe90-11ea-8fea-735dc9e1326d.png)
44 |
45 | If you'd like to get a feel for it, watch [this demo video](https://www.youtube.com/watch?v=rMCuSwsF2aM).
46 |
--------------------------------------------------------------------------------
/ladybug_tools/fromgeometry.py:
--------------------------------------------------------------------------------
1 | """Functions to translate from Ladybug geomtries to Rhino geometries."""
2 | from .config import tolerance
3 | #from .color import color_to_color, gray
4 |
5 | """____________2D GEOMETRY TRANSLATORS____________"""
6 |
7 |
8 | def from_vector2d(vector):
9 | """Rhino Vector3d from ladybug Vector2D."""
10 | return vector
11 | return (vector.x, vector.y, 0)
12 |
13 |
14 | def from_point2d(point, z=0):
15 | """Rhino Point3d from ladybug Point2D."""
16 | return point
17 | return (point.x, point.y, z)
18 |
19 |
20 | def from_ray2d(ray, z=0):
21 | """Rhino Ray3d from ladybug Ray2D."""
22 | return ray
23 | return rg.Ray3d(from_point2d(ray.p, z), from_vector2d(ray.v))
24 |
25 |
26 | def from_linesegment2d(line, z=0):
27 | """Rhino LineCurve from ladybug LineSegment2D."""
28 | return line
29 |
30 |
31 | def from_arc2d(arc, z=0):
32 | """Rhino Arc from ladybug Arc2D."""
33 | return arc
34 |
35 |
36 | def from_polygon2d(polygon, z=0):
37 | """Rhino closed PolyLineCurve from ladybug Polygon2D."""
38 | return polygon
39 |
40 |
41 | def from_polyline2d(polyline, z=0):
42 | """Rhino closed PolyLineCurve from ladybug Polyline2D."""
43 | return polyline
44 |
45 |
46 | def from_mesh2d(mesh, z=0):
47 | """Rhino Mesh from ladybug Mesh2D."""
48 | return mesh
49 |
50 |
51 | """____________3D GEOMETRY TRANSLATORS____________"""
52 |
53 |
54 | def from_vector3d(vector):
55 | """Rhino Vector3d from ladybug Vector3D."""
56 | return vector
57 |
58 |
59 | def from_point3d(point):
60 | """Rhino Point3d from ladybug Point3D."""
61 | return point
62 |
63 |
64 | def from_ray3d(ray, z=0):
65 | """Rhino Ray3d from ladybug Ray3D."""
66 | return ray
67 |
68 |
69 | def from_linesegment3d(line):
70 | """Rhino LineCurve from ladybug LineSegment3D."""
71 | return line
72 |
73 |
74 | def from_plane(pl):
75 | """Rhino Plane from ladybug Plane."""
76 | return pl
77 |
78 |
79 | def from_arc3d(arc):
80 | """Rhino Arc from ladybug Arc3D."""
81 | return arc
82 |
83 |
84 | def from_polyline3d(polyline):
85 | """Rhino closed PolyLineCurve from ladybug Polyline3D."""
86 | return polyline
87 |
88 |
89 | def from_mesh3d(mesh):
90 | """Rhino Mesh from ladybug Mesh3D."""
91 | return mesh
92 |
93 |
94 | def from_face3d(face):
95 | """Rhino Brep from ladybug Face3D."""
96 | return face
97 |
98 |
99 | def from_polyface3d(polyface):
100 | """Rhino Brep from ladybug Polyface3D."""
101 | return polyface
102 |
103 |
104 | """________ADDITIONAL 3D GEOMETRY TRANSLATORS________"""
105 |
106 |
107 | def from_face3d_to_wireframe(face):
108 | """Rhino PolyLineCurve from ladybug Face3D."""
109 | return face
110 |
111 |
112 | def from_polyface3d_to_wireframe(polyface):
113 | """Rhino PolyLineCurve from ladybug Polyface3D."""
114 | return polyface
115 |
116 |
117 | def from_face3d_to_solid(face, offset):
118 | """Rhino Solid Brep from a ladybug Face3D and an offset."""
119 | return "TODO FROM FACE3D TO SOLID"
120 | srf_brep = from_face3d(face)
121 | return rg.Brep.CreateFromOffsetFace(
122 | srf_brep.Faces[0], offset, tolerance, False, True)
123 |
124 |
125 | def from_face3ds_to_colored_mesh(faces, color):
126 | """Colored Rhino mesh from an array of ladybug Face3D and ladybug Color.
127 |
128 | This is used in workflows such as coloring Model geomtry with results.
129 | """
130 | return "TODO FACE3D TO COLORED MESH"
131 | joined_mesh = rg.Mesh()
132 | for face in faces:
133 | try:
134 | joined_mesh.Append(rg.Mesh.CreateFromBrep(
135 | from_face3d(face), rg.MeshingParameters.Default)[0])
136 | except TypeError:
137 | pass # failed to create a Rhino Mesh from the Face3D
138 | joined_mesh.VertexColors.CreateMonotoneMesh(color_to_color(color))
139 | return joined_mesh
140 |
--------------------------------------------------------------------------------
/ladybug_tools/sockets.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | import sverchok.core.socket_conversions
3 | from bpy.types import NodeSocket
4 | from bpy.props import StringProperty
5 | from sverchok.core.socket_conversions import ConversionPolicies
6 | from sverchok.core.sockets import SvSocketCommon, process_from_socket
7 |
8 |
9 | class SvLBSocketName(bpy.types.Operator):
10 | bl_idname = "node.sv_lb_socket_name"
11 | bl_label = "LB Info"
12 | bl_options = {'UNDO'}
13 |
14 | idtree: StringProperty(default='')
15 | idname: StringProperty(default='')
16 |
17 | tooltip: bpy.props.StringProperty()
18 |
19 | @classmethod
20 | def description(cls, context, properties):
21 | return properties.tooltip
22 |
23 | def execute(self, context):
24 | return {'FINISHED'}
25 |
26 |
27 | class SvLBSocket(NodeSocket, SvSocketCommon):
28 | bl_idname = "SvLBSocket"
29 | bl_label = "Strings Socket"
30 |
31 | color = (0.6, 1.0, 0.6, 1.0)
32 |
33 | quick_link_to_node: StringProperty() # this can be overridden by socket instances
34 |
35 | default_property_type: bpy.props.EnumProperty(items=[(i, i, '') for i in ['float', 'int']])
36 | default_float_property: bpy.props.FloatProperty(update=process_from_socket)
37 | default_int_property: bpy.props.IntProperty(update=process_from_socket)
38 |
39 | tooltip: bpy.props.StringProperty()
40 | default_conversion_name = ConversionPolicies.LENIENT.conversion_name
41 |
42 | @property
43 | def default_property(self):
44 | return self.default_float_property if self.default_property_type == 'float' else self.default_int_property
45 |
46 | def draw(self, context, layout, node, text):
47 | if not self.tooltip:
48 | self.tooltip = ''
49 |
50 | # just handle custom draw..be it input or output.
51 | if self.custom_draw:
52 | # does the node have the draw function referred to by
53 | # the string stored in socket's custom_draw attribute
54 | if hasattr(node, self.custom_draw):
55 | getattr(node, self.custom_draw)(self, context, layout)
56 |
57 | elif self.is_linked: # linked INPUT or OUTPUT
58 | layout.operator('node.sv_lb_socket_name',
59 | text=self.get_prop_name()[3:] or self.label or text, emboss=False).tooltip = self.tooltip
60 |
61 |
62 | elif self.is_output: # unlinked OUTPUT
63 | #layout.label(text=self.label or text)
64 | layout.operator('node.sv_lb_socket_name',
65 | text=self.label or text, emboss=False).tooltip = self.tooltip
66 |
67 | else: # unlinked INPUT
68 | if self.get_prop_name(): # has property
69 | self.draw_property(layout, prop_origin=node, prop_name=self.get_prop_name())
70 |
71 | elif self.use_prop: # no property but use default prop
72 | self.draw_property(layout)
73 |
74 | else: # no property and not use default prop
75 | self.draw_quick_link(context, layout, node)
76 | layout.label(text=self.label or text)
77 |
78 | def draw_property(self, layout, prop_origin=None, prop_name=None):
79 | if prop_origin and prop_name:
80 | row = layout.row(align=True)
81 | if not self.tooltip:
82 | self.tooltip = ''
83 | op = row.operator('node.sv_lb_socket_name', text=prop_name[3:], emboss=False).tooltip = self.tooltip
84 | row.prop(prop_origin, prop_name, text='')
85 | elif self.use_prop:
86 | if self.default_property_type == 'float':
87 | layout.prop(self, 'default_float_property', text=self.name)
88 | elif self.default_property_type == 'int':
89 | layout.prop(self, 'default_int_property', text=self.name)
90 |
91 | def register():
92 | bpy.utils.register_class(SvLBSocketName)
93 | bpy.utils.register_class(SvLBSocket)
94 |
95 | def unregister():
96 | bpy.utils.unregister_class(SvLBSocket)
97 | bpy.utils.unregister_class(SvLBSocketName)
98 |
--------------------------------------------------------------------------------
/generate_nodes.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import pystache
4 | import subprocess
5 | from pathlib import Path
6 |
7 | class Generator():
8 | def __init__(self):
9 | self.json_dir = './dist/working/json/'
10 | self.icon_dir = './dist/working/icon/'
11 | self.python2to3_bin = '/usr/bin/2to3'
12 | #self.out_dir = './nodes/ladybug/'
13 | self.out_dir = './dist/working/python/'
14 |
15 | def generate(self):
16 | for filename in Path(self.json_dir).glob('*.json'):
17 | if 'LB_Export_UserObject' in str(filename) \
18 | or 'LB_Sync_Grasshopper_File' in str(filename) \
19 | or 'LB_Versioner' in str(filename):
20 | continue # I think these nodes are just for Grasshopper
21 | with open(filename, 'r') as spec_f:
22 | self.generate_node(os.path.basename(filename), json.load(spec_f))
23 |
24 | def generate_node(self, filename, spec):
25 | code_data = {
26 | 'cad': 'tools',
27 | 'Cad': 'Blender Ladybug',
28 | 'plugin': 'sverchok',
29 | 'Plugin': '',
30 | 'PLGN': '',
31 | 'Package_Manager': ''
32 | }
33 | # 'grasshopper': '{{plugin}}', 'Grasshopper': '{{Plugin}}',
34 | # 'GH': '{{PLGN}}', 'Food4Rhino': '{{Package_Manager}}',
35 | # 'rhino': '{{cad}}', 'Rhino': '{{Cad}}'
36 | spec['code'] = pystache.render(spec['code'].replace('\n', '\n' + ' '*8), code_data)
37 | spec['outputs'] = spec['outputs'][0] # JSON double nests this, maybe a mistake?
38 | spec['input_name_list'] = ', '.join(["'{}'".format(i['name']) for i in spec['inputs']])
39 | spec['input_name_unquoted_list'] = ', '.join([i['name'] for i in spec['inputs']])
40 | spec['input_type_list'] = ', '.join(["'{}'".format(i['type']) for i in spec['inputs']])
41 | spec['input_default_list'] = [repr(i['default']) for i in spec['inputs']]
42 |
43 | # These two lines are because the JSON dosen't properly represent bools
44 | spec['input_default_list'] = ['True' if i == "'true'" else i for i in spec['input_default_list']]
45 | spec['input_default_list'] = ['False' if i == "'false'" else i for i in spec['input_default_list']]
46 |
47 | spec['input_default_list'] = ', '.join(spec['input_default_list'])
48 | spec['input_access_list'] = ', '.join(["'{}'".format(i['access']) for i in spec['inputs']])
49 | spec['output_name_list'] = ', '.join(["'{}'".format(o['name']) for o in spec['outputs']])
50 | spec['nickname'] = spec['nickname'].replace('+', 'Plus').replace(" ", "_")
51 | spec['nickname_uppercase'] = spec['nickname'].upper()
52 | spec['description'] = spec['description'].replace('\n', ' ').replace("'", "\\'")
53 | for item in spec['inputs']:
54 | item['description'] = item['description'].replace('\n', ' ').replace("'", "\\'")
55 | for item in spec['outputs']:
56 | item['description'] = item['description'].replace('\n', ' ').replace("'", "\\'")
57 | module_name = filename[0:-5]
58 | out_filepath = os.path.join(self.out_dir, module_name + '.py')
59 | with open(out_filepath, "w", encoding="utf-8") as f:
60 | with open('generic_node.mustache', 'r') as template:
61 | f.write(pystache.render(template.read(), spec))
62 |
63 | res = subprocess.run([self.python2to3_bin, "-x", "itertools_imports", "-w", out_filepath, "-n"])
64 | if res.returncode != 0:
65 | raise Exception(f"Failed to run 2to3 on {out_filepath}.")
66 |
67 | icon_path = os.path.join(self.icon_dir, 'lb_{}.png'.format(spec['nickname'].lower()))
68 | os.rename(
69 | os.path.join(self.icon_dir, '{}.png'.format(module_name.replace('_', ' '))),
70 | icon_path)
71 | # This incantation reverts the intensity channel in HSI. It will make light colors darker, and dark colors lighter
72 | res = subprocess.run(["convert", icon_path, "-colorspace", "HSI", "-channel", "B", "-level", "100,0%", "+channel", "-colorspace", "sRGB", icon_path])
73 | if res.returncode != 0:
74 | raise Exception(f"Failed to run magick convert on {icon_path}.")
75 |
76 | generator = Generator()
77 | generator.generate()
78 |
--------------------------------------------------------------------------------
/generic_node.mustache:
--------------------------------------------------------------------------------
1 | import bpy
2 | import ladybug_tools.helper
3 | from bpy.props import StringProperty
4 | from sverchok.node_tree import SverchCustomTreeNode
5 | from sverchok.data_structure import updateNode, zip_long_repeat
6 |
7 | ghenv = ladybug_tools.helper.ghenv
8 |
9 | class Sv{{{nickname}}}(bpy.types.Node, SverchCustomTreeNode):
10 | bl_idname = 'Sv{{{nickname}}}'
11 | bl_label = '{{{name}}}'
12 | sv_icon = 'LB_{{{nickname_uppercase}}}'
13 | {{#inputs}}
14 | sv_{{{name}}}: StringProperty(
15 | name='{{{name}}}',
16 | update=updateNode,
17 | description='{{{description}}}')
18 | {{/inputs}}
19 |
20 | def sv_init(self, context):
21 | self.width *= 1.3
22 | {{#inputs}}
23 | input_node = self.inputs.new('SvLBSocket', '{{{name}}}')
24 | input_node.prop_name = 'sv_{{{name}}}'
25 | input_node.tooltip = '{{{description}}}'
26 | {{/inputs}}
27 | {{#outputs}}
28 | output_node = self.outputs.new('SvLBSocket', '{{{name}}}')
29 | output_node.tooltip = '{{{description}}}'
30 | {{/outputs}}
31 |
32 | def draw_buttons(self, context, layout):
33 | op = layout.operator('node.sv_lb_socket_name', text='', icon='QUESTION', emboss=False).tooltip = '{{{description}}}'
34 |
35 | def process(self):
36 | if not any(socket.is_linked for socket in self.outputs):
37 | return
38 |
39 | self.sv_output_names = [{{{output_name_list}}}]
40 | for name in self.sv_output_names:
41 | setattr(self, '{}_out'.format(name), [])
42 | self.sv_input_names = [{{{input_name_list}}}]
43 | self.sv_input_types = [{{{input_type_list}}}]
44 | self.sv_input_defaults = [{{{input_default_list}}}]
45 | self.sv_input_access = [{{{input_access_list}}}]
46 | sv_inputs_nested = []
47 | for name in self.sv_input_names:
48 | sv_inputs_nested.append(self.inputs[name].sv_get())
49 | for sv_input_nested in zip_long_repeat(*sv_inputs_nested):
50 | for sv_input in zip_long_repeat(*sv_input_nested):
51 | sv_input = list(sv_input)
52 | for i, value in enumerate(sv_input):
53 | if self.sv_input_access[i] == 'list':
54 | if isinstance(value, (list, tuple)):
55 | values = value
56 | else:
57 | values = [value]
58 | value = [self.sv_cast(v, self.sv_input_types[i], self.sv_input_defaults[i]) for v in values]
59 | if value == [None]:
60 | value = []
61 | sv_input[i] = value
62 | else:
63 | sv_input[i] = self.sv_cast(value, self.sv_input_types[i], self.sv_input_defaults[i])
64 | self.process_ladybug(*sv_input)
65 | for name in self.sv_output_names:
66 | value = getattr(self, '{}_out'.format(name))
67 | # Not sure if this hack is correct, will find out when more nodes are generated
68 | #if len(value) == 0 or not isinstance(value[0], (list, tuple)):
69 | # value = [value]
70 | self.outputs[name].sv_set(value)
71 |
72 | def sv_cast(self, value, data_type, default):
73 | result = default if isinstance(value, str) and value == '' else value
74 | if result is None and data_type == 'bool':
75 | return False
76 | elif result is not None and data_type == 'bool':
77 | if result == 'True' or result == '1':
78 | return True
79 | elif result == 'False' or result == '0':
80 | return False
81 | return bool(result)
82 | elif result is not None and data_type == 'int':
83 | return int(result)
84 | elif result is not None and data_type == 'double':
85 | return float(result)
86 | return result
87 |
88 | def process_ladybug(self, {{{input_name_unquoted_list}}}):
89 | {{{code}}}
90 |
91 | for name in self.sv_output_names:
92 | if name in locals():
93 | getattr(self, '{}_out'.format(name)).append([locals()[name]])
94 |
95 |
96 | def register():
97 | bpy.utils.register_class(Sv{{{nickname}}})
98 |
99 | def unregister():
100 | bpy.utils.unregister_class(Sv{{{nickname}}})
101 |
--------------------------------------------------------------------------------
/ladybug_tools/fromobjects.py:
--------------------------------------------------------------------------------
1 | """Functions to translate entire Ladybug core objects to Rhino geometries.
2 |
3 | The methods here are intended to help translate groups of geometry that are commonly
4 | generated by several objects in Ladybug core (ie. legends, compasses, etc.)
5 | """
6 |
7 | from .fromgeometry import from_mesh3d, from_arc2d, from_linesegment2d
8 | from .text import text_objects, LadybugText
9 |
10 | try:
11 | from ladybug_geometry.geometry3d.pointvector import Point3D
12 | from ladybug_geometry.geometry3d.plane import Plane
13 | except ImportError as e:
14 | raise ImportError("Failed to import ladybug_geometry.\n{}".format(e))
15 |
16 |
17 | def legend_objects(legend):
18 | """Translate a Ladybug Legend object into Grasshopper geometry.
19 |
20 | Args:
21 | legend: A Ladybug Legend object to be converted to Rhino geometry.
22 |
23 | Returns:
24 | A list of Rhino geometries in the following order.
25 |
26 | - legend_mesh -- A colored mesh for the legend.
27 |
28 | - legend_title -- A bake-able text object for the legend title.
29 |
30 | - legend_text -- Bake-able text objects for the rest of the legend text.
31 | """
32 | _height = legend.legend_parameters.text_height
33 | _font = legend.legend_parameters.font
34 | legend_mesh = from_mesh3d(legend.segment_mesh)
35 | legend_title = text_objects(legend.title, legend.title_location, _height, _font)
36 | if legend.legend_parameters.continuous_legend is False:
37 | legend_text = [text_objects(txt, loc, _height, _font, 0, 5) for txt, loc in
38 | zip(legend.segment_text, legend.segment_text_location)]
39 | elif legend.legend_parameters.vertical is True:
40 | legend_text = [text_objects(txt, loc, _height, _font, 0, 3) for txt, loc in
41 | zip(legend.segment_text, legend.segment_text_location)]
42 | else:
43 | legend_text = [text_objects(txt, loc, _height, _font, 1, 5) for txt, loc in
44 | zip(legend.segment_text, legend.segment_text_location)]
45 | return [legend_mesh] + [legend_title] + legend_text
46 |
47 |
48 | def compass_objects(compass, z=0, custom_angles=None, projection=None, font='Arial'):
49 | """Translate a Ladybug Compass object into Grasshopper geometry.
50 |
51 | Args:
52 | compass: A Ladybug Compass object to be converted to Rhino geometry.
53 | z: A number for the Z-coordinate to be used in translation. (Default: 0)
54 | custom_angles: An array of numbers between 0 and 360 to be used to
55 | generate custom angle labels around the compass.
56 | projection: Text for the name of the projection to use from the sky
57 | dome hemisphere to the 2D plane. If None, no altitude circles o
58 | labels will be drawn (Default: None). Choose from the following:
59 |
60 | * Orthographic
61 | * Stereographic
62 |
63 | font: Optional text for the font to be used in creating the text.
64 | (Default: 'Arial')
65 |
66 | Returns:
67 | A list of Rhino geometries in the following order.
68 |
69 | - all_boundary_circles -- Three Circle objects for the compass boundary.
70 |
71 | - major_azimuth_ticks -- Line objects for the major azimuth labels.
72 |
73 | - major_azimuth_text -- Bake-able text objects for the major azimuth labels.
74 |
75 | - minor_azimuth_ticks -- Line objects for the minor azimuth labels
76 | (if applicable).
77 |
78 | - minor_azimuth_text -- Bake-able text objects for the minor azimuth
79 | labels (if applicable).
80 |
81 | - altitude_circles -- Circle objects for the altitude labels.
82 |
83 | - altitude_text -- Bake-able text objects for the altitude labels.
84 |
85 | """
86 | # set default variables based on the compass properties
87 | maj_txt = compass.radius / 20
88 | min_txt = maj_txt / 2
89 |
90 | result = [] # list to hold all of the returned objects
91 | for circle in compass.all_boundary_circles:
92 | result.append(from_arc2d(circle, z))
93 |
94 | # generate the labels and tick marks for the azimuths
95 | if custom_angles is None:
96 | for line in compass.major_azimuth_ticks:
97 | result.append(from_linesegment2d(line, z))
98 | for txt, pt in zip(compass.MAJOR_TEXT, compass.major_azimuth_points):
99 | result.append(text_objects(
100 | txt, Plane(o=Point3D(pt.x, pt.y, z)), maj_txt, font, 1, 3))
101 | for line in compass.minor_azimuth_ticks:
102 | result.append(from_linesegment2d(line, z))
103 | for txt, pt in zip(compass.MINOR_TEXT, compass.minor_azimuth_points):
104 | result.append(text_objects(
105 | txt, Plane(o=Point3D(pt.x, pt.y, z)), min_txt, font, 1, 3))
106 | else:
107 | for line in compass.ticks_from_angles(custom_angles):
108 | result.append(from_linesegment2d(line, z))
109 | for txt, pt in zip(custom_angles, compass.label_points_from_angles(custom_angles)):
110 | result.append(text_objects(
111 | str(txt), Plane(o=Point3D(pt.x, pt.y, z)), maj_txt, font, 1, 3))
112 |
113 | # generate the labels and tick marks for the altitudes
114 | if projection is not None:
115 | if projection.title() == 'Orthographic':
116 | for circle in compass.orthographic_altitude_circles:
117 | result.append(from_arc2d(circle, z))
118 | for txt, pt in zip(compass.ALTITUDES, compass.orthographic_altitude_points):
119 | result.append(text_objects(
120 | str(txt), Plane(o=Point3D(pt.x, pt.y, z)), min_txt, font, 1, 0))
121 | elif projection.title() == 'Stereographic':
122 | for circle in compass.stereographic_altitude_circles:
123 | result.append(from_arc2d(circle, z))
124 | for txt, pt in zip(compass.ALTITUDES, compass.stereographic_altitude_points):
125 | result.append(text_objects(
126 | str(txt), Plane(o=Point3D(pt.x, pt.y, z)), min_txt, font, 1, 0))
127 |
128 | return result
129 |
--------------------------------------------------------------------------------
/ladybug_tools/togeometry.py:
--------------------------------------------------------------------------------
1 | """Functions to create Ladybug geometries from Rhino geometries."""
2 |
3 | import bpy
4 | import mathutils
5 |
6 | try:
7 | from ladybug_geometry.geometry2d.pointvector import Vector2D, Point2D
8 | from ladybug_geometry.geometry2d.ray import Ray2D
9 | from ladybug_geometry.geometry2d.line import LineSegment2D
10 | from ladybug_geometry.geometry2d.polygon import Polygon2D
11 | from ladybug_geometry.geometry2d.mesh import Mesh2D
12 | from ladybug_geometry.geometry3d.pointvector import Vector3D, Point3D
13 | from ladybug_geometry.geometry3d.ray import Ray3D
14 | from ladybug_geometry.geometry3d.line import LineSegment3D
15 | from ladybug_geometry.geometry3d.plane import Plane
16 | from ladybug_geometry.geometry3d.mesh import Mesh3D
17 | from ladybug_geometry.geometry3d.face import Face3D
18 | from ladybug_geometry.geometry3d.polyface import Polyface3D
19 | except ImportError as e:
20 | raise ImportError(
21 | "Failed to import ladybug_geometry.\n{}".format(e))
22 | try:
23 | import ladybug.color as lbc
24 | except ImportError as e:
25 | raise ImportError("Failed to import ladybug.\n{}".format(e))
26 |
27 | #import ladybug_rhino.planarize as _planar
28 | #from .config import tolerance
29 |
30 |
31 | """____________2D GEOMETRY TRANSLATORS____________"""
32 |
33 |
34 | def to_vector2d(vector):
35 | """Ladybug Vector2D from Rhino Vector3d."""
36 | if isinstance(vector, Vector2D):
37 | return vector
38 | elif isinstance(vector, (list, tuple)):
39 | return Vector2D(vector[0], vector[1])
40 |
41 |
42 | def to_point2d(point):
43 | """Ladybug Point2D from Rhino Point3d."""
44 | if isinstance(point, Point3D):
45 | return Point2D(point.x, point.y)
46 | elif isinstance(point, Point2D):
47 | return point
48 | elif isinstance(point, (list, tuple)):
49 | return Point2D(point[0], point[1])
50 |
51 |
52 | def to_ray2d(ray):
53 | """Ladybug Ray2D from Rhino Ray3d."""
54 | return ray
55 |
56 |
57 | def to_linesegment2d(line):
58 | """Ladybug LineSegment2D from Rhino LineCurve."""
59 | return line
60 |
61 |
62 | def to_polygon2d(polygon):
63 | """Ladybug Polygon2D from Rhino closed PolyLineCurve."""
64 | return polygon
65 |
66 |
67 | def to_mesh2d(mesh, color_by_face=True):
68 | """Ladybug Mesh2D from Rhino Mesh."""
69 | return mesh
70 |
71 |
72 | """____________3D GEOMETRY TRANSLATORS____________"""
73 |
74 |
75 | def to_vector3d(vector):
76 | """Ladybug Vector3D from Rhino Vector3d."""
77 | return vector
78 |
79 |
80 | def to_point3d(point):
81 | """Ladybug Point3D from Rhino Point3d."""
82 | if isinstance(point, Point3D):
83 | return point
84 | elif isinstance(point, (list, tuple, mathutils.Vector)):
85 | return Point3D(point[0], point[1], point[2])
86 | elif isinstance(point, bpy.types.MeshVertex):
87 | return Point3D(point.co[0], point.co[1], point.co[2])
88 |
89 |
90 | def to_ray3d(ray):
91 | """Ladybug Ray3D from Rhino Ray3d."""
92 | return ray
93 |
94 |
95 | def to_linesegment3d(line):
96 | """Ladybug LineSegment3D from Rhino LineCurve."""
97 | return line
98 |
99 |
100 | def to_plane(pl):
101 | """Ladybug Plane from Rhino Plane."""
102 | return pl
103 |
104 |
105 | def to_face3d(geo, meshing_parameters=None):
106 | """List of Ladybug Face3D objects from a Rhino Brep, Surface or Mesh.
107 |
108 | Args:
109 | brep: A Rhino Brep, Surface or Mesh that will be converted into a list
110 | of Ladybug Face3D.
111 | meshing_parameters: Optional Rhino Meshing Parameters to describe how
112 | curved faces should be converted into planar elements. If None,
113 | Rhino's Default Meshing Parameters will be used.
114 | """
115 | return geo
116 |
117 |
118 | def to_polyface3d(geo, meshing_parameters=None):
119 | """A Ladybug Polyface3D object from a Rhino Brep.
120 |
121 | Args:
122 | geo: A Rhino Brep, Surface ro Mesh that will be converted into a single
123 | Ladybug Polyface3D.
124 | meshing_parameters: Optional Rhino Meshing Parameters to describe how
125 | curved faces should be converted into planar elements. If None,
126 | Rhino's Default Meshing Parameters will be used.
127 | """
128 | return geo
129 |
130 |
131 | def to_mesh3d(mesh, color_by_face=True):
132 | """Ladybug Mesh3D from Rhino Mesh."""
133 | if isinstance(mesh, Mesh3D):
134 | return mesh
135 | elif isinstance(mesh, bpy.types.Object):
136 | lb_verts = tuple(to_point3d(mesh.matrix_world @ pt.co) for pt in mesh.data.vertices)
137 | lb_faces, colors = _extract_mesh_faces_colors(mesh, mesh.data, color_by_face)
138 | return Mesh3D(lb_verts, lb_faces, colors)
139 |
140 |
141 | """________ADDITIONAL 3D GEOMETRY TRANSLATORS________"""
142 |
143 |
144 | def to_gridded_mesh3d(brep, grid_size, offset_distance=0):
145 | """Create a gridded Ladybug Mesh3D from a Rhino Brep.
146 |
147 | This is useful since Rhino's grid meshing is often more beautiful than what
148 | ladybug_geometry can produce. However, the ladybug_geometry Face3D.get_mesh_grid
149 | method provides a workable alternative to this if it is needed.
150 |
151 | Args:
152 | brep: A Rhino Brep that will be converted into a gridded Ladybug Mesh3D.
153 | grid_size: A number for the grid size dimension with which to make the mesh.
154 | offset_distance: A number for the distance at which to offset the mesh from
155 | the underlying brep. The default is 0.
156 | """
157 | # For now, let blender handle gridding via subdiv modifier
158 | new_data = bpy.data.meshes.new_from_object(brep.evaluated_get(bpy.context.evaluated_depsgraph_get()))
159 | new_data.transform(brep.matrix_world)
160 | new = bpy.data.objects.new('Evaluated Object', new_data)
161 | for vertex in new.data.vertices:
162 | vertex.co = vertex.co + (vertex.normal * offset_distance)
163 | return to_mesh3d(new)
164 |
165 |
166 | def to_joined_gridded_mesh3d(geometry, grid_size, offset_distance=0):
167 | """Create a single gridded Ladybug Mesh3D from an array of Rhino geometry.
168 |
169 | Args:
170 | breps: An array of Rhino Breps and/or Rhino meshes that will be converted
171 | into a single, joined gridded Ladybug Mesh3D.
172 | grid_size: A number for the grid size dimension with which to make the mesh.
173 | offset_distance: A number for the distance at which to offset the mesh from
174 | the underlying brep. The default is 0.
175 | """
176 | lb_meshes = []
177 | for geo in geometry:
178 | if isinstance(geo, bpy.types.Object):
179 | lb_meshes.append(to_gridded_mesh3d(geo, grid_size, offset_distance))
180 | else: # assume that it's a Mesh
181 | lb_meshes.append(to_mesh3d(geo))
182 | if len(lb_meshes) == 1:
183 | return lb_meshes[0]
184 | else:
185 | return Mesh3D.join_meshes(lb_meshes)
186 |
187 |
188 | """________________EXTRA HELPER FUNCTIONS________________"""
189 |
190 |
191 | def _extract_mesh_faces_colors(obj, mesh, color_by_face):
192 | """Extract face indices and colors from a Rhino mesh."""
193 | colors = None
194 | lb_faces = []
195 | colors = []
196 | for face in mesh.polygons:
197 | # TODO: does LB handle ngons?
198 | lb_faces.append(tuple(face.vertices))
199 | if obj.material_slots:
200 | c = obj.material_slots[face.material_index].material.diffuse_color
201 | colors.append(lbc.Color(int(c[0]*255), int(c[1]*255), int(c[2]*255)))
202 | else:
203 | colors.append(lbc.Color(0, 0, 0))
204 | return lb_faces, colors
205 |
--------------------------------------------------------------------------------
/ladybug_tools/nodes/ladybug/LB_Out.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.props import BoolProperty, StringProperty
3 | from bpy.types import Operator
4 | from sverchok.node_tree import SverchCustomTreeNode
5 | from sverchok.data_structure import multi_socket, updateNode, zip_long_repeat
6 |
7 | from ladybug_tools.text import LadybugText
8 | from ladybug_tools.colorize import ColoredPoint
9 | from ladybug_geometry.geometry2d.line import LineSegment2D
10 | from ladybug_geometry.geometry2d.arc import Arc2D
11 | from ladybug_geometry.geometry3d.arc import Arc3D
12 | from ladybug_geometry.geometry2d.mesh import Mesh2D
13 | from ladybug_geometry.geometry3d.mesh import Mesh3D
14 | from ladybug_geometry.geometry2d.pointvector import Point2D
15 | from ladybug_geometry.geometry3d.pointvector import Point3D
16 | from ladybug_geometry.geometry2d.polyline import Polyline2D
17 | from ladybug_geometry.geometry3d.polyline import Polyline3D
18 |
19 | from math import pi, sin, cos
20 | from mathutils import Vector, Matrix
21 |
22 | class SvLBOut(bpy.types.Node, SverchCustomTreeNode):
23 | bl_idname = 'SvLBOut'
24 | bl_label = 'LB Out'
25 | sv_icon = 'LB_OUT'
26 | base_name = 'geometry '
27 | multi_socket_type = 'SvStringsSocket'
28 | should_bake: BoolProperty(default=False, update=updateNode, name="BAKE ?")
29 |
30 | def sv_init(self, context):
31 | self.inputs.new('SvStringsSocket', 'geometry')
32 | self.outputs.new('SvVerticesSocket', "verts")
33 | self.outputs.new('SvStringsSocket', "edges")
34 | self.outputs.new('SvStringsSocket', "faces")
35 |
36 | def sv_update(self):
37 | if len(self.outputs) > 0:
38 | multi_socket(self, min=1)
39 |
40 | def draw_buttons(self, context, layout):
41 | r0 = layout.row()
42 | r0.prop(self, "should_bake")
43 |
44 | def process(self):
45 | self.v = []
46 | self.e = []
47 | self.f = []
48 | self.text_v = []
49 | self.text_s = []
50 | self.blender_v = []
51 | self.blender_colored_v = []
52 |
53 | for socket in self.inputs:
54 | if not (socket.is_linked and socket.links):
55 | continue
56 | for geometries in socket.sv_get():
57 | for geometry in geometries:
58 | self._process_geometry(geometry)
59 |
60 | if self.should_bake:
61 | self.create_blender_colored_v()
62 | self.create_wireframe([Vector(xyz) for xyz in self.blender_v], [])
63 | self.outputs['verts'].sv_set(self.v)
64 | self.outputs['edges'].sv_set(self.e)
65 | self.outputs['faces'].sv_set(self.f)
66 |
67 | def _process_geometry(self, geometry):
68 | if isinstance(geometry, (tuple, list)):
69 | for g in geometry:
70 | self._process_geometry(g)
71 | return
72 | self._process_sverchok_geometry(geometry)
73 | if self.should_bake:
74 | self._process_blender_geometry(geometry)
75 |
76 | def _process_sverchok_geometry(self, geometry):
77 | if isinstance(geometry, Arc2D):
78 | self.sverchok_from_arc2d(geometry)
79 | elif isinstance(geometry, Arc3D):
80 | self.sverchok_from_arc3d(geometry)
81 | elif isinstance(geometry, LineSegment2D):
82 | self.sverchok_from_linesegment2d(geometry)
83 | elif isinstance(geometry, (Point2D, Point3D)):
84 | self.sverchok_from_point(geometry)
85 | elif isinstance(geometry, (Polyline2D, Polyline3D)):
86 | self.sverchok_from_polyline(geometry)
87 | elif isinstance(geometry, (float, int, tuple, list, str)):
88 | pass # The user probably connected a non geometry node
89 | else:
90 | print('WARNING: geometry {} not yet supported in Sverchok: {}'.format(type(geometry), geometry))
91 |
92 | def _process_blender_geometry(self, geometry):
93 | if isinstance(geometry, Arc2D):
94 | self.blender_from_arc2d(geometry)
95 | elif isinstance(geometry, Arc3D):
96 | self.blender_from_arc3d(geometry)
97 | elif isinstance(geometry, ColoredPoint):
98 | self.blender_colored_v.append(geometry)
99 | elif isinstance(geometry, LineSegment2D):
100 | self.blender_from_linesegment2d(geometry)
101 | elif isinstance(geometry, LadybugText):
102 | self.blender_from_text(geometry)
103 | elif isinstance(geometry, (Mesh2D, Mesh3D)):
104 | self.blender_from_mesh(geometry)
105 | elif isinstance(geometry, (Point2D, Point3D)):
106 | # Points are much more efficient in a single mesh
107 | self.blender_v.append(self.from_point(geometry))
108 | elif isinstance(geometry, (Polyline2D, Polyline3D)):
109 | self.blender_from_polyline(geometry)
110 | elif isinstance(geometry, (float, int, tuple, list, str)):
111 | pass # The user probably connected a non geometry node
112 | else:
113 | print('WARNING: geometry {} not yet supported in Blender: {}'.format(type(geometry), geometry))
114 |
115 | def from_linesegment2d(self, line, z=0):
116 | """Rhino LineCurve from ladybug LineSegment2D."""
117 | v = [(line.p1.x, line.p1.y, z), (line.p2.x, line.p2.y, z)]
118 | return v, [[0, 1]]
119 |
120 | def sverchok_from_linesegment2d(self, line, z=0):
121 | v, e = self.from_linesegment2d(line, z)
122 | self.v.append(v)
123 | self.e.append(e)
124 | self.f.append([[0]]) # Hack
125 |
126 | def blender_from_linesegment2d(self, line, z=0):
127 | self.create_wireframe(*self.from_linesegment2d(line))
128 |
129 | def from_arc2d(self, arc, z=0):
130 | """Rhino Arc from ladybug Arc2D."""
131 | arc_perimeter = (arc.a2-arc.a1)*arc.r
132 | # TODO: unhardcode facetation of 32 times
133 | v = []
134 | e = []
135 | step = (arc.a2 - arc.a1) / 32
136 | for i in range(0, 32 + 1):
137 | a = arc.a1 + i * step
138 | v.append((cos(a)*arc.r+arc.c.x, sin(a)*arc.r+arc.c.y, z))
139 | e.append((i, i+1))
140 | del e[-1]
141 | return v, e
142 |
143 | def sverchok_from_arc2d(self, arc, z=0):
144 | v, e = self.from_arc2d(arc, z)
145 | self.v.append(v)
146 | self.e.append(e)
147 | self.f.append([[0]]) # Hack
148 |
149 | def blender_from_arc2d(self, arc, z=0):
150 | self.create_wireframe(*self.from_arc2d(arc))
151 |
152 | def from_arc3d(self, arc):
153 | """Rhino Arc from ladybug Arc3D."""
154 | if arc.is_circle:
155 | assert False, 'I have not yet built circular arcs'
156 | else:
157 | # TODO: unhardcode facetation of 32 times
158 | v = []
159 | e = []
160 | a1 = arc.a1
161 | # I'm assuming that a1 and a2 is _always_ ordered from small to large
162 | a2 = arc.a2 if arc.a1 < arc.a2 else arc.a2 + (2 * pi)
163 | step = (a2 - a1) / 32
164 | p = arc.plane
165 | mat = Matrix((
166 | (p.x.x, p.y.x, p.n.x, p.o.x),
167 | (p.x.y, p.y.y, p.n.y, p.o.y),
168 | (p.x.z, p.y.z, p.n.z, p.o.z),
169 | (0, 0, 0, 1),
170 | ))
171 | for i in range(0, 32 + 1):
172 | a = a1 + i * step
173 | co = Vector((cos(a)*arc.radius, sin(a)*arc.radius, 0))
174 | v.append(mat @ co)
175 | e.append((i, i+1))
176 | del e[-1]
177 | return v, e
178 |
179 | def sverchok_from_arc3d(self, arc):
180 | v, e = self.from_arc3d(arc)
181 | self.v.append(v)
182 | self.e.append(e)
183 | self.f.append([[0]]) # Hack
184 |
185 | def blender_from_arc3d(self, arc):
186 | self.create_wireframe(*self.from_arc3d(arc))
187 |
188 | def blender_from_mesh(self, mesh, z=0):
189 | """Rhino Mesh from ladybug Mesh2D."""
190 | data = bpy.data.meshes.new('Ladybug Mesh')
191 | data.from_pydata([Vector((v.x, v.y, v.z if hasattr(v, 'z') else 0)) for v in mesh.vertices], [], mesh.faces)
192 | def get_material_name(color):
193 | return 'ladybug-{}-{}-{}-{}'.format(color.r, color.g, color.b, color.a)
194 |
195 | if mesh.is_color_by_face:
196 | colors = list(set(mesh.colors))
197 | material_to_slot = {}
198 | for i, color in enumerate(colors):
199 | name = get_material_name(color)
200 | material_to_slot[name] = i
201 | material = bpy.data.materials.get(name)
202 | if not material:
203 | material = bpy.data.materials.new(name)
204 | material.diffuse_color = (color.r / 255, color.g / 255, color.b / 255, color.a / 255)
205 | material.specular_intensity = 0
206 | data.materials.append(material)
207 | material_index = [material_to_slot[get_material_name(c)] for c in mesh.colors]
208 | data.polygons.foreach_set('material_index', material_index)
209 | else:
210 | material = bpy.data.materials.get('LB_VCol')
211 | if not material:
212 | material = bpy.data.materials.new('LB_VCol')
213 | material.use_nodes = True
214 | for node in material.node_tree.nodes:
215 | if node.type == 'OUTPUT_MATERIAL':
216 | output_node = node
217 | break
218 | emission = material.node_tree.nodes.new(type='ShaderNodeEmission')
219 | attribute = material.node_tree.nodes.new(type='ShaderNodeAttribute')
220 | attribute.attribute_name = 'LB_Col'
221 | material.node_tree.links.new(attribute.outputs[0], emission.inputs[0])
222 | material.node_tree.links.new(emission.outputs[0], output_node.inputs[0])
223 | data.materials.append(material)
224 | data.vertex_colors.new(name='LB_Col')
225 | for polygon in data.polygons:
226 | for i, vi in enumerate(polygon.vertices):
227 | loop_index = polygon.loop_indices[i]
228 | color = mesh.colors[vi]
229 | data.vertex_colors['LB_Col'].data[loop_index].color = (color.r / 255, color.g / 255, color.b / 255, color.a / 255)
230 | obj = bpy.data.objects.new('Ladybug Mesh', data)
231 | bpy.context.scene.collection.objects.link(obj)
232 |
233 | def from_point(self, point):
234 | """Rhino Point3d from ladybug Point3D."""
235 | return (point.x, point.y, point.z if hasattr(point, 'z') else 0)
236 |
237 | def sverchok_from_point(self, point):
238 | self.v.append([self.from_point(point)])
239 | self.e.append([[0, 0]]) # Hack
240 | self.f.append([[0]]) # Hack
241 |
242 | def from_polyline(self, polyline, z=0):
243 | """Rhino closed PolyLineCurve from ladybug Polyline3D."""
244 | v = [(p.x, p.y, p.z if hasattr(p, 'z') else z) for p in polyline.vertices]
245 | e = [(i, i+1) for i in range(0, len(polyline.vertices)-1)]
246 | if polyline.interpolated:
247 | print('TODO: interpolate this polyline')
248 | return v, e
249 | self.v.append(v)
250 | self.e.append(e)
251 | self.f.append([[0]]) # Hack
252 | else:
253 | return v, e
254 | self.v.append(v)
255 | self.e.append(e)
256 | self.f.append([[0]]) # Hack
257 |
258 | def sverchok_from_polyline(self, polyline, z=0):
259 | v, e = self.from_polyline(polyline, z)
260 | self.v.append(v)
261 | self.e.append(e)
262 | self.f.append([[0]]) # Hack
263 |
264 | def blender_from_polyline(self, polyline, z=0):
265 | self.create_wireframe(*self.from_polyline(polyline, z))
266 |
267 | def blender_from_text(self, text):
268 | data = bpy.data.curves.new('Ladybug Text', 'FONT')
269 | data.body = text.text
270 | data.size = text.height
271 |
272 | if text.horizontal_alignment == 0:
273 | data.align_x = 'LEFT'
274 | elif text.horizontal_alignment == 1:
275 | data.align_x = 'CENTER'
276 | elif text.horizontal_alignment == 2:
277 | data.align_x = 'RIGHT'
278 |
279 | if text.vertical_alignment <= 2:
280 | data.align_y = 'TOP'
281 | elif text.vertical_alignment <= 4:
282 | data.align_y = 'CENTER'
283 | elif text.vertical_alignment <= 6:
284 | data.align_y = 'BOTTOM'
285 |
286 | name = 'ladybug-0-0-0-255'
287 | material = bpy.data.materials.get(name)
288 | if not material:
289 | material = bpy.data.materials.new(name)
290 | material.diffuse_color = (0, 0, 0, 255)
291 | material.specular_intensity = 0
292 | data.materials.append(material)
293 |
294 | obj = bpy.data.objects.new('Ladybug Text', data)
295 | obj.location = (text.plane.o.x, text.plane.o.y, text.plane.o.z)
296 | bpy.context.scene.collection.objects.link(obj)
297 |
298 | def create_blender_colored_v(self):
299 | if not self.blender_colored_v:
300 | return
301 | import numpy as np
302 | from space_view3d_point_cloud_visualizer import PCVControl
303 | obj = bpy.data.objects.new('Ladybug Colored Points', None)
304 | vs = [(cv.point.x, cv.point.y, cv.point.z if hasattr(cv.point, 'z') else 0) for cv in self.blender_colored_v]
305 | cs = [(cv.color.r/255, cv.color.g/255, cv.color.b/255) for cv in self.blender_colored_v]
306 | PCVControl(obj).draw(vs, [], cs)
307 | bpy.context.scene.collection.objects.link(obj)
308 |
309 | def create_wireframe(self, v, e):
310 | data = bpy.data.meshes.new('Ladybug Wireframe')
311 | data.from_pydata([Vector(xyz) for xyz in v], e, [])
312 | obj = bpy.data.objects.new('Ladybug Wireframe', data)
313 | bpy.context.scene.collection.objects.link(obj)
314 |
315 |
316 | def register():
317 | bpy.utils.register_class(SvLBOut)
318 |
319 | def unregister():
320 | bpy.utils.unregister_class(SvLBOut)
321 |
--------------------------------------------------------------------------------
/ladybug_tools/sverchok.py:
--------------------------------------------------------------------------------
1 | """Functions for dealing with inputs and outputs from Grasshopper components."""
2 | import collections
3 | import multiprocessing
4 | import types
5 |
6 | # Stub for .net tasks.
7 |
8 | def for_each(iterable, fn):
9 | for i in iterable:
10 | fn(i)
11 | return # Does this work in Sverchok?
12 |
13 | pool = multiprocessing.Pool()
14 | pool.map(fn, iterable)
15 | pool.close()
16 | pool.join()
17 |
18 | tasks = types.SimpleNamespace()
19 | Parallel = types.SimpleNamespace()
20 | Parallel.ForEach = for_each
21 | tasks.Parallel = Parallel
22 |
23 |
24 | def give_warning(component, message):
25 | """Give a warning message (turning the component orange).
26 |
27 | Args:
28 | component: The grasshopper component object, which can be accessed through
29 | the ghenv.Component call within Grasshopper API.
30 | message: Text string for the warning message.
31 | """
32 | return "TODO"
33 | component.AddRuntimeMessage(Message.Warning, message)
34 |
35 |
36 | def give_remark(component, message):
37 | """Give an remark message (giving a little grey ballon in the upper left).
38 |
39 | Args:
40 | component: The grasshopper component object, which can be accessed through
41 | the ghenv.Component call within Grasshopper API.
42 | message: Text string for the warning message.
43 | """
44 | return "TODO"
45 | component.AddRuntimeMessage(Message.Remark, message)
46 |
47 |
48 | def give_popup_message(message, window_title='', icon_type='information'):
49 | """Give a Windows popup message with an OK button.
50 |
51 | Useful in cases where you really need the user to pay attention to the message.
52 |
53 | Args:
54 | message: Text string for the popup message.
55 | window_title: Text string for the title of the popup window. (Default: "").
56 | icon_type: Text for the type of icon to be used. (Default: "information").
57 | Choose from the following options.
58 |
59 | * information
60 | * warning
61 | * error
62 |
63 | """
64 | print(icon_type, window_title, message)
65 | return "TODO"
66 | icon_types = {
67 | 'information': Forms.MessageBoxIcon.Information,
68 | 'warning': Forms.MessageBoxIcon.Warning,
69 | 'error': Forms.MessageBoxIcon.Error
70 | }
71 | icon = icon_types[icon_type]
72 | buttons = Forms.MessageBoxButtons.OK
73 | rui.Dialogs.ShowMessageBox(message, window_title, buttons, icon)
74 |
75 |
76 | def all_required_inputs(component):
77 | """Check that all required inputs on a component are present.
78 |
79 | Note that this method needs required inputs to be written in the correct
80 | format on the component in order to work (required inputs have a
81 | single _ at the start and no _ at the end).
82 |
83 | Args:
84 | component: The grasshopper component object, which can be accessed through
85 | the ghenv.Component call within Grasshopper API.
86 |
87 | Returns:
88 | True if all required inputs are present. False if they are not.
89 | """
90 | return "TODO"
91 | is_input_missing = False
92 | for param in component.Params.Input:
93 | if param.NickName.startswith('_') and not param.NickName.endswith('_'):
94 | missing = False
95 | if not param.VolatileDataCount:
96 | missing = True
97 | elif param.VolatileData[0][0] is None:
98 | missing = True
99 |
100 | if missing is True:
101 | msg = 'Input parameter {} failed to collect data!'.format(param.NickName)
102 | print(msg)
103 | give_warning(component, msg)
104 | is_input_missing = True
105 | return not is_input_missing
106 |
107 |
108 | def local_processor_count():
109 | """Get an integer for the number of processors on this machine.
110 |
111 | If, for whatever reason, the number of processors could not be sensed,
112 | None will be returned.
113 | """
114 | return multiprocessing.cpu_count()
115 |
116 |
117 | def recommended_processor_count():
118 | """Get an integer for the recommended number of processors for parallel calculation.
119 |
120 | This should be one less than the number of processors available on this machine
121 | unless the machine has only one processor, in which case 1 will be returned.
122 | If, for whatever reason, the number of processors could not be sensed, a value
123 | of 1 will be returned.
124 | """
125 | cpu_count = local_processor_count()
126 | return 1 if cpu_count is None or cpu_count <= 1 else cpu_count - 1
127 |
128 |
129 | def run_function_in_parallel(parallel_function, object_count, cpu_count=None):
130 | """Run any function in parallel given a number of objects to be iterated over.
131 |
132 | This method can run the calculation in a manner that targets a given CPU
133 | count and will also run the function normally (without the use of Tasks)
134 | if only one CPU is specified.
135 |
136 | Args:
137 | parallel_function: A function which will be iterated over in a parallelized
138 | manner. This function should have a single input argument, which
139 | is the integer of the object to be simulated. Note that, in order
140 | for this function to be successfully parallelized, any lists of
141 | output data must be set up beforehand and this parallel_function
142 | should simply be replacing the data in this pre-created list.
143 | object_count: An integer for the number of objects which will be iterated over
144 | in a parallelized manner.
145 | cpu_count: An integer for the number of CPUs to be used in the intersection
146 | calculation. The ladybug_rhino.grasshopper.recommended_processor_count
147 | function can be used to get a recommendation. If set to None, all
148 | available processors will be used. (Default: None).
149 | """
150 |
151 | def compute_each_object_group(worker_i):
152 | """Run groups of objects so that only the cpu_count is used."""
153 | start_i, stop_i = obj_groups[worker_i]
154 | for count in range(start_i, stop_i):
155 | parallel_function(count)
156 |
157 | if cpu_count is not None and cpu_count > 1:
158 | # group the objects in order to meet the cpu_count
159 | worker_count = min((cpu_count, object_count))
160 | i_per_group = int(math.ceil(object_count / worker_count))
161 | obj_groups = [[x, x + i_per_group] for x in range(0, object_count, i_per_group)]
162 | obj_groups[-1][-1] = object_count # ensure the last group ends with obj count
163 |
164 | if cpu_count is None: # use all availabe CPUs
165 | tasks.Parallel.ForEach(range(object_count), parallel_function)
166 | elif cpu_count <= 1: # run everything on a single processor
167 | for i in range(object_count):
168 | parallel_function(i)
169 | else: # run the groups in a manner that meets the CPU count
170 | tasks.Parallel.ForEach(range(len(obj_groups)), compute_each_object_group)
171 |
172 |
173 | def component_guid(component):
174 | """Get the unique ID associated with a specific component.
175 |
176 | This ID remains the same every time that the component is run.
177 |
178 | Args:
179 | component: The grasshopper component object, which can be accessed through
180 | the ghenv.Component call within Grasshopper API.
181 |
182 | Returns:
183 | Text string for the component's unique ID.
184 | """
185 | return "TODO"
186 | return component.GetHashCode().ToString()
187 |
188 |
189 | def bring_to_front(component):
190 | """Bring a component to the front of the canvas so that it is always executed last.
191 |
192 | Args:
193 | component: The grasshopper component object, which can be accessed through
194 | the ghenv.Component call within Grasshopper API.
195 | """
196 | return "TODO"
197 | doc = Instances.ActiveCanvas.Document.Objects
198 | in_front = doc[doc.Count - 1].InstanceGuid.Equals(component.InstanceGuid)
199 | if not in_front: # bring the component to the top
200 | component.OnPingDocument().DeselectAll() # de-select all components
201 | component.Attributes.Selected = True # select the component to move
202 | component.OnPingDocument().BringSelectionToTop()
203 | component.Attributes.Selected = False # de-select the component after moving
204 |
205 |
206 | def send_to_back(component):
207 | """Send a component to the back of the canvas so that it is always executed first.
208 |
209 | Args:
210 | component: The grasshopper component object, which can be accessed through
211 | the ghenv.Component call within Grasshopper API.
212 | """
213 | return "TODO"
214 | doc = Instances.ActiveCanvas.Document.Objects
215 | in_back = doc[0].InstanceGuid.Equals(component.InstanceGuid)
216 | if not in_back: # send the component to the back
217 | component.OnPingDocument().SelectAll() # select all components
218 | component.Attributes.Selected = False # de-select the component to move
219 | component.OnPingDocument().BringSelectionToTop()
220 | component.OnPingDocument().DeselectAll() # de-select all after moving
221 |
222 |
223 | def wrap_output(output):
224 | """Wrap Python objects as Grasshopper generic objects.
225 |
226 | Passing output lists of Python objects through this function can greatly reduce
227 | the time needed to run the component since Grasshopper can spend a long time
228 | figuring out the object type is if it is not recognized. However, if the number
229 | of output objects is usually < 100, running this method won't make a significant
230 | difference and so there's no need to use it.
231 |
232 | Args:
233 | output: A list of values to be wrapped as a generic Grasshopper Object (GOO).
234 | """
235 | return output
236 | if not output:
237 | return output
238 | try:
239 | return (Goo(i) for i in output)
240 | except Exception as e:
241 | raise ValueError('Failed to wrap {}:\n{}.'.format(output, e))
242 |
243 |
244 | def objectify_output(object_name, output_data):
245 | """Wrap data into a single custom Python object that can later be de-serialized.
246 |
247 | This is meant to address the same issue as the wrap_output method but it does
248 | so by simply hiding the individual items from the Grasshopper UI within a custom
249 | parent object that other components can accept as input and de-objectify to
250 | get access to the data. This strategy is also useful for the case of standard
251 | object types like integers where the large number of data points slows down
252 | the Grasshopper UI when they are output.
253 |
254 | Args:
255 | object_name: Text for the name of the custom object that will wrap the data.
256 | This is how the object will display in the Grasshopper UI.
257 | output_data: A list of data to be stored under the data property of
258 | the output object.
259 | """
260 | class Objectifier(object):
261 | """Generic class for objectifying data."""
262 |
263 | def __init__(self, name, data):
264 | self.name = name
265 | self.data = data
266 |
267 | def ToString(self):
268 | return '{} ({} items)'.format(self.name, len(self.data))
269 |
270 | return Objectifier(object_name, output_data)
271 |
272 |
273 | def de_objectify_output(objectified_data):
274 | """Extract the data from an object that was output from the objectify_output method.
275 |
276 | Args:
277 | objectified_data: An object that has been output from the objectify_output
278 | method for which data will be returned.
279 | """
280 | return objectified_data.data
281 |
282 |
283 | def document_counter(counter_name):
284 | """Get an integer for a counter name that advances each time this function is called.
285 |
286 | Args:
287 | counter_name: The name of the counter that will be advanced.
288 | """
289 | return "TODO"
290 | try: # get the counter and advance it one value
291 | scriptcontext.sticky[counter_name] += 1
292 | except KeyError: # first time that the counter is called
293 | scriptcontext.sticky[counter_name] = 1
294 | return scriptcontext.sticky[counter_name]
295 |
296 |
297 | def longest_list(values, index):
298 | """Get a value from a list while applying Grasshopper's longest-list logic.
299 |
300 | Args:
301 | values: An array of values from which a value will be pulled following
302 | longest list logic.
303 | index: Integer for the index of the item in the list to return. If this
304 | index is greater than the length of the values, the last item of the
305 | list will be returned.
306 | """
307 | try:
308 | return values[index]
309 | except IndexError:
310 | return values[-1]
311 |
312 |
313 | def data_tree_to_list(input):
314 | """Convert a grasshopper DataTree to nested lists of lists.
315 |
316 | Args:
317 | input: A Grasshopper DataTree.
318 |
319 | Returns:
320 | listData -- A list of namedtuples (path, dataList)
321 | """
322 | return input
323 | all_data = list(range(len(input.Paths)))
324 | pattern = collections.namedtuple('Pattern', 'path list')
325 |
326 | for i, path in enumerate(input.Paths):
327 | data = input.Branch(path)
328 | branch = pattern(path, [])
329 |
330 | for d in data:
331 | if d is not None:
332 | branch.list.append(d)
333 |
334 | all_data[i] = branch
335 |
336 | return all_data
337 |
338 |
339 | def list_to_data_tree(input, root_count=0, s_type=object):
340 | """Transform nested of lists or tuples to a Grasshopper DataTree.
341 |
342 | Args:
343 | input: A nested list of lists to be converted into a data tree.
344 | root_count: An integer for the starting path of the data tree.
345 | s_type: An optional data type (eg. float, int, str) that defines all of the
346 | data in the data tree. The default (object) works will all data types
347 | but the conversion to data trees can be more efficient if a more
348 | specific type is specified.
349 | """
350 | return input
351 |
352 | def proc(input, tree, track):
353 | for i, item in enumerate(input):
354 | if isinstance(item, (list, tuple, array.array)): # ignore iterables like str
355 | track.append(i)
356 | proc(item, tree, track)
357 | track.pop()
358 | else:
359 | tree.Add(item, Path(*track))
360 |
361 | if input is not None:
362 | t = DataTree[s_type]()
363 | proc(input, t, [root_count])
364 | return t
365 |
366 |
367 | def merge_data_tree(data_trees, s_type=object):
368 | """Merge a list of grasshopper DataTrees into a single DataTree.
369 |
370 | Args:
371 | input: A list Grasshopper DataTrees to be merged into one.
372 | s_type: An optional data type (eg. float, int, str) that defines all of the
373 | data in the data tree. The default (object) works will all data types
374 | but the conversion to data trees can be more efficient if a more
375 | specific type is specified.
376 | """
377 | return data_trees
378 | comb_tree = DataTree[s_type]()
379 | for d_tree in data_trees:
380 | for p, branch in zip(d_tree.Paths, d_tree.Branches):
381 | comb_tree.AddRange(branch, p)
382 | return comb_tree
383 |
384 |
385 | def flatten_data_tree(input):
386 | """Flatten and clean a grasshopper DataTree into a single list and a pattern.
387 |
388 | Args:
389 | input: A Grasshopper DataTree.
390 |
391 | Returns:
392 | A tuple with two elements
393 |
394 | - all_data -- All data in DataTree as a flattened list.
395 |
396 | - pattern -- A dictionary of patterns as namedtuple(path, index of last item
397 | on this path, path Count). Pattern is useful to un-flatten the list
398 | back to a DataTree.
399 | """
400 | return input
401 | Pattern = collections.namedtuple('Pattern', 'path index count')
402 | pattern = dict()
403 | all_data = []
404 | index = 0 # Global counter for all the data
405 | for i, path in enumerate(input.Paths):
406 | count = 0
407 | data = input.Branch(path)
408 |
409 | for d in data:
410 | if d is not None:
411 | count += 1
412 | index += 1
413 | all_data.append(d)
414 |
415 | pattern[i] = Pattern(path, index, count)
416 |
417 | return all_data, pattern
418 |
419 |
420 | def unflatten_to_data_tree(all_data, pattern):
421 | """Create DataTree from a single flattened list and a pattern.
422 |
423 | Args:
424 | all_data: A flattened list of all data
425 | pattern: A dictionary of patterns
426 | Pattern = namedtuple('Pattern', 'path index count')
427 |
428 | Returns:
429 | data_tree -- A Grasshopper DataTree.
430 | """
431 | return all_data
432 | data_tree = DataTree[Object]()
433 | for branch in range(len(pattern)):
434 | path, index, count = pattern[branch]
435 | data_tree.AddRange(all_data[index - count:index], path)
436 |
437 | return data_tree
438 |
439 |
440 | def recipe_result(result):
441 | """Process a recipe result and handle the case that it's a list of list.
442 |
443 | Args:
444 | result: A recipe result to be processed.
445 | """
446 | if isinstance(result, (list, tuple)):
447 | return list_to_data_tree(result)
448 | return result
449 |
450 |
451 | def hide_output(component, output_index):
452 | """Hide one of the outputs of a component.
453 |
454 | Args:
455 | component: The grasshopper component object, which can be accessed through
456 | the ghenv.Component call within Grasshopper API.
457 | output_index: Integer for the index of the output to hide.
458 | """
459 | return "TODO"
460 | component.Params.Output[output_index].Hidden = True
461 |
462 |
463 | def show_output(component, output_index):
464 | """Show one of the outputs of a component.
465 |
466 | Args:
467 | component: The grasshopper component object, which can be accessed through
468 | the ghenv.Component call within Grasshopper API.
469 | output_index: Integer for the index of the output to hide.
470 | """
471 | return
472 | component.Params.Output[output_index].Hidden = False
473 |
474 |
475 | def schedule_solution(component, milliseconds):
476 | """Schedule a new Grasshopper solution after a specified time interval.
477 |
478 | Args:
479 | component: The grasshopper component object, which can be accessed through
480 | the ghenv.Component call within Grasshopper API.
481 | milliseconds: Integer for the number of milliseconds after which the
482 | solution should happen.
483 | """
484 | return
485 | doc = component.OnPingDocument()
486 | doc.ScheduleSolution(milliseconds)
487 |
488 |
489 | # Empty method that LB requires.
490 | # Method itself seems to be Rhino specific
491 | # and doesn't require an implementation.
492 | def turn_off_old_tag(component): ...
493 |
--------------------------------------------------------------------------------
/ladybug_tools/intersect.py:
--------------------------------------------------------------------------------
1 | """Functions to handle intersection of Rhino geometries.
2 |
3 | These represent geometry computation methods that are either not supported by
4 | ladybug_geometry or there are much more efficient versions of them in Rhino.
5 | """
6 | import bpy
7 | import math
8 | import types
9 | import mathutils.geometry
10 | import array as specializedarray
11 | from .config import tolerance
12 | from mathutils import Vector, Matrix
13 |
14 |
15 | # Stub for .net tasks.
16 |
17 | def for_each(iterable, fn):
18 | for i in iterable:
19 | fn(i)
20 | return # Does this work in Sverchok?
21 |
22 | pool = multiprocessing.Pool()
23 | pool.map(fn, iterable)
24 | pool.close()
25 | pool.join()
26 |
27 | tasks = types.SimpleNamespace()
28 | Parallel = types.SimpleNamespace()
29 | Parallel.ForEach = for_each
30 | tasks.Parallel = Parallel
31 |
32 |
33 | def join_geometry_to_mesh(geometry):
34 | """Convert an array of Rhino Breps and/or Meshes into a single Rhino Mesh.
35 |
36 | This is a typical pre-step before using the intersect_mesh_rays function.
37 |
38 | Args:
39 | geometry: An array of Rhino Breps or Rhino Meshes.
40 | """
41 | copied_geometry = []
42 | for geo in geometry:
43 | new = geo.copy()
44 | new.data = new.data.copy()
45 | copied_geometry.append(new)
46 | c = {}
47 | c['object'] = c['active_object'] = copied_geometry[0]
48 | c['selected_objects'] = c['selected_editable_objects'] = copied_geometry
49 | bpy.ops.object.join(c)
50 | bpy.context.scene.collection.objects.link(copied_geometry[0])
51 | # Apply all transformations
52 | copied_geometry[0].data.transform(copied_geometry[0].matrix_world)
53 | copied_geometry[0].matrix_world = Matrix()
54 | return copied_geometry[0]
55 | for geo in geometry:
56 | if isinstance(geo, rg.Brep):
57 | meshes = rg.Mesh.CreateFromBrep(geo, rg.MeshingParameters.Default)
58 | for mesh in meshes:
59 | joined_mesh.Append(mesh)
60 | elif isinstance(geo, rg.Mesh):
61 | joined_mesh.Append(geo)
62 | else:
63 | raise TypeError('Geometry must be either a Brep or a Mesh. '
64 | 'Not {}.'.format(type(geo)))
65 | return joined_mesh
66 |
67 |
68 | def intersect_mesh_rays(
69 | mesh, points, vectors, normals=None, cpu_count=None, parallel=True):
70 | """Intersect a group of rays (represented by points and vectors) with a mesh.
71 |
72 | All combinations of rays that are possible between the input points and
73 | vectors will be intersected. This method exists since most CAD plugins have
74 | much more efficient mesh/ray intersection functions than ladybug_geometry.
75 | However, the ladybug_geometry Face3D.intersect_line_ray() method provides
76 | a workable (albeit very inefficient) alternative to this if it is needed.
77 |
78 | Args:
79 | mesh: A Rhino mesh that can block the rays.
80 | points: An array of Rhino points that will be used to generate rays.
81 | vectors: An array of Rhino vectors that will be used to generate rays.
82 | normals: An optional array of Rhino vectors that align with the input
83 | points and denote the direction each point is facing. These will
84 | be used to eliminate any cases where the vector and the normal differ
85 | by more than 90 degrees. If None, points are assumed to have no direction.
86 | cpu_count: An integer for the number of CPUs to be used in the intersection
87 | calculation. The ladybug_rhino.grasshopper.recommended_processor_count
88 | function can be used to get a recommendation. If set to None, all
89 | available processors will be used. (Default: None).
90 | parallel: Optional boolean to override the cpu_count and use a single CPU
91 | instead of multiple processors.
92 |
93 | Returns:
94 | A tuple with two elements
95 |
96 | - intersection_matrix -- A 2D matrix of 0's and 1's indicating the results
97 | of the intersection. Each sub-list of the matrix represents one of the
98 | points and has a length equal to the vectors. 0 indicates a blocked
99 | ray and 1 indicates a ray that was not blocked.
100 |
101 | - angle_matrix -- A 2D matrix of angles in radians. Each sub-list of the
102 | matrix represents one of the normals and has a length equal to the
103 | supplied vectors. Will be None if no normals are provided.
104 | """
105 | intersection_matrix = [0] * len(points) # matrix to be filled with results
106 | angle_matrix = [0] * len(normals) if normals is not None else None
107 | cutoff_angle = math.pi / 2 # constant used in all normal checks
108 | if not parallel:
109 | cpu_count = 1
110 |
111 | def intersect_point(i):
112 | """Intersect all of the vectors of a given point without any normal check."""
113 | pt = points[i]
114 | int_list = []
115 | for vec in vectors:
116 | is_clear = 0 if mesh.ray_cast(
117 | Vector((pt.x, pt.y, pt.z)),
118 | Vector((vec.x, vec.y, vec.z)))[0] else 1
119 | int_list.append(is_clear)
120 | intersection_matrix[i] = int_list
121 |
122 | def intersect_point_normal_check(i):
123 | """Intersect all of the vectors of a given point with a normal check."""
124 | pt, normal_vec = points[i], normals[i]
125 | int_list = []
126 | angle_list = []
127 | for vec in vectors:
128 | vec_angle = Vector((normal_vec.x, normal_vec.y, normal_vec.z)).angle(Vector((vec.x, vec.y, vec.z)))
129 | angle_list.append(vec_angle)
130 | if vec_angle <= cutoff_angle:
131 | is_clear = 0 if mesh.ray_cast(
132 | Vector((pt.x, pt.y, pt.z)),
133 | Vector((vec.x, vec.y, vec.z)))[0] else 1
134 | int_list.append(is_clear)
135 | else: # the vector is pointing behind the surface
136 | int_list.append(0)
137 | intersection_matrix[i] = specializedarray.array('B', int_list)
138 | angle_matrix[i] = specializedarray.array('d', angle_list)
139 |
140 | def intersect_each_point_group(worker_i):
141 | """Intersect groups of points so that only the cpu_count is used."""
142 | start_i, stop_i = pt_groups[worker_i]
143 | for count in range(start_i, stop_i):
144 | intersect_point(count)
145 |
146 | def intersect_each_point_group_normal_check(worker_i):
147 | """Intersect groups of points with distance check so only cpu_count is used."""
148 | start_i, stop_i = pt_groups[worker_i]
149 | for count in range(start_i, stop_i):
150 | intersect_point_normal_check(count)
151 |
152 | if cpu_count is not None and cpu_count > 1:
153 | # group the points in order to meet the cpu_count
154 | pt_count = len(points)
155 | worker_count = min((cpu_count, pt_count))
156 | i_per_group = int(math.ceil(pt_count / worker_count))
157 | pt_groups = [[x, x + i_per_group] for x in range(0, pt_count, i_per_group)]
158 | pt_groups[-1][-1] = pt_count # ensure the last group ends with point count
159 |
160 | if normals is not None:
161 | if cpu_count is None: # use all availabe CPUs
162 | tasks.Parallel.ForEach(range(len(points)), intersect_point_normal_check)
163 | elif cpu_count <= 1: # run everything on a single processor
164 | for i in range(len(points)):
165 | intersect_point_normal_check(i)
166 | else: # run the groups in a manner that meets the CPU count
167 | tasks.Parallel.ForEach(
168 | range(len(pt_groups)), intersect_each_point_group_normal_check)
169 | else:
170 | if cpu_count is None: # use all availabe CPUs
171 | tasks.Parallel.ForEach(range(len(points)), intersect_point)
172 | elif cpu_count <= 1: # run everything on a single processor
173 | for i in range(len(points)):
174 | intersect_point(i)
175 | else: # run the groups in a manner that meets the CPU count
176 | tasks.Parallel.ForEach(range(len(pt_groups)), intersect_each_point_group)
177 |
178 | return intersection_matrix, angle_matrix
179 |
180 |
181 | def intersect_mesh_lines(
182 | mesh, start_points, end_points, max_dist=None, cpu_count=None, parallel=True):
183 | """Intersect a group of lines (represented by start + end points) with a mesh.
184 |
185 | All combinations of lines that are possible between the input start_points and
186 | end_points will be intersected. This method exists since most CAD plugins have
187 | much more efficient mesh/line intersection functions than ladybug_geometry.
188 | However, the ladybug_geometry Face3D.intersect_line_ray() method provides
189 | a workable (albeit very inefficient) alternative to this if it is needed.
190 |
191 | Args:
192 | mesh: A Rhino mesh that can block the lines.
193 | start_points: An array of Rhino points that will be used to generate lines.
194 | end_points: An array of Rhino points that will be used to generate lines.
195 | max_dist: An optional number to set the maximum distance beyond which the
196 | end_points are no longer considered visible by the start_points.
197 | If None, points with an unobstructed view to one another will be
198 | considered visible no matter how far they are from one another.
199 | cpu_count: An integer for the number of CPUs to be used in the intersection
200 | calculation. The ladybug_rhino.grasshopper.recommended_processor_count
201 | function can be used to get a recommendation. If set to None, all
202 | available processors will be used. (Default: None).
203 | parallel: Optional boolean to override the cpu_count and use a single CPU
204 | instead of multiple processors.
205 |
206 | Returns:
207 | A 2D matrix of 0's and 1's indicating the results of the intersection.
208 | Each sub-list of the matrix represents one of the points and has a
209 | length equal to the end_points. 0 indicates a blocked ray and 1 indicates
210 | a ray that was not blocked.
211 | """
212 | int_matrix = [0] * len(start_points) # matrix to be filled with results
213 | if not parallel:
214 | cpu_count = 1
215 |
216 | def intersect_line(i):
217 | """Intersect a line defined by a start and an end with the mesh."""
218 | pt = start_points[i]
219 | int_list = []
220 | for ept in end_points:
221 | lin = rg.Line(pt, ept)
222 | int_obj = rg.Intersect.Intersection.MeshLine(mesh, lin)
223 | is_clear = 1 if None in int_obj or len(int_obj) == 0 else 0
224 | int_list.append(is_clear)
225 | int_matrix[i] = int_list
226 |
227 | def intersect_line_dist_check(i):
228 | """Intersect a line with the mesh with a distance check."""
229 | pt = start_points[i]
230 | int_list = []
231 | for ept in end_points:
232 | lin = rg.Line(pt, ept)
233 | if lin.Length > max_dist:
234 | int_list.append(0)
235 | else:
236 | int_obj = rg.Intersect.Intersection.MeshLine(mesh, lin)
237 | is_clear = 1 if None in int_obj or len(int_obj) == 0 else 0
238 | int_list.append(is_clear)
239 | int_matrix[i] = int_list
240 |
241 | def intersect_each_line_group(worker_i):
242 | """Intersect groups of lines so that only the cpu_count is used."""
243 | start_i, stop_i = l_groups[worker_i]
244 | for count in range(start_i, stop_i):
245 | intersect_line(count)
246 |
247 | def intersect_each_line_group_dist_check(worker_i):
248 | """Intersect groups of lines with distance check so only cpu_count is used."""
249 | start_i, stop_i = l_groups[worker_i]
250 | for count in range(start_i, stop_i):
251 | intersect_line_dist_check(count)
252 |
253 | if cpu_count is not None and cpu_count > 1:
254 | # group the lines in order to meet the cpu_count
255 | l_count = len(start_points)
256 | worker_count = min((cpu_count, l_count))
257 | i_per_group = int(math.ceil(l_count / worker_count))
258 | l_groups = [[x, x + i_per_group] for x in range(0, l_count, i_per_group)]
259 | l_groups[-1][-1] = l_count # ensure the last group ends with line count
260 |
261 | if max_dist is not None:
262 | if cpu_count is None: # use all availabe CPUs
263 | tasks.Parallel.ForEach(range(len(start_points)), intersect_line_dist_check)
264 | elif cpu_count <= 1: # run everything on a single processor
265 | for i in range(len(start_points)):
266 | intersect_line_dist_check(i)
267 | else: # run the groups in a manner that meets the CPU count
268 | tasks.Parallel.ForEach(
269 | range(len(l_groups)), intersect_each_line_group_dist_check)
270 | else:
271 | if cpu_count is None: # use all availabe CPUs
272 | tasks.Parallel.ForEach(range(len(start_points)), intersect_line)
273 | elif cpu_count <= 1: # run everything on a single processor
274 | for i in range(len(start_points)):
275 | intersect_line(i)
276 | else: # run the groups in a manner that meets the CPU count
277 | tasks.Parallel.ForEach(
278 | range(len(l_groups)), intersect_each_line_group)
279 | return int_matrix
280 |
281 |
282 | def intersect_solids_parallel(solids, bound_boxes, cpu_count=None):
283 | """Intersect the co-planar faces of an array of solids using parallel processing.
284 |
285 | Args:
286 | original_solids: An array of closed Rhino breps (polysurfaces) that do
287 | not have perfectly matching surfaces between adjacent Faces.
288 | bound_boxes: An array of Rhino bounding boxes that parellels the input
289 | solids and will be used to check whether two Breps have any potential
290 | for intersection before the actual intersection is performed.
291 | cpu_count: An integer for the number of CPUs to be used in the intersection
292 | calculation. The ladybug_rhino.grasshopper.recommended_processor_count
293 | function can be used to get a recommendation. If None, all available
294 | processors will be used. (Default: None).
295 | parallel: Optional boolean to override the cpu_count and use a single CPU
296 | instead of multiple processors.
297 |
298 | Returns:
299 | int_solids -- The input array of solids, which have all been intersected
300 | with one another.
301 | """
302 | int_solids = solids[:] # copy the input list to avoid editing it
303 |
304 | def intersect_each_solid(i):
305 | """Intersect a solid with all of the other solids of the list."""
306 | bb_1 = bound_boxes[i]
307 | # intersect the solids that come after this one
308 | for j, bb_2 in enumerate(bound_boxes[i + 1:]):
309 | if not overlapping_bounding_boxes(bb_1, bb_2):
310 | continue # no overlap in bounding box; intersection impossible
311 | split_brep1, int_exists = \
312 | intersect_solid(int_solids[i], int_solids[i + j + 1])
313 | if int_exists:
314 | int_solids[i] = split_brep1
315 | # intersect the solids that come before this one
316 | for j, bb_2 in enumerate(bound_boxes[:i]):
317 | if not overlapping_bounding_boxes(bb_1, bb_2):
318 | continue # no overlap in bounding box; intersection impossible
319 | split_brep2, int_exists = intersect_solid(int_solids[i], int_solids[j])
320 | if int_exists:
321 | int_solids[i] = split_brep2
322 |
323 | def intersect_each_solid_group(worker_i):
324 | """Intersect groups of solids so that only the cpu_count is used."""
325 | start_i, stop_i = s_groups[worker_i]
326 | for count in range(start_i, stop_i):
327 | intersect_each_solid(count)
328 |
329 | if cpu_count is None or cpu_count <= 1: # use all availabe CPUs
330 | tasks.Parallel.ForEach(range(len(solids)), intersect_each_solid)
331 | else: # group the solids in order to meet the cpu_count
332 | solid_count = len(int_solids)
333 | worker_count = min((cpu_count, solid_count))
334 | i_per_group = int(math.ceil(solid_count / worker_count))
335 | s_groups = [[x, x + i_per_group] for x in range(0, solid_count, i_per_group)]
336 | s_groups[-1][-1] = solid_count # ensure the last group ends with solid count
337 | tasks.Parallel.ForEach(range(len(s_groups)), intersect_each_solid_group)
338 |
339 | return int_solids
340 |
341 |
342 | def intersect_solids(solids, bound_boxes):
343 | """Intersect the co-planar faces of an array of solids.
344 |
345 | Args:
346 | original_solids: An array of closed Rhino breps (polysurfaces) that do
347 | not have perfectly matching surfaces between adjacent Faces.
348 | bound_boxes: An array of Rhino bounding boxes that parellels the input
349 | solids and will be used to check whether two Breps have any potential
350 | for intersection before the actual intersection is performed.
351 |
352 | Returns:
353 | int_solids -- The input array of solids, which have all been intersected
354 | with one another.
355 | """
356 | int_solids = solids[:] # copy the input list to avoid editing it
357 |
358 | for i, bb_1 in enumerate(bound_boxes):
359 | for j, bb_2 in enumerate(bound_boxes[i + 1:]):
360 | if not overlapping_bounding_boxes(bb_1, bb_2):
361 | continue # no overlap in bounding box; intersection impossible
362 |
363 | # split the first solid with the second one
364 | split_brep1, int_exists = intersect_solid(
365 | int_solids[i], int_solids[i + j + 1])
366 | int_solids[i] = split_brep1
367 |
368 | # split the second solid with the first one if an intersection was found
369 | if int_exists:
370 | split_brep2, int_exists = intersect_solid(
371 | int_solids[i + j + 1], int_solids[i])
372 | int_solids[i + j + 1] = split_brep2
373 |
374 | return int_solids
375 |
376 |
377 | def intersect_solid(solid, other_solid):
378 | """Intersect the co-planar faces of one solid Brep using another.
379 |
380 | Args:
381 | solid: The solid Brep which will be split with intersections.
382 | other_solid: The other Brep, which will be used to split.
383 |
384 | Returns:
385 | A tuple with two elements
386 |
387 | - solid -- The input solid, which has been split.
388 |
389 | - intersection_exists -- Boolean to note whether an intersection was found
390 | between the solid and the other_solid. If False, there's no need to
391 | split the other_solid with the input solid.
392 | """
393 | # variables to track the splitting process
394 | intersection_exists = False # boolean to note whether an intersection exists
395 | temp_brep = solid.Split(other_solid, tolerance)
396 | if len(temp_brep) != 0:
397 | solid = rg.Brep.JoinBreps(temp_brep, tolerance)[0]
398 | solid.Faces.ShrinkFaces()
399 | intersection_exists = True
400 | return solid, intersection_exists
401 |
402 |
403 | def overlapping_bounding_boxes(bound_box1, bound_box2):
404 | """Check if two Rhino bounding boxes overlap within the tolerance.
405 |
406 | This is particularly useful as a check before performing computationally
407 | intense intersection processes between two bounding boxes. Checking the
408 | overlap of the bounding boxes is extremely quick given this method's use
409 | of the Separating Axis Theorem. This method is built into the intersect_solids
410 | functions in order to improve its calculation time.
411 |
412 | Args:
413 | bound_box1: The first bound_box to check.
414 | bound_box2: The second bound_box to check.
415 | """
416 | # Bounding box check using the Separating Axis Theorem
417 | bb1_width = bound_box1.Max.X - bound_box1.Min.X
418 | bb2_width = bound_box2.Max.X - bound_box2.Min.X
419 | dist_btwn_x = abs(bound_box1.Center.X - bound_box2.Center.X)
420 | x_gap_btwn_box = dist_btwn_x - (0.5 * bb1_width) - (0.5 * bb2_width)
421 |
422 | bb1_depth = bound_box1.Max.Y - bound_box1.Min.Y
423 | bb2_depth = bound_box2.Max.Y - bound_box2.Min.Y
424 | dist_btwn_y = abs(bound_box1.Center.Y - bound_box2.Center.Y)
425 | y_gap_btwn_box = dist_btwn_y - (0.5 * bb1_depth) - (0.5 * bb2_depth)
426 |
427 | bb1_height = bound_box1.Max.Z - bound_box1.Min.Z
428 | bb2_height = bound_box2.Max.Z - bound_box2.Min.Z
429 | dist_btwn_z = abs(bound_box1.Center.Z - bound_box2.Center.Z)
430 | z_gap_btwn_box = dist_btwn_z - (0.5 * bb1_height) - (0.5 * bb2_height)
431 |
432 | if x_gap_btwn_box > tolerance or y_gap_btwn_box > tolerance or \
433 | z_gap_btwn_box > tolerance:
434 | return False # no overlap
435 | return True # overlap exists
436 |
437 |
438 | def split_solid_to_floors(building_solid, floor_heights):
439 | """Extract a series of planar floor surfaces from solid building massing.
440 |
441 | Args:
442 | building_solid: A closed brep representing a building massing.
443 | floor_heights: An array of float values for the floor heights, which
444 | will be used to generate planes that subdivide the building solid.
445 |
446 | Returns:
447 | floor_breps -- A list of planar, horizontal breps representing the floors
448 | of the building.
449 | """
450 | # get the floor brep at each of the floor heights.
451 | floor_breps = []
452 | for hgt in floor_heights:
453 | story_breps = []
454 | floor_base_pt = rg.Point3d(0, 0, hgt)
455 | section_plane = rg.Plane(floor_base_pt, rg.Vector3d.ZAxis)
456 | floor_crvs = rg.Brep.CreateContourCurves(building_solid, section_plane)
457 | try: # Assume a single countour curve has been found
458 | floor_brep = rg.Brep.CreatePlanarBreps(floor_crvs, tolerance)
459 | except TypeError: # An array of contour curves has been found
460 | floor_brep = rg.Brep.CreatePlanarBreps(floor_crvs)
461 | if floor_brep is not None:
462 | story_breps.extend(floor_brep)
463 | floor_breps.append(story_breps)
464 |
465 | return floor_breps
466 |
467 |
468 | def geo_min_max_height(geometry):
469 | """Get the min and max Z values of any input object.
470 |
471 | This is useful as a pre-step before the split_solid_to_floors method.
472 | """
473 | bound_box = geometry.GetBoundingBox(rg.Plane.WorldXY)
474 | return bound_box.Min.Z, bound_box.Max.Z
475 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------