├── MANIFEST.in ├── example.png ├── setup.py ├── streamlit_stl ├── index.html ├── three_js_scripts │ ├── stl-viewer.js │ ├── STLLoader.js │ └── OrbitControls.js └── __init__.py ├── README.md ├── example.py ├── .gitignore └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include streamlit_stl * -------------------------------------------------------------------------------- /example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lucandia/streamlit_stl/HEAD/example.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from pathlib import Path 3 | 4 | this_directory = Path(__file__).parent 5 | long_description = (this_directory / "README.md").read_text() 6 | 7 | setup( 8 | name='streamlit_stl', 9 | version='0.0.6', 10 | author='Luca Monari', 11 | author_email='Luca.Monari@mr.mpg.de', 12 | url="https://github.com/Lucandia/streamlit_stl", 13 | description='A Streamlit component to display 3D models in STL format', 14 | long_description_content_type="text/markdown", 15 | long_description=long_description, 16 | packages=find_packages(), 17 | include_package_data=True, 18 | python_requires=">=3.7", 19 | install_requires=[], 20 | ) -------------------------------------------------------------------------------- /streamlit_stl/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streamlit STL Display Component 2 | 3 | A Streamlit component to display STL files. 4 | 5 | ## Installation 6 | 7 | **This component requires access to write files to the temporary directory.** 8 | 9 | ``` 10 | pip install streamlit_stl 11 | ``` 12 | 13 | ## Example 14 | 15 | ![Alt Text](https://github.com/Lucandia/streamlit_stl/blob/main/example.png?raw=true) 16 | 17 | Look at the [example](https://st-stl.streamlit.app/) for a streamlit Web App: 18 | 19 | [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://st-stl.streamlit.app/) 20 | 21 | The original STL file is from [Printables](https://www.printables.com/it/model/505713-flexifier-flexi-3d-models-generator-print-in-place). 22 | 23 | ## Usage 24 | 25 | ### Display from file paths 26 | 27 | ```python 28 | import streamlit as st 29 | from streamlit_stl import stl_from_file 30 | 31 | success = stl_from_file( 32 | file_path=path_to_conf, # Path to the STL file 33 | color='#FF9900', # Color of the STL file (hexadecimal value) 34 | material='material', # Material of the STL file ('material', 'flat', or 'wireframe') 35 | auto_rotate=True, # Enable auto-rotation of the STL model 36 | opacity=1, # Opacity of the STL model (0 to 1) 37 | shininess=100, # How shiny the specular highlight is, when using the 'material' style. 38 | cam_v_angle=60, # Vertical angle (in degrees) of the camera 39 | cam_h_angle=-90, # Horizontal angle (in degrees) of the camera 40 | cam_distance=None, # Distance of the camera from the object (defaults to 3x bounding box size) 41 | height=500, # Height of the viewer frame 42 | max_view_distance=1000, # Maximum viewing distance for the camera 43 | key=None # Streamlit component key 44 | ) 45 | ``` 46 | 47 | ### Display from file text 48 | 49 | ```python 50 | import streamlit as st 51 | from streamlit_stl import stl_from_text 52 | 53 | file_input = st.file_uploader("Or upload an STL file", type=["stl"]) 54 | 55 | if file_input is not None: 56 | success = stl_from_text( 57 | text=file_input.getvalue(), # Content of the STL file as text 58 | color='#FF9900', # Color of the STL file (hexadecimal value) 59 | material='material', # Material of the STL file ('material', 'flat', or 'wireframe') 60 | auto_rotate=True, # Enable auto-rotation of the STL model 61 | opacity=1, # Opacity of the STL model (0 to 1) 62 | shininess=100, # How shiny the specular highlight is, when using the 'material' style. 63 | cam_v_angle=60, # Vertical angle (in degrees) of the camera 64 | cam_h_angle=-90, # Horizontal angle (in degrees) of the camera 65 | cam_distance=None, # Distance of the camera from the object (defaults to 3x bounding box size) 66 | height=500, # Height of the viewer frame 67 | max_view_distance=1000, # Maximum viewing distance for the camera 68 | key=None # Streamlit component key 69 | ) 70 | ``` 71 | 72 | The functions return a boolean value indicating if the program was able to write and read the files. 73 | 74 | The 'material' style is the default style, it uses the [Phong shading](https://threejs.org/docs/api/en/materials/MeshPhongMaterial.html) model from Three.js. 75 | 76 | ## License 77 | 78 | Code is licensed under the GNU General Public License v3.0 ([GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.en.html)) 79 | 80 | [![License: GPL-3.0](https://img.shields.io/badge/License-GPL%20v3-lightgrey.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html) 81 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from streamlit_stl import stl_from_file, stl_from_text 3 | 4 | if __name__ == "__main__": 5 | st.set_page_config(layout="wide") 6 | 7 | st.title("Streamlit STL Examples") 8 | 9 | st.subheader("Look: a flexi squirrel!") 10 | cols = st.columns(5) 11 | with cols[0]: 12 | color = st.color_picker("Pick a color", "#FF9900", key='color_file') 13 | with cols[1]: 14 | material = st.selectbox("Select a material", ["material", "flat", "wireframe"], key='material_file') 15 | with cols[2]: 16 | st.write('\n'); st.write('\n') 17 | auto_rotate = st.toggle("Auto rotation", key='auto_rotate_file') 18 | with cols[3]: 19 | opacity = st.slider("Opacity", min_value=0.0, max_value=1.0, value=1.0, key='opacity_file') 20 | with cols[4]: 21 | height = st.slider("Height", min_value=50, max_value=1000, value=500, key='height_file') 22 | 23 | # camera position 24 | cols = st.columns(4) 25 | with cols[0]: 26 | cam_v_angle = st.number_input("Camera Vertical Angle", value=60, key='cam_v_angle') 27 | with cols[1]: 28 | cam_h_angle = st.number_input("Camera Horizontal Angle", value=-90, key='cam_h_angle') 29 | with cols[2]: 30 | cam_distance = st.number_input("Camera Distance", value=0, key='cam_distance') 31 | with cols[3]: 32 | max_view_distance = st.number_input("Max view distance", min_value=1, value=1000, key='max_view_distance') 33 | 34 | stl_from_file( file_path='squirrel.stl', 35 | color=color, 36 | material=material, 37 | auto_rotate=auto_rotate, 38 | opacity=opacity, 39 | height=height, 40 | shininess=100, 41 | cam_v_angle=cam_v_angle, 42 | cam_h_angle=cam_h_angle, 43 | cam_distance=cam_distance, 44 | max_view_distance=max_view_distance, 45 | key='example1') 46 | 47 | file_input = st.file_uploader("Or upload a STL file ", type=["stl"]) 48 | 49 | cols = st.columns(5) 50 | with cols[0]: 51 | color = st.color_picker("Pick a color", "#0099FF", key='color_text') 52 | with cols[1]: 53 | material = st.selectbox("Select a material", ["material", "flat", "wireframe"], key='material_text') 54 | with cols[2]: 55 | st.write('\n'); st.write('\n') 56 | auto_rotate = st.toggle("Auto rotation", key='auto_rotate_text') 57 | with cols[3]: 58 | opacity = st.slider("Opacity", min_value=0.0, max_value=1.0, value=1.0, key='opacity_text') 59 | with cols[4]: 60 | height = st.slider("Height", min_value=50, max_value=1000, value=500, key='height_text') 61 | 62 | cols = st.columns(4) 63 | with cols[0]: 64 | cam_v_angle = st.number_input("Camera Vertical Angle", value=60, key='cam_v_angle_text') 65 | with cols[1]: 66 | cam_h_angle = st.number_input("Camera Horizontal Angle", value=0, key='cam_h_angle_text') 67 | with cols[2]: 68 | cam_distance = st.number_input("Camera Distance", value=0, key='cam_distance_text') 69 | with cols[3]: 70 | max_view_distance = st.number_input("Max view distance", min_value=1, value=1000, key='max_view_distance_text') 71 | 72 | 73 | if file_input: 74 | stl_from_text( text=file_input.getvalue(), 75 | color=color, 76 | material=material, 77 | auto_rotate=auto_rotate, 78 | opacity=opacity, 79 | height=height, 80 | cam_v_angle=cam_v_angle, 81 | cam_h_angle=cam_h_angle, 82 | cam_distance=cam_distance, 83 | max_view_distance=max_view_distance, 84 | key='example2') 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | # Created by https://www.gitignore.io/api/macos,linux,django,python,pycharm 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | db.sqlite3 12 | media 13 | 14 | ### Linux ### 15 | *~ 16 | 17 | # temporary files which can be created if a process still has a handle open of a deleted file 18 | .fuse_hidden* 19 | 20 | # KDE directory preferences 21 | .directory 22 | 23 | # Linux trash folder which might appear on any partition or disk 24 | .Trash-* 25 | 26 | # .nfs files are created when an open file is removed but is still being accessed 27 | .nfs* 28 | 29 | ### macOS ### 30 | *.DS_Store 31 | .AppleDouble 32 | .LSOverride 33 | 34 | # Icon must end with two \r 35 | Icon 36 | 37 | # Thumbnails 38 | ._* 39 | 40 | # Files that might appear in the root of a volume 41 | .DocumentRevisions-V100 42 | .fseventsd 43 | .Spotlight-V100 44 | .TemporaryItems 45 | .Trashes 46 | .VolumeIcon.icns 47 | .com.apple.timemachine.donotpresent 48 | 49 | # Directories potentially created on remote AFP share 50 | .AppleDB 51 | .AppleDesktop 52 | Network Trash Folder 53 | Temporary Items 54 | .apdisk 55 | 56 | ### PyCharm ### 57 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 58 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 59 | 60 | # User-specific stuff: 61 | .idea/**/workspace.xml 62 | .idea/**/tasks.xml 63 | .idea/dictionaries 64 | 65 | # Sensitive or high-churn files: 66 | .idea/**/dataSources/ 67 | .idea/**/dataSources.ids 68 | .idea/**/dataSources.xml 69 | .idea/**/dataSources.local.xml 70 | .idea/**/sqlDataSources.xml 71 | .idea/**/dynamic.xml 72 | .idea/**/uiDesigner.xml 73 | 74 | # Gradle: 75 | .idea/**/gradle.xml 76 | .idea/**/libraries 77 | 78 | # CMake 79 | cmake-build-debug/ 80 | 81 | # Mongo Explorer plugin: 82 | .idea/**/mongoSettings.xml 83 | 84 | ## File-based project format: 85 | *.iws 86 | 87 | ## Plugin-specific files: 88 | 89 | # IntelliJ 90 | /out/ 91 | 92 | # mpeltonen/sbt-idea plugin 93 | .idea_modules/ 94 | 95 | # JIRA plugin 96 | atlassian-ide-plugin.xml 97 | 98 | # Cursive Clojure plugin 99 | .idea/replstate.xml 100 | 101 | # Crashlytics plugin (for Android Studio and IntelliJ) 102 | com_crashlytics_export_strings.xml 103 | crashlytics.properties 104 | crashlytics-build.properties 105 | fabric.properties 106 | 107 | ### PyCharm Patch ### 108 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 109 | 110 | # *.iml 111 | # modules.xml 112 | # .idea/misc.xml 113 | # *.ipr 114 | 115 | # Sonarlint plugin 116 | .idea/sonarlint 117 | 118 | ### Python ### 119 | # Byte-compiled / optimized / DLL files 120 | *.py[cod] 121 | *$py.class 122 | 123 | # C extensions 124 | *.so 125 | 126 | # Distribution / packaging 127 | .Python 128 | env/ 129 | build/ 130 | develop-eggs/ 131 | dist/ 132 | downloads/ 133 | eggs/ 134 | .eggs/ 135 | lib/ 136 | lib64/ 137 | parts/ 138 | sdist/ 139 | var/ 140 | wheels/ 141 | *.egg-info/ 142 | .installed.cfg 143 | *.egg 144 | 145 | # PyInstaller 146 | # Usually these files are written by a python script from a template 147 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 148 | *.manifest 149 | 150 | # Installer logs 151 | pip-log.txt 152 | pip-delete-this-directory.txt 153 | 154 | # Unit test / coverage reports 155 | htmlcov/ 156 | .tox/ 157 | .coverage 158 | .coverage.* 159 | .cache 160 | nosetests.xml 161 | coverage.xml 162 | *,cover 163 | .hypothesis/ 164 | 165 | # Translations 166 | *.mo 167 | 168 | # Django stuff: 169 | 170 | # Flask stuff: 171 | instance/ 172 | .webassets-cache 173 | 174 | # Scrapy stuff: 175 | .scrapy 176 | 177 | # Sphinx documentation 178 | docs/_build/ 179 | 180 | # PyBuilder 181 | target/ 182 | 183 | # Jupyter Notebook 184 | .ipynb_checkpoints 185 | 186 | # pyenv 187 | .python-version 188 | 189 | # celery beat schedule file 190 | celerybeat-schedule 191 | 192 | # SageMath parsed files 193 | *.sage.py 194 | 195 | # dotenv 196 | .env 197 | 198 | # virtualenv 199 | .venv 200 | venv/ 201 | ENV/ 202 | 203 | # Spyder project settings 204 | .spyderproject 205 | .spyproject 206 | 207 | # Rope project settings 208 | .ropeproject 209 | 210 | # mkdocs documentation 211 | /site 212 | 213 | # End of https://www.gitignore.io/api/macos,linux,django,python,pycharm -------------------------------------------------------------------------------- /streamlit_stl/three_js_scripts/stl-viewer.js: -------------------------------------------------------------------------------- 1 | class STLViewer extends HTMLElement { 2 | constructor() { 3 | super(); 4 | } 5 | 6 | connectedCallback() { 7 | this.connected = true; 8 | 9 | const shadowRoot = this.attachShadow({ mode: 'open' }); 10 | const container = document.createElement('div'); 11 | container.style.width = '100%'; 12 | container.style.height = '100%'; 13 | 14 | shadowRoot.appendChild(container); 15 | 16 | if (!this.hasAttribute('model')) { 17 | throw new Error('model attribute is required'); 18 | } 19 | 20 | const model = this.getAttribute('model'); 21 | const color = parseInt(this.getAttribute('color').replace("#","0x"), 16); 22 | const auto_rotate = this.getAttribute('auto_rotate'); 23 | const opacity = this.getAttribute('opacity'); 24 | const shininess = Number(this.getAttribute('shininess')); 25 | let materialType = this.getAttribute('materialType'); 26 | const cam_v_angle = Number(this.getAttribute('cam_v_angle')); 27 | const cam_h_angle = Number(this.getAttribute('cam_h_angle')); 28 | let cam_distance = Number(this.getAttribute('cam_distance')); 29 | const max_view_distance = Number(this.getAttribute('max_view_distance')); 30 | 31 | 32 | let camera = new THREE.PerspectiveCamera(50, container.clientWidth / container.clientHeight, 1, max_view_distance); 33 | let renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); 34 | renderer.setSize(container.clientWidth, container.clientHeight); 35 | container.appendChild(renderer.domElement); 36 | 37 | window.addEventListener('resize', function () { 38 | renderer.setSize(container.clientWidth, container.clientHeight); 39 | camera.aspect = container.clientWidth / container.clientHeight; 40 | camera.updateProjectionMatrix(); 41 | }, false); 42 | let controls = new THREE.OrbitControls(camera, renderer.domElement); 43 | controls.enableZoom = true; 44 | let scene = new THREE.Scene(); 45 | let hem_light = new THREE.HemisphereLight(0xffffff, 0x222222, 1.5); 46 | hem_light.position.set(0, 0, 1); 47 | scene.add(hem_light); 48 | 49 | 50 | let dirLight = new THREE.DirectionalLight(0xffffff,1.5); 51 | dirLight.position.set(-1, 1, 0); 52 | scene.add(dirLight); 53 | 54 | 55 | new THREE.STLLoader().load(model, (geometry) => { 56 | let material = new THREE.MeshPhongMaterial({ 57 | color: color, 58 | shininess: shininess, 59 | opacity: opacity, 60 | transparent: true, 61 | }); 62 | 63 | let flat = new THREE.MeshBasicMaterial({ 64 | color: color, 65 | opacity: opacity, 66 | transparent: true, 67 | }); 68 | 69 | let wireframe = new THREE.MeshBasicMaterial({ 70 | color: color, 71 | wireframe: true, 72 | wireframeLinewidth: 40 73 | }); 74 | 75 | if (materialType == 'material') { 76 | materialType = material; 77 | } else if (materialType == 'flat') { 78 | materialType = flat; 79 | } 80 | else { 81 | materialType = wireframe; 82 | } 83 | 84 | let mesh = new THREE.Mesh(geometry, materialType); 85 | //mesh = THREE.SceneUtils.createMultiMaterialObject(geometry, [material, lines]); 86 | 87 | // avoid singularities in the rotation matrix with vertical angles of 0 and 180 degrees 88 | if (cam_v_angle % 180 == 0) { 89 | mesh.rotation.z = cam_h_angle * (Math.PI / 180); 90 | } 91 | scene.add(mesh); 92 | 93 | let middle = new THREE.Vector3(); 94 | geometry.computeBoundingBox(); 95 | geometry.boundingBox.getCenter(middle); 96 | mesh.geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(-middle.x, -middle.y, -middle.z)); 97 | let largestDimension = Math.max(geometry.boundingBox.max.x, geometry.boundingBox.max.y, geometry.boundingBox.max.z) 98 | if (cam_distance == 0) { 99 | cam_distance = largestDimension * 3; 100 | } 101 | 102 | // Convert degrees to radians 103 | const phi = cam_v_angle * (Math.PI / 180); 104 | const theta = cam_h_angle * (Math.PI / 180); 105 | camera.position.x = cam_distance * Math.sin(phi) * Math.cos(theta); 106 | camera.position.y = cam_distance * Math.sin(phi) * Math.sin(theta); 107 | camera.position.z = cam_distance * Math.cos(phi); 108 | camera.up.set( 0, 0, 1 ); 109 | camera.lookAt(new THREE.Vector3(0,0,0)); 110 | 111 | if (auto_rotate == 'true') { 112 | controls.autoRotate = true; 113 | controls.autoRotateSpeed = .5; 114 | } 115 | let animate = () => { 116 | controls.update(); 117 | renderer.render(scene, camera); 118 | if (this.connected) { 119 | requestAnimationFrame(animate); 120 | } 121 | }; 122 | animate(); 123 | }); 124 | } 125 | 126 | disconnectedCallback() { 127 | this.connected = false; 128 | } 129 | } 130 | 131 | customElements.define('stl-viewer', STLViewer); -------------------------------------------------------------------------------- /streamlit_stl/three_js_scripts/STLLoader.js: -------------------------------------------------------------------------------- 1 | ( function () { 2 | 3 | /** 4 | * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs. 5 | * 6 | * Supports both binary and ASCII encoded files, with automatic detection of type. 7 | * 8 | * The loader returns a non-indexed buffer geometry. 9 | * 10 | * Limitations: 11 | * Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL). 12 | * There is perhaps some question as to how valid it is to always assume little-endian-ness. 13 | * ASCII decoding assumes file is UTF-8. 14 | * 15 | * Usage: 16 | * const loader = new STLLoader(); 17 | * loader.load( './models/stl/slotted_disk.stl', function ( geometry ) { 18 | * scene.add( new THREE.Mesh( geometry ) ); 19 | * }); 20 | * 21 | * For binary STLs geometry might contain colors for vertices. To use it: 22 | * // use the same code to load STL as above 23 | * if (geometry.hasColors) { 24 | * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: true }); 25 | * } else { .... } 26 | * const mesh = new THREE.Mesh( geometry, material ); 27 | * 28 | * For ASCII STLs containing multiple solids, each solid is assigned to a different group. 29 | * Groups can be used to assign a different color by defining an array of materials with the same length of 30 | * geometry.groups and passing it to the Mesh constructor: 31 | * 32 | * const mesh = new THREE.Mesh( geometry, material ); 33 | * 34 | * For example: 35 | * 36 | * const materials = []; 37 | * const nGeometryGroups = geometry.groups.length; 38 | * 39 | * const colorMap = ...; // Some logic to index colors. 40 | * 41 | * for (let i = 0; i < nGeometryGroups; i++) { 42 | * 43 | * const material = new THREE.MeshPhongMaterial({ 44 | * color: colorMap[i], 45 | * wireframe: false 46 | * }); 47 | * 48 | * } 49 | * 50 | * materials.push(material); 51 | * const mesh = new THREE.Mesh(geometry, materials); 52 | */ 53 | 54 | class STLLoader extends THREE.Loader { 55 | 56 | constructor( manager ) { 57 | 58 | super( manager ); 59 | 60 | } 61 | 62 | load( url, onLoad, onProgress, onError ) { 63 | 64 | const scope = this; 65 | const loader = new THREE.FileLoader( this.manager ); 66 | loader.setPath( this.path ); 67 | loader.setResponseType( 'arraybuffer' ); 68 | loader.setRequestHeader( this.requestHeader ); 69 | loader.setWithCredentials( this.withCredentials ); 70 | loader.load( url, function ( text ) { 71 | 72 | try { 73 | 74 | onLoad( scope.parse( text ) ); 75 | 76 | } catch ( e ) { 77 | 78 | if ( onError ) { 79 | 80 | onError( e ); 81 | 82 | } else { 83 | 84 | console.error( e ); 85 | 86 | } 87 | 88 | scope.manager.itemError( url ); 89 | 90 | } 91 | 92 | }, onProgress, onError ); 93 | 94 | } 95 | 96 | parse( data ) { 97 | 98 | function isBinary( data ) { 99 | 100 | const reader = new DataView( data ); 101 | const face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; 102 | const n_faces = reader.getUint32( 80, true ); 103 | const expect = 80 + 32 / 8 + n_faces * face_size; 104 | 105 | if ( expect === reader.byteLength ) { 106 | 107 | return true; 108 | 109 | } // An ASCII STL data must begin with 'solid ' as the first six bytes. 110 | // However, ASCII STLs lacking the SPACE after the 'd' are known to be 111 | // plentiful. So, check the first 5 bytes for 'solid'. 112 | // Several encodings, such as UTF-8, precede the text with up to 5 bytes: 113 | // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding 114 | // Search for "solid" to start anywhere after those prefixes. 115 | // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd' 116 | 117 | 118 | const solid = [ 115, 111, 108, 105, 100 ]; 119 | 120 | for ( let off = 0; off < 5; off ++ ) { 121 | 122 | // If "solid" text is matched to the current offset, declare it to be an ASCII STL. 123 | if ( matchDataViewAt( solid, reader, off ) ) return false; 124 | 125 | } // Couldn't find "solid" text at the beginning; it is binary STL. 126 | 127 | 128 | return true; 129 | 130 | } 131 | 132 | function matchDataViewAt( query, reader, offset ) { 133 | 134 | // Check if each byte in query matches the corresponding byte from the current offset 135 | for ( let i = 0, il = query.length; i < il; i ++ ) { 136 | 137 | if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false; 138 | 139 | } 140 | 141 | return true; 142 | 143 | } 144 | 145 | function parseBinary( data ) { 146 | 147 | const reader = new DataView( data ); 148 | const faces = reader.getUint32( 80, true ); 149 | let r, 150 | g, 151 | b, 152 | hasColors = false, 153 | colors; 154 | let defaultR, defaultG, defaultB, alpha; // process STL header 155 | // check for default color in header ("COLOR=rgba" sequence). 156 | 157 | for ( let index = 0; index < 80 - 10; index ++ ) { 158 | 159 | if ( reader.getUint32( index, false ) == 0x434F4C4F 160 | /*COLO*/ 161 | && reader.getUint8( index + 4 ) == 0x52 162 | /*'R'*/ 163 | && reader.getUint8( index + 5 ) == 0x3D 164 | /*'='*/ 165 | ) { 166 | 167 | hasColors = true; 168 | colors = new Float32Array( faces * 3 * 3 ); 169 | defaultR = reader.getUint8( index + 6 ) / 255; 170 | defaultG = reader.getUint8( index + 7 ) / 255; 171 | defaultB = reader.getUint8( index + 8 ) / 255; 172 | alpha = reader.getUint8( index + 9 ) / 255; 173 | 174 | } 175 | 176 | } 177 | 178 | const dataOffset = 84; 179 | const faceLength = 12 * 4 + 2; 180 | const geometry = new THREE.BufferGeometry(); 181 | const vertices = new Float32Array( faces * 3 * 3 ); 182 | const normals = new Float32Array( faces * 3 * 3 ); 183 | 184 | for ( let face = 0; face < faces; face ++ ) { 185 | 186 | const start = dataOffset + face * faceLength; 187 | const normalX = reader.getFloat32( start, true ); 188 | const normalY = reader.getFloat32( start + 4, true ); 189 | const normalZ = reader.getFloat32( start + 8, true ); 190 | 191 | if ( hasColors ) { 192 | 193 | const packedColor = reader.getUint16( start + 48, true ); 194 | 195 | if ( ( packedColor & 0x8000 ) === 0 ) { 196 | 197 | // facet has its own unique color 198 | r = ( packedColor & 0x1F ) / 31; 199 | g = ( packedColor >> 5 & 0x1F ) / 31; 200 | b = ( packedColor >> 10 & 0x1F ) / 31; 201 | 202 | } else { 203 | 204 | r = defaultR; 205 | g = defaultG; 206 | b = defaultB; 207 | 208 | } 209 | 210 | } 211 | 212 | for ( let i = 1; i <= 3; i ++ ) { 213 | 214 | const vertexstart = start + i * 12; 215 | const componentIdx = face * 3 * 3 + ( i - 1 ) * 3; 216 | vertices[ componentIdx ] = reader.getFloat32( vertexstart, true ); 217 | vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true ); 218 | vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true ); 219 | normals[ componentIdx ] = normalX; 220 | normals[ componentIdx + 1 ] = normalY; 221 | normals[ componentIdx + 2 ] = normalZ; 222 | 223 | if ( hasColors ) { 224 | 225 | colors[ componentIdx ] = r; 226 | colors[ componentIdx + 1 ] = g; 227 | colors[ componentIdx + 2 ] = b; 228 | 229 | } 230 | 231 | } 232 | 233 | } 234 | 235 | geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); 236 | geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); 237 | 238 | if ( hasColors ) { 239 | 240 | geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); 241 | geometry.hasColors = true; 242 | geometry.alpha = alpha; 243 | 244 | } 245 | 246 | return geometry; 247 | 248 | } 249 | 250 | function parseASCII( data ) { 251 | 252 | const geometry = new THREE.BufferGeometry(); 253 | const patternSolid = /solid([\s\S]*?)endsolid/g; 254 | const patternFace = /facet([\s\S]*?)endfacet/g; 255 | let faceCounter = 0; 256 | const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; 257 | const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' ); 258 | const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' ); 259 | const vertices = []; 260 | const normals = []; 261 | const normal = new THREE.Vector3(); 262 | let result; 263 | let groupCount = 0; 264 | let startVertex = 0; 265 | let endVertex = 0; 266 | 267 | while ( ( result = patternSolid.exec( data ) ) !== null ) { 268 | 269 | startVertex = endVertex; 270 | const solid = result[ 0 ]; 271 | 272 | while ( ( result = patternFace.exec( solid ) ) !== null ) { 273 | 274 | let vertexCountPerFace = 0; 275 | let normalCountPerFace = 0; 276 | const text = result[ 0 ]; 277 | 278 | while ( ( result = patternNormal.exec( text ) ) !== null ) { 279 | 280 | normal.x = parseFloat( result[ 1 ] ); 281 | normal.y = parseFloat( result[ 2 ] ); 282 | normal.z = parseFloat( result[ 3 ] ); 283 | normalCountPerFace ++; 284 | 285 | } 286 | 287 | while ( ( result = patternVertex.exec( text ) ) !== null ) { 288 | 289 | vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ); 290 | normals.push( normal.x, normal.y, normal.z ); 291 | vertexCountPerFace ++; 292 | endVertex ++; 293 | 294 | } // every face have to own ONE valid normal 295 | 296 | 297 | if ( normalCountPerFace !== 1 ) { 298 | 299 | console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter ); 300 | 301 | } // each face have to own THREE valid vertices 302 | 303 | 304 | if ( vertexCountPerFace !== 3 ) { 305 | 306 | console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter ); 307 | 308 | } 309 | 310 | faceCounter ++; 311 | 312 | } 313 | 314 | const start = startVertex; 315 | const count = endVertex - startVertex; 316 | geometry.addGroup( start, count, groupCount ); 317 | groupCount ++; 318 | 319 | } 320 | 321 | geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) ); 322 | geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) ); 323 | return geometry; 324 | 325 | } 326 | 327 | function ensureString( buffer ) { 328 | 329 | if ( typeof buffer !== 'string' ) { 330 | 331 | return THREE.LoaderUtils.decodeText( new Uint8Array( buffer ) ); 332 | 333 | } 334 | 335 | return buffer; 336 | 337 | } 338 | 339 | function ensureBinary( buffer ) { 340 | 341 | if ( typeof buffer === 'string' ) { 342 | 343 | const array_buffer = new Uint8Array( buffer.length ); 344 | 345 | for ( let i = 0; i < buffer.length; i ++ ) { 346 | 347 | array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian 348 | 349 | } 350 | 351 | return array_buffer.buffer || array_buffer; 352 | 353 | } else { 354 | 355 | return buffer; 356 | 357 | } 358 | 359 | } // start 360 | 361 | 362 | const binData = ensureBinary( data ); 363 | return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) ); 364 | 365 | } 366 | 367 | } 368 | 369 | THREE.STLLoader = STLLoader; 370 | 371 | } )(); 372 | -------------------------------------------------------------------------------- /streamlit_stl/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | import atexit 4 | import tempfile 5 | from typing import Literal 6 | import streamlit.components.v1 as components 7 | 8 | 9 | parent_dir = os.path.dirname(os.path.abspath(__file__)) 10 | 11 | class STLComponent: 12 | def __init__(self): 13 | """Initialize the STLComponent class and set up the environment.""" 14 | self.has_setup = False 15 | self.temp_folder = None 16 | self.current_temp_files = [] # List to track created temporary files 17 | self.setup() # Automatically call setup upon initialization 18 | 19 | def setup(self): 20 | """Set up the necessary directories for the Streamlit_stl component.""" 21 | if not self.has_setup: 22 | 23 | ### Create a unique temporary directory for the component 24 | if self.temp_folder and os.path.exists(self.temp_folder): 25 | shutil.rmtree(self.temp_folder) 26 | self.temp_folder = tempfile.mkdtemp(suffix='_st_stl') 27 | 28 | ### Copy the current component directory to the temporary folder 29 | for file in os.listdir(parent_dir): 30 | src = parent_dir + os.sep + file 31 | dst = self.temp_folder + os.sep + file 32 | if os.path.isdir(src): 33 | shutil.copytree(src, dst) 34 | else: 35 | shutil.copy(src, dst) 36 | 37 | ### Mark setup as complete to prevent re-initialization 38 | self.has_setup = True 39 | 40 | def stl_from_text(self, 41 | text: str, 42 | color: str = '#696969', 43 | material: Literal['material', 'flat', 'wireframe'] = 'material', 44 | auto_rotate: bool = False, 45 | opacity: int = 1, 46 | shininess: int = 100, 47 | cam_v_angle: int = 60, 48 | cam_h_angle: int = -90, 49 | cam_distance: int = 0, 50 | height: int = 500, 51 | max_view_distance: int =1000, 52 | **kwargs): 53 | """ 54 | Create a 3D STL viewer component in Streamlit using a text-based STL file. 55 | 56 | Parameters: 57 | ---------- 58 | text : str 59 | The text content of the STL file to render. 60 | color : str, optional 61 | The hexadecimal color (starting with '#') for the 3D object. Default is '#696969'. 62 | material : Literal['material', 'flat', 'wireframe'], optional 63 | The material style of the 3D object. Options are: 64 | - 'material': Basic physical material. 65 | - 'flat': Flat shading. 66 | - 'wireframe': Wireframe view. 67 | Default is 'material'. 68 | auto_rotate : bool, optional 69 | Whether to enable auto-rotation of the 3D object. Default is False. 70 | opacity : int, optional 71 | Opacity of the 3D object, ranging from 0 (fully transparent) to 1 (fully opaque). Default is 1. 72 | shininess : int, optional 73 | How shiny the specular highlight is, when using the 'material' material style. Default is 100. 74 | cam_v_angle : int, optional 75 | Vertical angle (in degrees) for the camera view. Default is 60. 76 | cam_h_angle : int, optional 77 | Horizontal angle (in degrees) for the camera view. Default is -90. 78 | cam_distance : int, optional 79 | Distance of the camera from the object. If zero, defaults to three times the largest bounding box size. Default is zero. 80 | height : int, optional 81 | Height of the 3D viewer component in pixels. Default is 500. 82 | max_view_distance : int, optional 83 | Maximum viewing distance for the camera. Default is 1000. 84 | **kwargs : 85 | Additional arguments passed to the Streamlit component. 86 | 87 | Returns: 88 | ------- 89 | bool 90 | True if the component is successfully created, False otherwise. 91 | """ 92 | self.setup() # Ensure the environment is set up 93 | file_path = [] # The path of the created temporary file 94 | if material not in ('material', 'flat', 'wireframe'): 95 | raise ValueError(f'The possible materials are "material", "flat" or "wireframe", got {material} instead') 96 | if color[0] != '#': 97 | raise ValueError(f"The color must be a hexadecimal value starting with '#', got {color} instead") 98 | if text is not None: 99 | 100 | ### Create a temporary file in the temporary stl folder 101 | try: 102 | with tempfile.NamedTemporaryFile(dir=self.temp_folder, suffix='.stl', delete=False) as temp_file: 103 | if isinstance(text, bytes): 104 | temp_file.write(text) 105 | elif isinstance(text, str): 106 | # Write the text content to the file 107 | temp_file.write(text.encode("utf-8")) 108 | else: 109 | raise ValueError(f"Invalid text type for the stl file") 110 | # Ensure all data is written to disk 111 | temp_file.flush() 112 | # Store the relative path 113 | file_path = temp_file.name.split(os.sep)[-1] 114 | # Keep track of the file for cleanup 115 | self.current_temp_files.append(temp_file.name) 116 | 117 | except Exception as e: 118 | print(f"Error processing the stl file: {e}") 119 | _component_func(files_text='', height=height **kwargs) 120 | return False 121 | 122 | ### Call the stl component with the list of file paths and their types 123 | _component_func(file_path=file_path, 124 | color=color, 125 | material=material, 126 | auto_rotate=bool(auto_rotate), 127 | opacity=opacity, 128 | shininess=shininess, 129 | cam_v_angle=cam_v_angle, 130 | cam_h_angle=cam_h_angle, 131 | cam_distance=cam_distance, 132 | height=height, 133 | max_view_distance=max_view_distance, 134 | **kwargs) 135 | return True 136 | 137 | def stl_from_file(self, 138 | file_path: str, 139 | color: str = '#696969', 140 | material: Literal['material', 'flat', 'wireframe'] = 'material', 141 | auto_rotate: bool = False, 142 | opacity: int = 1, 143 | shininess: int = 100, 144 | cam_v_angle: int = 60, 145 | cam_h_angle: int = -90, 146 | cam_distance: int = 0, 147 | height: int = 500, 148 | max_view_distance: int = 1000, 149 | **kwargs): 150 | """ 151 | Render a 3D STL file in Streamlit using a file path. 152 | 153 | Parameters: 154 | ---------- 155 | file_path : str 156 | The path to the STL file to render. 157 | color : str, optional 158 | The hexadecimal color (starting with '#') for the 3D object. Default is '#696969'. 159 | material : Literal['material', 'flat', 'wireframe'], optional 160 | The material style of the 3D object. Options are: 161 | - 'material': Basic physical material. 162 | - 'flat': Flat shading. 163 | - 'wireframe': Wireframe view. 164 | Default is 'material'. 165 | auto_rotate : bool, optional 166 | Whether to enable auto-rotation of the 3D object. Default is False. 167 | opacity : int, optional 168 | Opacity of the 3D object, ranging from 0 (fully transparent) to 1 (fully opaque). Default is 1. 169 | shininess : int, optional 170 | How shiny the specular highlight is, when using the 'material' material style. Default is 100. 171 | cam_v_angle : int, optional 172 | Vertical angle (in degrees) for the camera view. Default is 60. 173 | cam_h_angle : int, optional 174 | Horizontal angle (in degrees) for the camera view. Default is -90. 175 | cam_distance : int, optional 176 | Distance of the camera from the object. If zero, defaults to three times the largest bounding box size. Default is zero. 177 | height : int, optional 178 | Height of the 3D viewer component in pixels. Default is 500. 179 | max_view_distance : int, optional 180 | Maximum viewing distance for the camera. Default is 1000. 181 | **kwargs : 182 | Additional arguments passed to the Streamlit component. 183 | 184 | Returns: 185 | ------- 186 | bool 187 | True if the component is successfully created, False otherwise. 188 | """ 189 | 190 | file_text = None 191 | 192 | ### Read the file content and add it to the list 193 | if file_path is not None: 194 | with open(file_path, "rb") as f: 195 | file_text = f.read() 196 | 197 | ### Pass the file content to stl_from_text 198 | return self.stl_from_text(text=file_text, 199 | color=color, 200 | material=material, 201 | auto_rotate=auto_rotate, 202 | opacity=opacity, 203 | shininess=shininess, 204 | height=height, 205 | cam_v_angle=cam_v_angle, 206 | cam_h_angle=cam_h_angle, 207 | cam_distance=cam_distance, 208 | max_view_distance=max_view_distance, 209 | **kwargs) 210 | 211 | def cleanup_temp_files(self): 212 | """Clean up temporary files and directories created during the session.""" 213 | ### Remove the entire temporary directory 214 | try: 215 | if os.path.exists(self.temp_folder): 216 | shutil.rmtree(self.temp_folder) 217 | 218 | except Exception as e: 219 | print(f"Error deleting temporary streamlit-stl folder {self.temp_folder}: {e}") 220 | # If the directory can't be deleted, try to delete each file individually 221 | for temp_file in self.current_temp_files: 222 | try: # Remove individual temporary files 223 | os.unlink(temp_file) 224 | except Exception as e: 225 | print(f"Error deleting temp file {temp_file}: {e}") 226 | 227 | # Instantiate the STLComponent class to set up the environment and handle resources 228 | stl_component = STLComponent() 229 | # Register the cleanup function to be called automatically when the program exits 230 | atexit.register(stl_component.cleanup_temp_files) 231 | 232 | 233 | ### Declare the functions to be used in the Streamlit script 234 | stl_from_text = stl_component.stl_from_text 235 | stl_from_file = stl_component.stl_from_file 236 | 237 | # Declare the Streamlit component and link it to the temporary directory 238 | _component_func = components.declare_component( 239 | "streamlit_stl", 240 | path=stl_component.temp_folder, 241 | ) -------------------------------------------------------------------------------- /streamlit_stl/three_js_scripts/OrbitControls.js: -------------------------------------------------------------------------------- 1 | ( function () { 2 | 3 | // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). 4 | // 5 | // Orbit - left mouse / touch: one-finger move 6 | // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish 7 | // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move 8 | 9 | const _changeEvent = { 10 | type: 'change' 11 | }; 12 | const _startEvent = { 13 | type: 'start' 14 | }; 15 | const _endEvent = { 16 | type: 'end' 17 | }; 18 | 19 | class OrbitControls extends THREE.EventDispatcher { 20 | 21 | constructor( object, domElement ) { 22 | 23 | super(); 24 | if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); 25 | if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); 26 | this.object = object; 27 | this.domElement = domElement; // Set to false to disable this control 28 | 29 | this.enabled = true; // "target" sets the location of focus, where the object orbits around 30 | 31 | this.target = new THREE.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only ) 32 | 33 | this.minDistance = 0; 34 | this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only ) 35 | 36 | this.minZoom = 0; 37 | this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits. 38 | // Range is 0 to Math.PI radians. 39 | 40 | this.minPolarAngle = 0; // radians 41 | 42 | this.maxPolarAngle = Math.PI; // radians 43 | // How far you can orbit horizontally, upper and lower limits. 44 | // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) 45 | 46 | this.minAzimuthAngle = - Infinity; // radians 47 | 48 | this.maxAzimuthAngle = Infinity; // radians 49 | // Set to true to enable damping (inertia) 50 | // If damping is enabled, you must call controls.update() in your animation loop 51 | 52 | this.enableDamping = false; 53 | this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. 54 | // Set to false to disable zooming 55 | 56 | this.enableZoom = true; 57 | this.zoomSpeed = 1.0; // Set to false to disable rotating 58 | 59 | this.enableRotate = true; 60 | this.rotateSpeed = 1.0; // Set to false to disable panning 61 | 62 | this.enablePan = true; 63 | this.panSpeed = 1.0; 64 | this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up 65 | 66 | this.keyPanSpeed = 7.0; // pixels moved per arrow key push 67 | // Set to true to automatically rotate around the target 68 | // If auto-rotate is enabled, you must call controls.update() in your animation loop 69 | 70 | this.autoRotate = false; 71 | this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 72 | // The four arrow keys 73 | 74 | this.keys = { 75 | LEFT: 'ArrowLeft', 76 | UP: 'ArrowUp', 77 | RIGHT: 'ArrowRight', 78 | BOTTOM: 'ArrowDown' 79 | }; // Mouse buttons 80 | 81 | this.mouseButtons = { 82 | LEFT: THREE.MOUSE.ROTATE, 83 | MIDDLE: THREE.MOUSE.DOLLY, 84 | RIGHT: THREE.MOUSE.PAN 85 | }; // Touch fingers 86 | 87 | this.touches = { 88 | ONE: THREE.TOUCH.ROTATE, 89 | TWO: THREE.TOUCH.DOLLY_PAN 90 | }; // for reset 91 | 92 | this.target0 = this.target.clone(); 93 | this.position0 = this.object.position.clone(); 94 | this.zoom0 = this.object.zoom; // the target DOM element for key events 95 | 96 | this._domElementKeyEvents = null; // 97 | // public methods 98 | // 99 | 100 | this.getPolarAngle = function () { 101 | 102 | return spherical.phi; 103 | 104 | }; 105 | 106 | this.getAzimuthalAngle = function () { 107 | 108 | return spherical.theta; 109 | 110 | }; 111 | 112 | this.listenToKeyEvents = function ( domElement ) { 113 | 114 | domElement.addEventListener( 'keydown', onKeyDown ); 115 | this._domElementKeyEvents = domElement; 116 | 117 | }; 118 | 119 | this.saveState = function () { 120 | 121 | scope.target0.copy( scope.target ); 122 | scope.position0.copy( scope.object.position ); 123 | scope.zoom0 = scope.object.zoom; 124 | 125 | }; 126 | 127 | this.reset = function () { 128 | 129 | scope.target.copy( scope.target0 ); 130 | scope.object.position.copy( scope.position0 ); 131 | scope.object.zoom = scope.zoom0; 132 | scope.object.updateProjectionMatrix(); 133 | scope.dispatchEvent( _changeEvent ); 134 | scope.update(); 135 | state = STATE.NONE; 136 | 137 | }; // this method is exposed, but perhaps it would be better if we can make it private... 138 | 139 | 140 | this.update = function () { 141 | 142 | const offset = new THREE.Vector3(); // so camera.up is the orbit axis 143 | 144 | const quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 0, 1 ) ); 145 | const quatInverse = quat.clone().invert(); 146 | const lastPosition = new THREE.Vector3(); 147 | const lastQuaternion = new THREE.Quaternion(); 148 | const twoPI = 2 * Math.PI; 149 | return function update() { 150 | 151 | const position = scope.object.position; 152 | offset.copy( position ).sub( scope.target ); // rotate offset to "y-axis-is-up" space 153 | 154 | offset.applyQuaternion( quat ); // angle from z-axis around y-axis 155 | 156 | spherical.setFromVector3( offset ); 157 | 158 | if ( scope.autoRotate && state === STATE.NONE ) { 159 | 160 | rotateLeft( getAutoRotationAngle() ); 161 | 162 | } 163 | 164 | if ( scope.enableDamping ) { 165 | 166 | spherical.theta += sphericalDelta.theta * scope.dampingFactor; 167 | spherical.phi += sphericalDelta.phi * scope.dampingFactor; 168 | 169 | } else { 170 | 171 | spherical.theta += sphericalDelta.theta; 172 | spherical.phi += sphericalDelta.phi; 173 | 174 | } // restrict theta to be between desired limits 175 | 176 | 177 | let min = scope.minAzimuthAngle; 178 | let max = scope.maxAzimuthAngle; 179 | 180 | if ( isFinite( min ) && isFinite( max ) ) { 181 | 182 | if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; 183 | if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; 184 | 185 | if ( min <= max ) { 186 | 187 | spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); 188 | 189 | } else { 190 | 191 | spherical.theta = spherical.theta > ( min + max ) / 2 ? Math.max( min, spherical.theta ) : Math.min( max, spherical.theta ); 192 | 193 | } 194 | 195 | } // restrict phi to be between desired limits 196 | 197 | 198 | spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); 199 | spherical.makeSafe(); 200 | spherical.radius *= scale; // restrict radius to be between desired limits 201 | 202 | spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); // move target to panned location 203 | 204 | if ( scope.enableDamping === true ) { 205 | 206 | scope.target.addScaledVector( panOffset, scope.dampingFactor ); 207 | 208 | } else { 209 | 210 | scope.target.add( panOffset ); 211 | 212 | } 213 | 214 | offset.setFromSpherical( spherical ); // rotate offset back to "camera-up-vector-is-up" space 215 | 216 | offset.applyQuaternion( quatInverse ); 217 | position.copy( scope.target ).add( offset ); 218 | scope.object.lookAt( scope.target ); 219 | 220 | if ( scope.enableDamping === true ) { 221 | 222 | sphericalDelta.theta *= 1 - scope.dampingFactor; 223 | sphericalDelta.phi *= 1 - scope.dampingFactor; 224 | panOffset.multiplyScalar( 1 - scope.dampingFactor ); 225 | 226 | } else { 227 | 228 | sphericalDelta.set( 0, 0, 0 ); 229 | panOffset.set( 0, 0, 0 ); 230 | 231 | } 232 | 233 | scale = 1; // update condition is: 234 | // min(camera displacement, camera rotation in radians)^2 > EPS 235 | // using small-angle approximation cos(x/2) = 1 - x^2 / 8 236 | 237 | if ( zoomChanged || lastPosition.distanceToSquared( scope.object.position ) > EPS || 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { 238 | 239 | scope.dispatchEvent( _changeEvent ); 240 | lastPosition.copy( scope.object.position ); 241 | lastQuaternion.copy( scope.object.quaternion ); 242 | zoomChanged = false; 243 | return true; 244 | 245 | } 246 | 247 | return false; 248 | 249 | }; 250 | 251 | }(); 252 | 253 | this.dispose = function () { 254 | 255 | scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); 256 | scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); 257 | scope.domElement.removeEventListener( 'wheel', onMouseWheel ); 258 | scope.domElement.removeEventListener( 'touchstart', onTouchStart ); 259 | scope.domElement.removeEventListener( 'touchend', onTouchEnd ); 260 | scope.domElement.removeEventListener( 'touchmove', onTouchMove ); 261 | scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); 262 | scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); 263 | 264 | if ( scope._domElementKeyEvents !== null ) { 265 | 266 | scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); 267 | 268 | } //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? 269 | 270 | }; // 271 | // internals 272 | // 273 | 274 | 275 | const scope = this; 276 | const STATE = { 277 | NONE: - 1, 278 | ROTATE: 0, 279 | DOLLY: 1, 280 | PAN: 2, 281 | TOUCH_ROTATE: 3, 282 | TOUCH_PAN: 4, 283 | TOUCH_DOLLY_PAN: 5, 284 | TOUCH_DOLLY_ROTATE: 6 285 | }; 286 | let state = STATE.NONE; 287 | const EPS = 0.000001; // current position in spherical coordinates 288 | 289 | const spherical = new THREE.Spherical(); 290 | const sphericalDelta = new THREE.Spherical(); 291 | let scale = 1; 292 | const panOffset = new THREE.Vector3(); 293 | let zoomChanged = false; 294 | const rotateStart = new THREE.Vector2(); 295 | const rotateEnd = new THREE.Vector2(); 296 | const rotateDelta = new THREE.Vector2(); 297 | const panStart = new THREE.Vector2(); 298 | const panEnd = new THREE.Vector2(); 299 | const panDelta = new THREE.Vector2(); 300 | const dollyStart = new THREE.Vector2(); 301 | const dollyEnd = new THREE.Vector2(); 302 | const dollyDelta = new THREE.Vector2(); 303 | 304 | function getAutoRotationAngle() { 305 | 306 | return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; 307 | 308 | } 309 | 310 | function getZoomScale() { 311 | 312 | return Math.pow( 0.95, scope.zoomSpeed ); 313 | 314 | } 315 | 316 | function rotateLeft( angle ) { 317 | 318 | sphericalDelta.theta += angle; 319 | 320 | } 321 | 322 | function rotateUp( angle ) { 323 | 324 | sphericalDelta.phi += angle; 325 | 326 | } 327 | 328 | const panLeft = function () { 329 | 330 | const v = new THREE.Vector3(); 331 | return function panLeft( distance, objectMatrix ) { 332 | 333 | v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix 334 | 335 | v.multiplyScalar( - distance ); 336 | panOffset.add( v ); 337 | 338 | }; 339 | 340 | }(); 341 | 342 | const panUp = function () { 343 | 344 | const v = new THREE.Vector3(); 345 | return function panUp( distance, objectMatrix ) { 346 | 347 | if ( scope.screenSpacePanning === true ) { 348 | 349 | v.setFromMatrixColumn( objectMatrix, 1 ); 350 | 351 | } else { 352 | 353 | v.setFromMatrixColumn( objectMatrix, 0 ); 354 | v.crossVectors( scope.object.up, v ); 355 | 356 | } 357 | 358 | v.multiplyScalar( distance ); 359 | panOffset.add( v ); 360 | 361 | }; 362 | 363 | }(); // deltaX and deltaY are in pixels; right and down are positive 364 | 365 | 366 | const pan = function () { 367 | 368 | const offset = new THREE.Vector3(); 369 | return function pan( deltaX, deltaY ) { 370 | 371 | const element = scope.domElement; 372 | 373 | if ( scope.object.isPerspectiveCamera ) { 374 | 375 | // perspective 376 | const position = scope.object.position; 377 | offset.copy( position ).sub( scope.target ); 378 | let targetDistance = offset.length(); // half of the fov is center to top of screen 379 | 380 | targetDistance *= Math.tan( scope.object.fov / 2 * Math.PI / 180.0 ); // we use only clientHeight here so aspect ratio does not distort speed 381 | 382 | panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); 383 | panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); 384 | 385 | } else if ( scope.object.isOrthographicCamera ) { 386 | 387 | // orthographic 388 | panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); 389 | panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); 390 | 391 | } else { 392 | 393 | // camera neither orthographic nor perspective 394 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); 395 | scope.enablePan = false; 396 | 397 | } 398 | 399 | }; 400 | 401 | }(); 402 | 403 | function dollyOut( dollyScale ) { 404 | 405 | if ( scope.object.isPerspectiveCamera ) { 406 | 407 | scale /= dollyScale; 408 | 409 | } else if ( scope.object.isOrthographicCamera ) { 410 | 411 | scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); 412 | scope.object.updateProjectionMatrix(); 413 | zoomChanged = true; 414 | 415 | } else { 416 | 417 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); 418 | scope.enableZoom = false; 419 | 420 | } 421 | 422 | } 423 | 424 | function dollyIn( dollyScale ) { 425 | 426 | if ( scope.object.isPerspectiveCamera ) { 427 | 428 | scale *= dollyScale; 429 | 430 | } else if ( scope.object.isOrthographicCamera ) { 431 | 432 | scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); 433 | scope.object.updateProjectionMatrix(); 434 | zoomChanged = true; 435 | 436 | } else { 437 | 438 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); 439 | scope.enableZoom = false; 440 | 441 | } 442 | 443 | } // 444 | // event callbacks - update the object state 445 | // 446 | 447 | 448 | function handleMouseDownRotate( event ) { 449 | 450 | rotateStart.set( event.clientX, event.clientY ); 451 | 452 | } 453 | 454 | function handleMouseDownDolly( event ) { 455 | 456 | dollyStart.set( event.clientX, event.clientY ); 457 | 458 | } 459 | 460 | function handleMouseDownPan( event ) { 461 | 462 | panStart.set( event.clientX, event.clientY ); 463 | 464 | } 465 | 466 | function handleMouseMoveRotate( event ) { 467 | 468 | rotateEnd.set( event.clientX, event.clientY ); 469 | rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); 470 | const element = scope.domElement; 471 | rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height 472 | 473 | rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); 474 | rotateStart.copy( rotateEnd ); 475 | scope.update(); 476 | 477 | } 478 | 479 | function handleMouseMoveDolly( event ) { 480 | 481 | dollyEnd.set( event.clientX, event.clientY ); 482 | dollyDelta.subVectors( dollyEnd, dollyStart ); 483 | 484 | if ( dollyDelta.y > 0 ) { 485 | 486 | dollyOut( getZoomScale() ); 487 | 488 | } else if ( dollyDelta.y < 0 ) { 489 | 490 | dollyIn( getZoomScale() ); 491 | 492 | } 493 | 494 | dollyStart.copy( dollyEnd ); 495 | scope.update(); 496 | 497 | } 498 | 499 | function handleMouseMovePan( event ) { 500 | 501 | panEnd.set( event.clientX, event.clientY ); 502 | panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); 503 | pan( panDelta.x, panDelta.y ); 504 | panStart.copy( panEnd ); 505 | scope.update(); 506 | 507 | } 508 | 509 | function handleMouseUp( ) { // no-op 510 | } 511 | 512 | function handleMouseWheel( event ) { 513 | 514 | if ( event.deltaY < 0 ) { 515 | 516 | dollyIn( getZoomScale() ); 517 | 518 | } else if ( event.deltaY > 0 ) { 519 | 520 | dollyOut( getZoomScale() ); 521 | 522 | } 523 | 524 | scope.update(); 525 | 526 | } 527 | 528 | function handleKeyDown( event ) { 529 | 530 | let needsUpdate = false; 531 | 532 | switch ( event.code ) { 533 | 534 | case scope.keys.UP: 535 | pan( 0, scope.keyPanSpeed ); 536 | needsUpdate = true; 537 | break; 538 | 539 | case scope.keys.BOTTOM: 540 | pan( 0, - scope.keyPanSpeed ); 541 | needsUpdate = true; 542 | break; 543 | 544 | case scope.keys.LEFT: 545 | pan( scope.keyPanSpeed, 0 ); 546 | needsUpdate = true; 547 | break; 548 | 549 | case scope.keys.RIGHT: 550 | pan( - scope.keyPanSpeed, 0 ); 551 | needsUpdate = true; 552 | break; 553 | 554 | } 555 | 556 | if ( needsUpdate ) { 557 | 558 | // prevent the browser from scrolling on cursor keys 559 | event.preventDefault(); 560 | scope.update(); 561 | 562 | } 563 | 564 | } 565 | 566 | function handleTouchStartRotate( event ) { 567 | 568 | if ( event.touches.length == 1 ) { 569 | 570 | rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 571 | 572 | } else { 573 | 574 | const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); 575 | const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); 576 | rotateStart.set( x, y ); 577 | 578 | } 579 | 580 | } 581 | 582 | function handleTouchStartPan( event ) { 583 | 584 | if ( event.touches.length == 1 ) { 585 | 586 | panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 587 | 588 | } else { 589 | 590 | const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); 591 | const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); 592 | panStart.set( x, y ); 593 | 594 | } 595 | 596 | } 597 | 598 | function handleTouchStartDolly( event ) { 599 | 600 | const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 601 | const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 602 | const distance = Math.sqrt( dx * dx + dy * dy ); 603 | dollyStart.set( 0, distance ); 604 | 605 | } 606 | 607 | function handleTouchStartDollyPan( event ) { 608 | 609 | if ( scope.enableZoom ) handleTouchStartDolly( event ); 610 | if ( scope.enablePan ) handleTouchStartPan( event ); 611 | 612 | } 613 | 614 | function handleTouchStartDollyRotate( event ) { 615 | 616 | if ( scope.enableZoom ) handleTouchStartDolly( event ); 617 | if ( scope.enableRotate ) handleTouchStartRotate( event ); 618 | 619 | } 620 | 621 | function handleTouchMoveRotate( event ) { 622 | 623 | if ( event.touches.length == 1 ) { 624 | 625 | rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 626 | 627 | } else { 628 | 629 | const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); 630 | const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); 631 | rotateEnd.set( x, y ); 632 | 633 | } 634 | 635 | rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); 636 | const element = scope.domElement; 637 | rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height 638 | 639 | rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); 640 | rotateStart.copy( rotateEnd ); 641 | 642 | } 643 | 644 | function handleTouchMovePan( event ) { 645 | 646 | if ( event.touches.length == 1 ) { 647 | 648 | panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 649 | 650 | } else { 651 | 652 | const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); 653 | const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); 654 | panEnd.set( x, y ); 655 | 656 | } 657 | 658 | panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); 659 | pan( panDelta.x, panDelta.y ); 660 | panStart.copy( panEnd ); 661 | 662 | } 663 | 664 | function handleTouchMoveDolly( event ) { 665 | 666 | const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 667 | const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 668 | const distance = Math.sqrt( dx * dx + dy * dy ); 669 | dollyEnd.set( 0, distance ); 670 | dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); 671 | dollyOut( dollyDelta.y ); 672 | dollyStart.copy( dollyEnd ); 673 | 674 | } 675 | 676 | function handleTouchMoveDollyPan( event ) { 677 | 678 | if ( scope.enableZoom ) handleTouchMoveDolly( event ); 679 | if ( scope.enablePan ) handleTouchMovePan( event ); 680 | 681 | } 682 | 683 | function handleTouchMoveDollyRotate( event ) { 684 | 685 | if ( scope.enableZoom ) handleTouchMoveDolly( event ); 686 | if ( scope.enableRotate ) handleTouchMoveRotate( event ); 687 | 688 | } 689 | 690 | function handleTouchEnd( ) { // no-op 691 | } // 692 | // event handlers - FSM: listen for events and reset state 693 | // 694 | 695 | 696 | function onPointerDown( event ) { 697 | 698 | if ( scope.enabled === false ) return; 699 | 700 | switch ( event.pointerType ) { 701 | 702 | case 'mouse': 703 | case 'pen': 704 | onMouseDown( event ); 705 | break; 706 | // TODO touch 707 | 708 | } 709 | 710 | } 711 | 712 | function onPointerMove( event ) { 713 | 714 | if ( scope.enabled === false ) return; 715 | 716 | switch ( event.pointerType ) { 717 | 718 | case 'mouse': 719 | case 'pen': 720 | onMouseMove( event ); 721 | break; 722 | // TODO touch 723 | 724 | } 725 | 726 | } 727 | 728 | function onPointerUp( event ) { 729 | 730 | switch ( event.pointerType ) { 731 | 732 | case 'mouse': 733 | case 'pen': 734 | onMouseUp( event ); 735 | break; 736 | // TODO touch 737 | 738 | } 739 | 740 | } 741 | 742 | function onMouseDown( event ) { 743 | 744 | // Prevent the browser from scrolling. 745 | event.preventDefault(); // Manually set the focus since calling preventDefault above 746 | // prevents the browser from setting it automatically. 747 | 748 | scope.domElement.focus ? scope.domElement.focus() : window.focus(); 749 | let mouseAction; 750 | 751 | switch ( event.button ) { 752 | 753 | case 0: 754 | mouseAction = scope.mouseButtons.LEFT; 755 | break; 756 | 757 | case 1: 758 | mouseAction = scope.mouseButtons.MIDDLE; 759 | break; 760 | 761 | case 2: 762 | mouseAction = scope.mouseButtons.RIGHT; 763 | break; 764 | 765 | default: 766 | mouseAction = - 1; 767 | 768 | } 769 | 770 | switch ( mouseAction ) { 771 | 772 | case THREE.MOUSE.DOLLY: 773 | if ( scope.enableZoom === false ) return; 774 | handleMouseDownDolly( event ); 775 | state = STATE.DOLLY; 776 | break; 777 | 778 | case THREE.MOUSE.ROTATE: 779 | if ( event.ctrlKey || event.metaKey || event.shiftKey ) { 780 | 781 | if ( scope.enablePan === false ) return; 782 | handleMouseDownPan( event ); 783 | state = STATE.PAN; 784 | 785 | } else { 786 | 787 | if ( scope.enableRotate === false ) return; 788 | handleMouseDownRotate( event ); 789 | state = STATE.ROTATE; 790 | 791 | } 792 | 793 | break; 794 | 795 | case THREE.MOUSE.PAN: 796 | if ( event.ctrlKey || event.metaKey || event.shiftKey ) { 797 | 798 | if ( scope.enableRotate === false ) return; 799 | handleMouseDownRotate( event ); 800 | state = STATE.ROTATE; 801 | 802 | } else { 803 | 804 | if ( scope.enablePan === false ) return; 805 | handleMouseDownPan( event ); 806 | state = STATE.PAN; 807 | 808 | } 809 | 810 | break; 811 | 812 | default: 813 | state = STATE.NONE; 814 | 815 | } 816 | 817 | if ( state !== STATE.NONE ) { 818 | 819 | scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove ); 820 | scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp ); 821 | scope.dispatchEvent( _startEvent ); 822 | 823 | } 824 | 825 | } 826 | 827 | function onMouseMove( event ) { 828 | 829 | if ( scope.enabled === false ) return; 830 | event.preventDefault(); 831 | 832 | switch ( state ) { 833 | 834 | case STATE.ROTATE: 835 | if ( scope.enableRotate === false ) return; 836 | handleMouseMoveRotate( event ); 837 | break; 838 | 839 | case STATE.DOLLY: 840 | if ( scope.enableZoom === false ) return; 841 | handleMouseMoveDolly( event ); 842 | break; 843 | 844 | case STATE.PAN: 845 | if ( scope.enablePan === false ) return; 846 | handleMouseMovePan( event ); 847 | break; 848 | 849 | } 850 | 851 | } 852 | 853 | function onMouseUp( event ) { 854 | 855 | scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); 856 | scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); 857 | if ( scope.enabled === false ) return; 858 | handleMouseUp( event ); 859 | scope.dispatchEvent( _endEvent ); 860 | state = STATE.NONE; 861 | 862 | } 863 | 864 | function onMouseWheel( event ) { 865 | 866 | if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE ) return; 867 | event.preventDefault(); 868 | scope.dispatchEvent( _startEvent ); 869 | handleMouseWheel( event ); 870 | scope.dispatchEvent( _endEvent ); 871 | 872 | } 873 | 874 | function onKeyDown( event ) { 875 | 876 | if ( scope.enabled === false || scope.enablePan === false ) return; 877 | handleKeyDown( event ); 878 | 879 | } 880 | 881 | function onTouchStart( event ) { 882 | 883 | if ( scope.enabled === false ) return; 884 | event.preventDefault(); // prevent scrolling 885 | 886 | switch ( event.touches.length ) { 887 | 888 | case 1: 889 | switch ( scope.touches.ONE ) { 890 | 891 | case THREE.TOUCH.ROTATE: 892 | if ( scope.enableRotate === false ) return; 893 | handleTouchStartRotate( event ); 894 | state = STATE.TOUCH_ROTATE; 895 | break; 896 | 897 | case THREE.TOUCH.PAN: 898 | if ( scope.enablePan === false ) return; 899 | handleTouchStartPan( event ); 900 | state = STATE.TOUCH_PAN; 901 | break; 902 | 903 | default: 904 | state = STATE.NONE; 905 | 906 | } 907 | 908 | break; 909 | 910 | case 2: 911 | switch ( scope.touches.TWO ) { 912 | 913 | case THREE.TOUCH.DOLLY_PAN: 914 | if ( scope.enableZoom === false && scope.enablePan === false ) return; 915 | handleTouchStartDollyPan( event ); 916 | state = STATE.TOUCH_DOLLY_PAN; 917 | break; 918 | 919 | case THREE.TOUCH.DOLLY_ROTATE: 920 | if ( scope.enableZoom === false && scope.enableRotate === false ) return; 921 | handleTouchStartDollyRotate( event ); 922 | state = STATE.TOUCH_DOLLY_ROTATE; 923 | break; 924 | 925 | default: 926 | state = STATE.NONE; 927 | 928 | } 929 | 930 | break; 931 | 932 | default: 933 | state = STATE.NONE; 934 | 935 | } 936 | 937 | if ( state !== STATE.NONE ) { 938 | 939 | scope.dispatchEvent( _startEvent ); 940 | 941 | } 942 | 943 | } 944 | 945 | function onTouchMove( event ) { 946 | 947 | if ( scope.enabled === false ) return; 948 | event.preventDefault(); // prevent scrolling 949 | 950 | switch ( state ) { 951 | 952 | case STATE.TOUCH_ROTATE: 953 | if ( scope.enableRotate === false ) return; 954 | handleTouchMoveRotate( event ); 955 | scope.update(); 956 | break; 957 | 958 | case STATE.TOUCH_PAN: 959 | if ( scope.enablePan === false ) return; 960 | handleTouchMovePan( event ); 961 | scope.update(); 962 | break; 963 | 964 | case STATE.TOUCH_DOLLY_PAN: 965 | if ( scope.enableZoom === false && scope.enablePan === false ) return; 966 | handleTouchMoveDollyPan( event ); 967 | scope.update(); 968 | break; 969 | 970 | case STATE.TOUCH_DOLLY_ROTATE: 971 | if ( scope.enableZoom === false && scope.enableRotate === false ) return; 972 | handleTouchMoveDollyRotate( event ); 973 | scope.update(); 974 | break; 975 | 976 | default: 977 | state = STATE.NONE; 978 | 979 | } 980 | 981 | } 982 | 983 | function onTouchEnd( event ) { 984 | 985 | if ( scope.enabled === false ) return; 986 | handleTouchEnd( event ); 987 | scope.dispatchEvent( _endEvent ); 988 | state = STATE.NONE; 989 | 990 | } 991 | 992 | function onContextMenu( event ) { 993 | 994 | if ( scope.enabled === false ) return; 995 | event.preventDefault(); 996 | 997 | } // 998 | 999 | 1000 | scope.domElement.addEventListener( 'contextmenu', onContextMenu ); 1001 | scope.domElement.addEventListener( 'pointerdown', onPointerDown ); 1002 | scope.domElement.addEventListener( 'wheel', onMouseWheel, { 1003 | passive: false 1004 | } ); 1005 | scope.domElement.addEventListener( 'touchstart', onTouchStart, { 1006 | passive: false 1007 | } ); 1008 | scope.domElement.addEventListener( 'touchend', onTouchEnd ); 1009 | scope.domElement.addEventListener( 'touchmove', onTouchMove, { 1010 | passive: false 1011 | } ); // force an update at start 1012 | 1013 | this.update(); 1014 | 1015 | } 1016 | 1017 | } // This set of controls performs orbiting, dollying (zooming), and panning. 1018 | // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). 1019 | // This is very similar to OrbitControls, another set of touch behavior 1020 | // 1021 | // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate 1022 | // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish 1023 | // Pan - left mouse, or arrow keys / touch: one-finger move 1024 | 1025 | 1026 | class MapControls extends OrbitControls { 1027 | 1028 | constructor( object, domElement ) { 1029 | 1030 | super( object, domElement ); 1031 | this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up 1032 | 1033 | this.mouseButtons.LEFT = THREE.MOUSE.PAN; 1034 | this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE; 1035 | this.touches.ONE = THREE.TOUCH.PAN; 1036 | this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE; 1037 | 1038 | } 1039 | 1040 | } 1041 | 1042 | THREE.MapControls = MapControls; 1043 | THREE.OrbitControls = OrbitControls; 1044 | 1045 | } )(); 1046 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------