├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── demo.gif ├── examples └── abb │ ├── irb4600-40.blend │ └── irb4600-40.json └── export_webots.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.blend1 2 | .*.wbproj 3 | *.wbt 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Blender to Webots exporter add-on 2 | 3 | Blender add-on to export your Blender project to Webots. 4 | 5 | ![Demo](demo.gif) 6 | 7 | ## Features 8 | 9 | - Export your Blender project to Webots 10 | - Define conversion rules in a JSON file 11 | - Support collision export (either generated from the AABB boxes or manually defined) 12 | - Support joint export (linear or rotational with custom parameters including axis, limits, etc.) 13 | - Support the export of any [Webots Solid (or derived) node](https://www.cyberbotics.com/doc/reference/jointparameters) with custom fields (`Camera.width`, `name`, etc.). 14 | - Basic support of materials (colors and the base color map) to Webots PBR appearance. 15 | 16 | ## Requirements 17 | 18 | - [Blender 2.79b](https://download.blender.org/release/Blender2.79/) 19 | - [Webots R2019a.rev1](https://www.cyberbotics.com) or later 20 | 21 | ## Installation and Update 22 | 23 | Let say `$BLENDER_ADD_ON_PATH` is the Blender add-on user directory: 24 | 25 | - on macOS: `export BLENDER_ADD_ON_PATH=$HOME/Library/Application\ Support/Blender/2.79/scripts/addons` 26 | - on Linux: `export BLENDER_ADD_ON_PATH=$HOME/.config/blender/2.79/scripts/addons` 27 | - on Windows: 28 | - go to `Blender / Preferences / File / Scripts` and paste `C:\Users\username\AppData\Roaming\Blender Foundation\Blender\2.79\scripts`. (replace username) 29 | - for the following steps, use the pasted address as `$BLENDER_ADD_ON_PATH`. 30 | 31 | Install the add-on by applying the following commands: 32 | 33 | ``` 34 | mkdir -p $BLENDER_ADD_ON_PATH/export_webots 35 | cp __init__.py "$BLENDER_ADD_ON_PATH/export_webots" 36 | cp export_webots.py "$BLENDER_ADD_ON_PATH/export_webots" 37 | ``` 38 | 39 | Enable the "Webots exporter" add-on in `Blender / Preferences / Add-ons / Community`. 40 | 41 | ## JSON Conversion File Specifications 42 | 43 | The [JSON](https://en.wikipedia.org/wiki/JSON) conversion file specifies how to convert the Blender nodes to Webots ones. 44 | 45 | If not specified in the parameters, the JSON conversion file is searched in the same path as the `.blend` file. 46 | 47 | It is basically a JSON Object (i.e. key-value associative array) containing a conversion rule for each node. 48 | During the exportation, when a key of this JSON Object matches with the slugified Blender node name, then its value (a JSON Object) is used for the conversion. 49 | 50 | The conversion JSON Object could contain the following conversion rules: 51 | 52 | | Key | Flags | Value | 53 | | --- | --- | --- | 54 | | `target node` | _required_ | JSON String defining to which Webots node the Blender node should be converted. For example, it could be `Solid`, `Robot`, `Camera`, `HingeJoint`, `SliderJoint` or a custom Webots appearance node (like `BrushedAluminium`). | 55 | | `fields` | _optional_ | JSON Object which can contain any Webots node fields. The conversion tool will add these fields as-is. It is convenient to add device specific fields, like `Camera.width`, `Emitter.name`, etc. | 56 | 57 | The following conversion rules are only available in the case of a `Solid` node (or derived): 58 | 59 | | Key | Flags | Value | 60 | | --- | --- | --- | 61 | | `physics` | _optional_ | JSON Object which can contain the [Webots Physics node](https://www.cyberbotics.com/doc/reference/physics) fields (like `mass`, `density` and `centerOfMass`). If this key is not defined, then no `Physics` node is generated (the Solid can be pinned to the static environment, or controlled using kinematics rules.) | 62 | | `boundingObject` | _optional_ | JSON Object which can contain either a JSON String called `custom` to define the content of the [Webots Solid.boundingObject field](https://www.cyberbotics.com/doc/reference/solid) fields. If `custom` is not defined, then the AABB box of the Blender object is used to create the boundingObject. If this key is not defined, then no collision object is generated. | 63 | 64 | The following conversion rules are only available in the case of a `Joint` node: 65 | 66 | | Key | Flags | Value | 67 | | --- | --- | --- | 68 | | `jointParameters` | _optional_ | JSON Object which can contain the [Webots (Hinge)JointParameters node](https://www.cyberbotics.com/doc/reference/jointparameters) fields (like `axis`, `spring/dampingConstant` and `suspension*`). | 69 | | `motor` | _optional_ | JSON Object which can contain the [Webots LinearMotor or RotationalMotor node](https://www.cyberbotics.com/doc/reference/rotationalmotor) fields (like `name`, `maxTorque`, `maxPosition` or `maxVelocity`) | 70 | | `positionSensor` | _optional_ | JSON Object which can contain the [Webots PositionSensor node](https://www.cyberbotics.com/doc/reference/positionsensor) fields (like `name`) | 71 | 72 | Examples: 73 | 74 | https://github.com/cyberbotics/blender-webots-exporter/tree/master/examples 75 | 76 | 77 | ## References 78 | 79 | This script has been inspired by the [Blender X3D exporter](https://github.com/sobotka/blender-addons/blob/master/io_scene_x3d/export_x3d.py) of Campbell Barton, Bart, Bastien Montagne, Seva Alekseyev. 80 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 1996-2018 Cyberbotics Ltd. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | bl_info = { 16 | 'name': 'Webots format', 17 | 'author': 'Fabien Rohrer', 18 | 'version': (1, 1, 0), 19 | 'blender': (2, 79, 0), 20 | 'location': 'File > Import-Export', 21 | 'description': 'Export Webots', 22 | 'warning': '', 23 | 'wiki_url': 'https://github.com/omichel/blender-webots-exporter/wiki', 24 | 'support': 'COMMUNITY', 25 | 'category': 'Import-Export', 26 | } 27 | 28 | if 'bpy' in locals(): 29 | import importlib 30 | if 'export_webots' in locals(): 31 | importlib.reload(export_webots) 32 | 33 | import bpy 34 | from bpy.props import ( 35 | BoolProperty, 36 | FloatProperty, 37 | StringProperty, 38 | ) 39 | from bpy_extras.io_utils import ( 40 | ExportHelper, 41 | orientation_helper_factory, 42 | axis_conversion, 43 | path_reference_mode, 44 | ) 45 | 46 | 47 | IOX3DOrientationHelper = orientation_helper_factory('IOX3DOrientationHelper', axis_forward='Z', axis_up='Y') 48 | 49 | 50 | class ExportWebots(bpy.types.Operator, ExportHelper, IOX3DOrientationHelper): 51 | """Export selection to Webots file (.wbt)""" 52 | bl_idname = 'scene.wbt' 53 | bl_label = 'Export Webots' 54 | bl_options = {'PRESET'} 55 | 56 | filename_ext = '.wbt' 57 | filter_glob = StringProperty(default='*.wbt', options={'HIDDEN'}) 58 | 59 | use_selection = BoolProperty( 60 | name='Selection Only', 61 | description='Export selected objects only', 62 | default=False, 63 | ) 64 | use_mesh_modifiers = BoolProperty( 65 | name='Apply Modifiers', 66 | description='Use transformed mesh data from each object', 67 | default=True, 68 | ) 69 | converstion_file_path = StringProperty( 70 | name='Custom conversion File Path', 71 | description='File path targeting the JSON file containing the custom Blender->Webots conversion rules.', 72 | default='' 73 | ) 74 | global_scale = FloatProperty( 75 | name='Scale', 76 | min=0.01, max=1000.0, 77 | default=1.0, 78 | ) 79 | 80 | path_mode = path_reference_mode 81 | 82 | def execute(self, context): 83 | from . import export_webots 84 | from mathutils import Matrix 85 | 86 | keywords = self.as_keywords(ignore=('axis_forward', 'axis_up', 'global_scale', 'check_existing', 'filter_glob')) 87 | global_matrix = axis_conversion(to_forward=self.axis_forward, to_up=self.axis_up).to_4x4() * Matrix.Scale(self.global_scale, 4) 88 | keywords['global_matrix'] = global_matrix 89 | 90 | return export_webots.save(context, **keywords) 91 | 92 | 93 | def menu_func_export(self, context): 94 | self.layout.operator(ExportWebots.bl_idname, text='Webots (.wbt)') 95 | 96 | 97 | def register(): 98 | bpy.utils.register_module(__name__) 99 | bpy.types.INFO_MT_file_export.append(menu_func_export) 100 | 101 | 102 | def unregister(): 103 | bpy.utils.unregister_module(__name__) 104 | bpy.types.INFO_MT_file_export.remove(menu_func_export) 105 | 106 | 107 | if __name__ == '__main__': 108 | register() 109 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberbotics/blender-webots-exporter/c6f7bc0b9d0cfd8a8b4e765b9578ca720436da28/demo.gif -------------------------------------------------------------------------------- /examples/abb/irb4600-40.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberbotics/blender-webots-exporter/c6f7bc0b9d0cfd8a8b4e765b9578ca720436da28/examples/abb/irb4600-40.blend -------------------------------------------------------------------------------- /examples/abb/irb4600-40.json: -------------------------------------------------------------------------------- 1 | { 2 | "BASE": { 3 | "target node": "Robot", 4 | "boundingObject": { 5 | } 6 | }, 7 | "LINK_A": { 8 | "target node": "HingeJoint", 9 | "jointParameters": { 10 | "axis": "0 0 1" 11 | }, 12 | "motor": { 13 | "name": "A motor", 14 | "maxTorque": 10000, 15 | "minPosition": -3.1415, 16 | "maxPosition": 3.1415 17 | }, 18 | "positionSensor": { 19 | "name": "A sensor" 20 | }, 21 | "physics": { 22 | "density": 1150 23 | }, 24 | "boundingObject": { 25 | } 26 | }, 27 | "LINK_B": { 28 | "target node": "HingeJoint", 29 | "jointParameters": { 30 | "axis": "0 1 0" 31 | }, 32 | "motor": { 33 | "name": "B motor", 34 | "maxTorque": 10000, 35 | "minPosition": -1.5708, 36 | "maxPosition": 2.61799 37 | }, 38 | "positionSensor": { 39 | "name": "B sensor" 40 | }, 41 | "physics": { 42 | "density": 500 43 | }, 44 | "boundingObject": { 45 | } 46 | }, 47 | "LINK_C": { 48 | "target node": "HingeJoint", 49 | "jointParameters": { 50 | "axis": "0 1 0" 51 | }, 52 | "motor": { 53 | "name": "C motor", 54 | "maxTorque": 10000, 55 | "minPosition": -3.1415, 56 | "maxPosition": 1.309 57 | }, 58 | "positionSensor": { 59 | "name": "C sensor" 60 | }, 61 | "physics": { 62 | "density": 400 63 | }, 64 | "boundingObject": { 65 | } 66 | }, 67 | "LINK_D": { 68 | "target node": "HingeJoint", 69 | "jointParameters": { 70 | "axis": "1 0 0" 71 | }, 72 | "motor": { 73 | "name": "D motor", 74 | "maxTorque": 10000, 75 | "minPosition": -6.98132, 76 | "maxPosition": 6.98132 77 | }, 78 | "positionSensor": { 79 | "name": "D sensor" 80 | }, 81 | "physics": { 82 | "density": 300 83 | }, 84 | "boundingObject": { 85 | } 86 | }, 87 | "LINK_E": { 88 | "target node": "HingeJoint", 89 | "jointParameters": { 90 | "axis": "0 1 0" 91 | }, 92 | "motor": { 93 | "name": "E motor", 94 | "maxTorque": 10000, 95 | "minPosition": -2.18166, 96 | "maxPosition": 2.0944 97 | }, 98 | "positionSensor": { 99 | "name": "E sensor" 100 | }, 101 | "physics": { 102 | "density": 200 103 | }, 104 | "boundingObject": { 105 | } 106 | }, 107 | "LINK_F": { 108 | "target node": "HingeJoint", 109 | "jointParameters": { 110 | "axis": "1 0 0" 111 | }, 112 | "motor": { 113 | "name": "F motor", 114 | "maxTorque": 10000, 115 | "minPosition": -6.98132, 116 | "maxPosition": 6.98132 117 | }, 118 | "positionSensor": { 119 | "name": "F sensor" 120 | }, 121 | "physics": { 122 | "density": 100 123 | }, 124 | "boundingObject": { 125 | "custom": "Transform {\ntranslation -0.01 0 0\nrotation 0 0 1 1.5708\nchildren [\nCylinder {\nheight 0.04\nradius 0.065\n}\n]\n}" 126 | } 127 | }, 128 | "METAL": { 129 | "target node": "BrushedAluminium" 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /export_webots.py: -------------------------------------------------------------------------------- 1 | # Copyright 1996-2018 Cyberbotics Ltd. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """This Blender plugin script exports to the Webots format.""" 16 | 17 | import json 18 | import os 19 | import re 20 | 21 | import bpy 22 | import mathutils 23 | 24 | from bpy_extras.io_utils import create_derived_objects, free_derived_objects 25 | 26 | 27 | def export(file, global_matrix, scene, use_mesh_modifiers=False, use_selection=True, conversion_data={}, path_mode='AUTO'): 28 | """Export to wbt file.""" 29 | 30 | # Global Setup 31 | import bpy_extras 32 | from bpy_extras.io_utils import unique_name 33 | from xml.sax.saxutils import escape 34 | 35 | # Caches 36 | uuid_cache_object = {} 37 | uuid_cache_mesh = {} 38 | uuid_cache_image = {} 39 | 40 | # Decorators 41 | COORDS_ = 'COORDS_' 42 | OB_ = 'OB_' 43 | ME_ = 'ME_' 44 | IM_ = 'IM_' 45 | GROUP_ = 'GROUP_' 46 | _IFS = '_IFS' 47 | _TRANSFORM = '_TRANSFORM' 48 | 49 | copy_set = set() # Store files to copy. 50 | mesh_name_set = set() # Store names of newly cerated meshes, so we dont overlap 51 | 52 | base_src = os.path.dirname(bpy.data.filepath) 53 | base_dst = os.path.dirname(file.name) 54 | 55 | def fw(line): 56 | strippedLine = line.strip() 57 | if strippedLine.startswith('}') or strippedLine.startswith(']'): 58 | fw.indentation -= 1 59 | if fw.isLastCharacterACariageReturn: 60 | file.write(' ' * fw.indentation) 61 | file.write(line) 62 | fw.isLastCharacterACariageReturn = line.endswith('\n') 63 | if strippedLine.endswith('{') or strippedLine.endswith('['): 64 | fw.indentation += 1 65 | fw.indentation = 0 66 | fw.isLastCharacterACariageReturn = False 67 | 68 | def write_header(): 69 | fw('#VRML_SIM R2019a utf8\n') 70 | fw('WorldInfo {\n') 71 | fw('basicTimeStep 8\n') 72 | fw('}\n') 73 | fw('Viewpoint {\n') 74 | fw('orientation -0.5 -0.852 -0.159 0.71\n') 75 | fw('position -3.6 2.0 5.4\n') 76 | fw('}\n') 77 | fw('TexturedBackground {\n') 78 | fw('}\n') 79 | fw('TexturedBackgroundLight {\n') 80 | fw('}\n') 81 | 82 | def write_transform_begin(obj, matrix, def_id): 83 | translation, rotation, scale = matrix.decompose() 84 | rotation = rotation.to_axis_angle() 85 | rotation = (*rotation[0], rotation[1]) 86 | 87 | identityTranslation = nearly_equal(translation[0], 0.0) and nearly_equal(translation[1], 0.0) and nearly_equal(translation[2], 0.0) 88 | identityRotation = nearly_equal(rotation[3], 0.0) 89 | identityScale = nearly_equal(scale[0], 1.0) and nearly_equal(scale[1], 1.0) and nearly_equal(scale[2], 1.0) 90 | identity = identityTranslation and identityRotation and identityScale 91 | 92 | joint = False 93 | propeller = False 94 | 95 | isWebotsNode = def_id in conversion_data 96 | if isWebotsNode: 97 | fw('DEF %s ' % def_id) 98 | node_conversion_data = conversion_data[def_id] 99 | fw('%s {\n' % node_conversion_data['target node']) 100 | joint = 'Joint' in node_conversion_data['target node'] 101 | propeller = 'Propeller' == node_conversion_data['target node'] 102 | elif identity: 103 | return (True, False) # Skipped useless transform. 104 | else: 105 | if def_id is not None: 106 | fw('DEF %s ' % def_id) 107 | fw('Transform {\n') 108 | 109 | if joint: 110 | node_conversion_data = conversion_data[def_id] 111 | if 'jointParameters' in node_conversion_data: 112 | fw('jointParameters %sJointParameters {\n' % ('Hinge' if 'Hinge' in node_conversion_data['target node'] else '')) 113 | if not identityTranslation and 'Hinge' in node_conversion_data['target node']: 114 | fw('anchor %.6g %.6g %.6g\n' % translation[:]) 115 | for fieldName in node_conversion_data['jointParameters'].keys(): 116 | fieldValue = node_conversion_data['jointParameters'][fieldName] 117 | fw('%s %s\n' % (fieldName, str(fieldValue))) 118 | fw('}\n') 119 | fw('device [\n') 120 | if 'motor' in node_conversion_data: 121 | motor = node_conversion_data['motor'] 122 | if 'Hinge' in node_conversion_data['target node']: 123 | fw('RotationalMotor {\n') 124 | else: 125 | fw('LinearMotor {\n') 126 | for fieldName in motor.keys(): 127 | fieldValue = motor[fieldName] 128 | if fieldName == "name": 129 | fw('%s "%s"\n' % (fieldName, str(fieldValue))) 130 | else: 131 | fw('%s %s\n' % (fieldName, str(fieldValue))) 132 | fw('}\n') 133 | if 'positionSensor' in node_conversion_data: 134 | positionSensor = node_conversion_data['positionSensor'] 135 | fw('PositionSensor {\n') 136 | for fieldName in positionSensor.keys(): 137 | fieldValue = positionSensor[fieldName] 138 | if fieldName == "name": 139 | fw('%s "%s"\n' % (fieldName, str(fieldValue))) 140 | else: 141 | fw('%s %s\n' % (fieldName, str(fieldValue))) 142 | fw('}\n') 143 | fw(']\n') 144 | fw('endPoint Solid {\n') 145 | if 'motor' in node_conversion_data and 'name' in node_conversion_data['motor']: 146 | fw('name "%s"\n' % node_conversion_data['motor']['name']) 147 | elif propeller: 148 | node_conversion_data = conversion_data[def_id] 149 | fw('centerOfThrust %.6g %.6g %.6g\n' % translation[:]) 150 | if 'propellerFields' in node_conversion_data: 151 | for fieldName in node_conversion_data['propellerFields'].keys(): 152 | fieldValue = node_conversion_data['propellerFields'][fieldName] 153 | fw('%s %s\n' % (fieldName, str(fieldValue))) 154 | if 'motor' in node_conversion_data: 155 | motor = node_conversion_data['motor'] 156 | fw('device RotationalMotor {\n') 157 | for fieldName in motor.keys(): 158 | fieldValue = motor[fieldName] 159 | if fieldName == "name": 160 | fw('%s "%s"\n' % (fieldName, str(fieldValue))) 161 | else: 162 | fw('%s %s\n' % (fieldName, str(fieldValue))) 163 | fw('}\n') 164 | fw('slowHelix Solid {\n') 165 | if 'motor' in node_conversion_data and 'name' in node_conversion_data['motor']: 166 | fw('name "%s"\n' % node_conversion_data['motor']['name']) 167 | 168 | if not identityTranslation: 169 | fw('translation %.6g %.6g %.6g\n' % translation[:]) 170 | if not identityRotation: 171 | fw('rotation %.6g %.6g %.6g %.6g\n' % rotation) 172 | if not identityScale: 173 | fw('scale %.6g %.6g %.6g\n' % scale[:]) 174 | 175 | if isWebotsNode: 176 | if 'fields' in node_conversion_data: 177 | for fieldName in node_conversion_data['fields'].keys(): 178 | fieldValue = node_conversion_data['fields'][fieldName] 179 | if fieldName == "name": 180 | fw('%s "%s"\n' % (fieldName, str(fieldValue))) 181 | else: 182 | fw('%s %s\n' % (fieldName, str(fieldValue))) 183 | if 'boundingObject' in node_conversion_data: 184 | if 'custom' in node_conversion_data['boundingObject']: 185 | fw('boundingObject ') 186 | for line in node_conversion_data['boundingObject']['custom'].split('\n'): 187 | fw('%s\n' % line) 188 | else: 189 | fw('boundingObject Transform {\n') 190 | x = 0.5 * (max([v[0] for v in obj.bound_box]) + min([v[0] for v in obj.bound_box])) 191 | y = 0.5 * (max([v[1] for v in obj.bound_box]) + min([v[1] for v in obj.bound_box])) 192 | z = 0.5 * (max([v[2] for v in obj.bound_box]) + min([v[2] for v in obj.bound_box])) 193 | fw('translation %.6g %.6g %.6g\n' % (x, y, z)) 194 | fw('children [\n') 195 | fw('Box {\n') 196 | fw('size %.6g %.6g %.6g\n' % obj.dimensions[:]) 197 | fw('}\n') 198 | fw(']\n') 199 | fw('}\n') 200 | if 'physics' in node_conversion_data: 201 | fw('physics Physics {\n') 202 | for fieldName in node_conversion_data['physics'].keys(): 203 | fieldValue = node_conversion_data['physics'][fieldName] 204 | if fieldName == 'mass': 205 | fw('density -1\n') 206 | fw('%s %s\n' % (fieldName, str(fieldValue))) 207 | fw('}\n') 208 | 209 | fw('children [\n') 210 | 211 | return (False, joint or propeller) 212 | 213 | def write_transform_end(supplementaryCurvyBracket): 214 | fw(']\n') 215 | fw('}\n') 216 | if supplementaryCurvyBracket: 217 | fw('}\n') 218 | 219 | def write_indexed_face_set(obj, mesh, matrix, world): 220 | obj_id = unique_name(obj, OB_ + obj.name, uuid_cache_object, clean_func=slugify, sep='_') 221 | mesh_id = unique_name(mesh, ME_ + mesh.name, uuid_cache_mesh, clean_func=slugify, sep='_') 222 | mesh_id_group = GROUP_ + mesh_id 223 | mesh_id_coords = COORDS_ + mesh_id 224 | 225 | # Tessellation faces may not exist. 226 | if not mesh.tessfaces and mesh.polygons: 227 | mesh.update(calc_tessface=True) 228 | 229 | if not mesh.tessfaces: 230 | return 231 | 232 | # Use _IFS_TRANSFORM suffix so we dont collide with transform node when hierarchys are used. 233 | (skipUselessTransform, supplementaryCurvyBracket) = write_transform_begin(obj, matrix, obj_id + _IFS + _TRANSFORM) 234 | 235 | if mesh.tag: 236 | fw('USE %s\n' % (mesh_id_group)) 237 | else: 238 | mesh.tag = True 239 | 240 | is_uv = bool(mesh.tessface_uv_textures.active) 241 | is_coords_written = False 242 | 243 | mesh_materials = mesh.materials[:] 244 | if not mesh_materials: 245 | mesh_materials = [None] 246 | 247 | mesh_material_tex = [None] * len(mesh_materials) 248 | mesh_material_mtex = [None] * len(mesh_materials) 249 | mesh_material_images = [None] * len(mesh_materials) 250 | 251 | for i, material in enumerate(mesh_materials): 252 | if material: 253 | for mtex in material.texture_slots: 254 | if mtex: 255 | tex = mtex.texture 256 | if tex and tex.type == 'IMAGE': 257 | image = tex.image 258 | if image: 259 | mesh_material_tex[i] = tex 260 | mesh_material_mtex[i] = mtex 261 | mesh_material_images[i] = image 262 | break 263 | 264 | mesh_materials_use_face_texture = [getattr(material, 'use_face_texture', True) for material in mesh_materials] 265 | 266 | mesh_faces = mesh.tessfaces[:] 267 | mesh_faces_materials = [f.material_index for f in mesh_faces] 268 | mesh_faces_vertices = [f.vertices[:] for f in mesh_faces] 269 | 270 | if is_uv and True in mesh_materials_use_face_texture: 271 | mesh_faces_image = [ 272 | (fuv.image if mesh_materials_use_face_texture[mesh_faces_materials[i]] 273 | else mesh_material_images[mesh_faces_materials[i]]) 274 | for i, fuv in enumerate(mesh.tessface_uv_textures.active.data) 275 | ] 276 | 277 | mesh_faces_image_unique = set(mesh_faces_image) 278 | elif len(set(mesh_material_images) | {None}) > 1: # Make sure there is at least one image 279 | mesh_faces_image = [mesh_material_images[material_index] for material_index in mesh_faces_materials] 280 | mesh_faces_image_unique = set(mesh_faces_image) 281 | else: 282 | mesh_faces_image = [None] * len(mesh_faces) 283 | mesh_faces_image_unique = {None} 284 | 285 | # Group faces. 286 | face_groups = {} 287 | for material_index in range(len(mesh_materials)): 288 | for image in mesh_faces_image_unique: 289 | face_groups[material_index, image] = [] 290 | del mesh_faces_image_unique 291 | 292 | for i, (material_index, image) in enumerate(zip(mesh_faces_materials, mesh_faces_image)): 293 | face_groups[material_index, image].append(i) 294 | 295 | # Same as face_groups.items() but sorted so we can get predictable output. 296 | face_groups_items = list(face_groups.items()) 297 | face_groups_items.sort(key=lambda m: (m[0][0], getattr(m[0][1], 'name', ''))) 298 | 299 | for (material_index, image), face_group in face_groups_items: # face_groups.items() 300 | if face_group: 301 | fw('Shape {\n') 302 | 303 | is_smooth = False 304 | 305 | for i in face_group: 306 | if mesh_faces[i].use_smooth: 307 | is_smooth = True 308 | break 309 | 310 | material = mesh_materials[material_index] 311 | if material is not None: 312 | material_def_name = slugify(material.name) 313 | if material_def_name in conversion_data and 'target node' in conversion_data[material_def_name]: 314 | material_data = conversion_data[material_def_name] 315 | fw('appearance %s {\n' % (material_data['target node'])) 316 | if 'fields' in material_data: 317 | for fieldName in material_data['fields'].keys(): 318 | fieldValue = material_data['fields'][fieldName] 319 | fw('%s %s\n' % (fieldName, str(fieldValue))) 320 | fw('}\n') 321 | else: 322 | if material_def_name: 323 | fw('appearance DEF %s PBRAppearance {\n' % (material_def_name)) 324 | else: 325 | fw('appearance PBRAppearance {\n') 326 | 327 | if image: 328 | write_image_texture(image) 329 | 330 | if material: 331 | diffuse = material.diffuse_color[:] 332 | ambient = ((material.ambient * 2.0) * world.ambient_color)[:] if world else [0.0, 0.0, 0.0] 333 | emissive = tuple(((c * material.emit) + ambient[i]) / 2.0 for i, c in enumerate(diffuse)) 334 | 335 | fw('baseColor %.6g %.6g %.6g\n' % clamp_color(diffuse)) 336 | fw('emissiveColor %.6g %.6g %.6g\n' % clamp_color(emissive)) 337 | fw('metalness 0\n') 338 | fw('roughness 0.5\n') 339 | if material.use_transparency: 340 | fw('transparency %f\n' % (1.0 - material.alpha)) 341 | 342 | fw('}\n') # -- PBRAppearance 343 | 344 | mesh_faces_uv = mesh.tessface_uv_textures.active.data if is_uv else None 345 | 346 | fw('geometry IndexedFaceSet {\n') 347 | 348 | if is_smooth: 349 | # use Auto-Smooth angle, if enabled. Otherwise make 350 | # the mesh perfectly smooth by creaseAngle > pi. 351 | fw('creaseAngle %.6g\n' % (mesh.auto_smooth_angle if mesh.use_auto_smooth else 1.0)) 352 | 353 | # for IndexedTriangleSet we use a uv per vertex so this isnt needed. 354 | if is_uv: 355 | fw('texCoordIndex [\n') 356 | 357 | j = 0 358 | for i in face_group: 359 | if len(mesh_faces_vertices[i]) == 4: 360 | fw('%d %d %d %d -1 ' % (j, j + 1, j + 2, j + 3)) 361 | j += 4 362 | else: 363 | fw('%d %d %d -1 ' % (j, j + 1, j + 2)) 364 | j += 3 365 | fw('\n') 366 | fw(']\n') 367 | 368 | if True: 369 | fw('coordIndex [\n') 370 | for i in face_group: 371 | fv = mesh_faces_vertices[i] 372 | if len(fv) == 3: 373 | fw('%i %i %i -1 ' % fv) 374 | else: 375 | fw('%i %i %i %i -1 ' % fv) 376 | fw('\n') 377 | fw(']\n') 378 | 379 | if True: 380 | if is_coords_written: 381 | fw('coord USE %s\n' % (mesh_id_coords)) 382 | else: 383 | fw('coord ') 384 | fw('DEF %s ' % mesh_id_coords) 385 | fw('Coordinate {\n') 386 | fw('point [\n') 387 | for v in mesh.vertices: 388 | fw('%.6g %.6g %.6g ' % v.co[:]) 389 | fw('\n') 390 | fw(']\n') 391 | fw('}\n') 392 | 393 | is_coords_written = True 394 | 395 | if is_uv: 396 | fw('texCoord TextureCoordinate {\n') 397 | fw('point [\n') 398 | for i in face_group: 399 | for uv in mesh_faces_uv[i].uv: 400 | fw('%.6g %.6g ' % uv[:]) 401 | del mesh_faces_uv 402 | fw('\n') 403 | fw(']\n') 404 | fw('}\n') 405 | 406 | fw('}\n') # --- IndexedFaceSet 407 | fw('}\n') # --- Shape 408 | 409 | if not skipUselessTransform: 410 | write_transform_end(supplementaryCurvyBracket) 411 | 412 | def write_image_texture(image): 413 | image_id = unique_name(image, IM_ + image.name, uuid_cache_image, clean_func=slugify, sep='_') 414 | 415 | if image.tag: 416 | fw('texture USE %s\n' % (image_id)) 417 | else: 418 | image.tag = True 419 | 420 | fw('baseColorMap ') 421 | fw('DEF %s ' % image_id) 422 | fw('ImageTexture {\n') 423 | 424 | # Collect image paths, can load multiple [relative, name-only, absolute] 425 | filepath = image.filepath 426 | filepath_full = bpy.path.abspath(filepath, library=image.library) 427 | filepath_ref = bpy_extras.io_utils.path_reference(filepath_full, base_src, base_dst, path_mode, 'textures', copy_set, image.library) 428 | filepath_base = os.path.basename(filepath_full) 429 | 430 | images = [ 431 | filepath_ref, 432 | filepath_base, 433 | ] 434 | if path_mode != 'RELATIVE': 435 | images.append(filepath_full) 436 | 437 | images = [f.replace('\\', '/') for f in images] 438 | images = [f for i, f in enumerate(images) if f not in images[:i]] 439 | 440 | fw('url [ %s ]\n' % ' '.join(['"%s"' % escape(f) for f in images])) 441 | fw('}\n') 442 | 443 | def export_object(obj_main_parent, obj_main, obj_children): 444 | """Export Object Hierarchy (recursively called).""" 445 | matrix_fallback = mathutils.Matrix() 446 | world = scene.world 447 | free, derived = create_derived_objects(scene, obj_main) 448 | 449 | obj_main_matrix_world = obj_main.matrix_world 450 | if obj_main_parent: 451 | obj_main_matrix = obj_main_parent.matrix_world.inverted(matrix_fallback) * obj_main_matrix_world 452 | else: 453 | obj_main_matrix = obj_main_matrix_world 454 | obj_main_matrix_world_invert = obj_main_matrix_world.inverted(matrix_fallback) 455 | 456 | obj_main_id = unique_name(obj_main, obj_main.name, uuid_cache_object, clean_func=slugify, sep='_') 457 | 458 | (skipUselessTransform, supplementaryCurvyBracket) = write_transform_begin(obj_main, obj_main_matrix if obj_main_parent else global_matrix * obj_main_matrix, obj_main_id) 459 | 460 | for obj, obj_matrix in (() if derived is None else derived): 461 | obj_type = obj.type 462 | obj_matrix = obj_main_matrix_world_invert * obj_matrix # Make transform node relative. 463 | 464 | if obj_type in {'MESH', 'CURVE', 'SURFACE', 'FONT'}: 465 | if (obj_type != 'MESH') or (use_mesh_modifiers and obj.is_modified(scene, 'PREVIEW')): 466 | me = obj.to_mesh(scene, use_mesh_modifiers, 'PREVIEW') 467 | do_remove = True 468 | else: 469 | me = obj.data 470 | do_remove = False 471 | 472 | if me is not None: 473 | # ensure unique name, we could also do this by 474 | # postponing mesh removal, but clearing data - TODO 475 | if do_remove: 476 | me.name = obj.name.rstrip('1234567890').rstrip('.') 477 | me_name_new = me_name_org = me.name 478 | count = 0 479 | while me_name_new in mesh_name_set: 480 | me.name = '%.17s.%03d' % (me_name_org, count) 481 | me_name_new = me.name 482 | count += 1 483 | mesh_name_set.add(me_name_new) 484 | del me_name_new, me_name_org, count 485 | 486 | write_indexed_face_set(obj, me, obj_matrix, world) 487 | 488 | # Rree mesh created with create_mesh() 489 | if do_remove: 490 | bpy.data.meshes.remove(me) 491 | 492 | else: 493 | # print('Info: Ignoring [%s], object type [%s] not handle yet' % (object.name,object.getType)) 494 | pass 495 | 496 | if free: 497 | free_derived_objects(obj_main) 498 | 499 | # Write out children recursively 500 | for obj_child, obj_child_children in obj_children: 501 | export_object(obj_main, obj_child, obj_child_children) 502 | 503 | if not skipUselessTransform: 504 | write_transform_end(supplementaryCurvyBracket) 505 | 506 | def export_main(): 507 | """Main Export Function.""" 508 | 509 | # tag un-exported IDs 510 | bpy.data.meshes.tag(False) 511 | bpy.data.materials.tag(False) 512 | bpy.data.images.tag(False) 513 | 514 | if use_selection: 515 | objects = [obj for obj in scene.objects if obj.is_visible(scene) and obj.select] 516 | else: 517 | objects = [obj for obj in scene.objects if obj.is_visible(scene)] 518 | 519 | print('Info: starting Webots export to %r...' % file.name) 520 | write_header() 521 | 522 | objects_hierarchy = build_hierarchy(objects) 523 | 524 | for obj_main, obj_main_children in objects_hierarchy: 525 | export_object(None, obj_main, obj_main_children) 526 | 527 | export_main() 528 | 529 | # Global cleanup 530 | file.close() 531 | 532 | # Copy all collected files. 533 | bpy_extras.io_utils.path_reference_copy(copy_set) 534 | 535 | print('Info: finished Webots export to %r' % file.name) 536 | 537 | 538 | def save(context, filepath, *, use_selection=True, use_mesh_modifiers=False, converstion_file_path='', global_matrix=None, path_mode='AUTO'): 539 | bpy.path.ensure_ext(filepath, '.wbt') 540 | if bpy.ops.object.mode_set.poll(): 541 | bpy.ops.object.mode_set(mode='OBJECT') 542 | 543 | file = open(filepath, 'w', encoding='utf-8') 544 | 545 | if global_matrix is None: 546 | global_matrix = mathutils.Matrix() 547 | 548 | conversion_data = {} 549 | 550 | if not converstion_file_path or not os.path.isfile(converstion_file_path): 551 | converstion_file_path = bpy.data.filepath.replace('.blend', '.json') 552 | 553 | if converstion_file_path and os.path.isfile(converstion_file_path): 554 | with open(converstion_file_path) as f: 555 | conversion_data = json.load(f) 556 | 557 | export(file, global_matrix, context.scene, use_mesh_modifiers=use_mesh_modifiers, use_selection=use_selection, conversion_data=conversion_data, path_mode=path_mode) 558 | 559 | return {'FINISHED'} 560 | 561 | 562 | def clamp_color(col): 563 | return tuple([max(min(c, 1.0), 0.0) for c in col]) 564 | 565 | 566 | def matrix_direction_neg_z(matrix): 567 | return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()[:] 568 | 569 | 570 | def bool_as_str(value): 571 | return ('FALSE', 'TRUE')[bool(value)] 572 | 573 | 574 | def slugify(s): 575 | if not s: 576 | s = 'none' 577 | s = s.upper() 578 | for k in range(len(s)): 579 | if not re.match(r'[A-Z]', s[k]): 580 | s = s[:k] + '_' + s[(k + 1):] 581 | if not re.match(r'[A-Z]', s[0]): 582 | s = '_' + s 583 | while '__' in s: 584 | s = s.replace('__', '_') 585 | if s[-1] == '_': 586 | s = s[:-1] 587 | return s 588 | 589 | 590 | def nearly_equal(a, b, sig_fig=5): 591 | return a == b or int(a * 10 ** sig_fig) == int(b * 10 ** sig_fig) 592 | 593 | 594 | def build_hierarchy(objects): 595 | """Returns parent child relationships, skipping.""" 596 | objects_set = set(objects) 597 | par_lookup = {} 598 | 599 | def test_parent(parent): 600 | while (parent is not None) and (parent not in objects_set): 601 | parent = parent.parent 602 | return parent 603 | 604 | for obj in objects: 605 | par_lookup.setdefault(test_parent(obj.parent), []).append((obj, [])) 606 | 607 | for parent, children in par_lookup.items(): 608 | for obj, subchildren in children: 609 | subchildren[:] = par_lookup.get(obj, []) 610 | 611 | return par_lookup.get(None, []) 612 | --------------------------------------------------------------------------------