├── .bumpversion.cfg ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── _config.yml ├── data ├── lift_duck.json ├── push_teddy.json └── tea_time.json ├── mano_pybullet ├── __init__.py ├── __version__.py ├── envs │ ├── __init__.py │ ├── hand_env.py │ ├── hand_lift_env.py │ ├── hand_object_env.py │ ├── hand_push_env.py │ └── wrappers │ │ ├── __init__.py │ │ ├── gif_recorder.py │ │ ├── json_player.py │ │ └── json_recorder.py ├── hand_body.py ├── hand_model.py ├── mano_model.py ├── math_utils.py ├── mesh_utils.py └── tools │ ├── __init__.py │ └── gui_control.py ├── media ├── lift_duck.gif ├── push_teddy.gif └── tea_time.gif ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── envs ├── __init__.py ├── test_hand_env.py ├── test_hand_lift_env.py ├── test_hand_object_env.py └── test_hand_push_env.py ├── test_hand_body.py ├── test_hand_model.py ├── test_mano_model.py └── test_math_utils.py /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | commit = True 3 | tag = False 4 | current_version = 0.1.0 5 | parse = (?P\d+)\.(?P\d+)\.(?P\d+) 6 | serialize = 7 | {major}.{minor}.{patch} 8 | 9 | [bumpversion:file:setup.py] 10 | 11 | [bumpversion:file:mano_pybullet/__version__.py] 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## c++ 2 | 3 | # Prerequisites 4 | *.d 5 | 6 | # Compiled Object files 7 | *.slo 8 | *.lo 9 | *.o 10 | *.obj 11 | 12 | # Precompiled Headers 13 | *.gch 14 | *.pch 15 | 16 | # Compiled Dynamic libraries 17 | *.so 18 | *.dylib 19 | *.dll 20 | 21 | # Fortran module files 22 | *.mod 23 | *.smod 24 | 25 | # Compiled Static libraries 26 | *.lai 27 | *.la 28 | *.a 29 | *.lib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | 36 | ## python 37 | 38 | # Byte-compiled / optimized / DLL files 39 | __pycache__/ 40 | *.py[cod] 41 | *$py.class 42 | 43 | # C extensions 44 | *.so 45 | 46 | # Distribution / packaging 47 | .Python 48 | build/ 49 | develop-eggs/ 50 | dist/ 51 | downloads/ 52 | eggs/ 53 | .eggs/ 54 | lib/ 55 | lib64/ 56 | parts/ 57 | sdist/ 58 | var/ 59 | wheels/ 60 | *.egg-info/ 61 | .installed.cfg 62 | *.egg 63 | MANIFEST 64 | 65 | # PyInstaller 66 | # Usually these files are written by a python script from a template 67 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 68 | *.manifest 69 | *.spec 70 | 71 | # Installer logs 72 | pip-log.txt 73 | pip-delete-this-directory.txt 74 | 75 | # Unit test / coverage reports 76 | htmlcov/ 77 | .tox/ 78 | .coverage 79 | .coverage.* 80 | .cache 81 | nosetests.xml 82 | coverage.xml 83 | *.cover 84 | .hypothesis/ 85 | .pytest_cache/ 86 | 87 | # Translations 88 | *.mo 89 | *.pot 90 | 91 | # Django stuff: 92 | *.log 93 | local_settings.py 94 | db.sqlite3 95 | 96 | # Flask stuff: 97 | instance/ 98 | .webassets-cache 99 | 100 | # Scrapy stuff: 101 | .scrapy 102 | 103 | # Sphinx documentation 104 | docs/_build/ 105 | 106 | # PyBuilder 107 | target/ 108 | 109 | # Jupyter Notebook 110 | .ipynb_checkpoints 111 | 112 | # pyenv 113 | .python-version 114 | 115 | # celery beat schedule file 116 | celerybeat-schedule 117 | 118 | # SageMath parsed files 119 | *.sage.py 120 | 121 | # Environments 122 | .env 123 | .venv 124 | env/ 125 | venv/ 126 | ENV/ 127 | env.bak/ 128 | venv.bak/ 129 | 130 | # Spyder project settings 131 | .spyderproject 132 | .spyproject 133 | 134 | # Rope project settings 135 | .ropeproject 136 | 137 | # mkdocs documentation 138 | /site 139 | 140 | # mypy 141 | .mypy_cache/ 142 | 143 | # vscode 144 | .vscode/ 145 | 146 | .DS_Store 147 | 148 | /test.* 149 | /test_semantic.glb 150 | /test_semantic.ply 151 | 152 | compile_commands.json 153 | .vimtags 154 | .ycm* 155 | 156 | .autoenv* 157 | 158 | build_with_utils.sh 159 | run_example 160 | .lvimrc 161 | .ccls-cache/ 162 | 163 | # Vim swap files 164 | *.swp 165 | 166 | # temp folder 167 | /tmp 168 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md LICENSE 2 | include *.cfg 3 | recursive-include media *.gif 4 | recursive-include data *.json 5 | recursive-include tests *.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mano_pybullet 2 | [MANO](http://mano.is.tue.mpg.de/)-based hand models for the [PyBullet](https://pybullet.org/wordpress/) simulator. 3 | 4 | ## Install 5 | 6 | ### From source code 7 | 8 | ``` 9 | git clone https://github.com/ikalevatykh/mano_pybullet.git 10 | cd mano_pybullet 11 | pip install -e . 12 | ``` 13 | or if you plan to use [OpenAI gym](https://gym.openai.com/) environments: 14 | ``` 15 | pip install -e .[gym] 16 | ``` 17 | 18 | ### Run tests 19 | 20 | ``` 21 | export MANO_MODELS_DIR='/path/to/mano_v*_*/models/' 22 | pytest 23 | ``` 24 | 25 | ## Download MANO models 26 | 27 | - Register at the [MANO website](http://mano.is.tue.mpg.de/) and download the models. 28 | - Unzip the file mano_v*_*.zip: `unzip mano_v*_*.zip` 29 | - Set environment variable: `export MANO_MODELS_DIR=/path/to/mano_v*_*/models/` 30 | 31 | 32 | ## Hand models 33 | 34 | The package provides MANO-based rigid hand model. 35 | 36 | ![TeaTime](https://github.com/ikalevatykh/mano_pybullet/blob/main/media/tea_time.gif?raw=true "TeaTime") 37 | 38 | ## Gym environments 39 | 40 | The package also provides several [OpenAI gym](https://gym.openai.com/) environments: 41 | 42 | - HandEnv - base environment with one or two hands on the scene. 43 | 44 | - HandObjectEnv - base environment with hands and an object on the scene. 45 | 46 | - HandLiftEnv - environment where the target is to lift an object. 47 | 48 | ![HandLiftEnv](https://github.com/ikalevatykh/mano_pybullet/blob/main/media/lift_duck.gif?raw=true "HandLiftEnv") 49 | 50 | - HandPushEnv - environment where the target is to push an object. 51 | 52 | ![HandPushEnv](https://github.com/ikalevatykh/mano_pybullet/blob/main/media/push_teddy.gif?raw=true "HandPushEnv") 53 | 54 | 55 | ## Graphical debugging 56 | 57 | ``` 58 | python -m mano_pybullet.tools.gui_control 59 | ``` 60 | 61 | usage: GUI debug tool [-h] [--dofs DOFS] [--left-hand] [--right-hand] [--visual-shapes] [--no-visual-shapes] [--self-collisions] [--no-self-collisions] 62 | 63 | optional arguments: 64 | - -h, --help show help message and exit 65 | - --dofs DOFS number of degrees of freedom (20 or 45) [default=20] 66 | - --left-hand show left hand 67 | - --right-hand show right hand [default] 68 | - --visual-shapes show visual shapes [default] 69 | - --no-visual-shapes hide visual shapes 70 | - --self-collisions enable self collisions [default] 71 | - --no-self-collisions disable self collisions 72 | 73 | ## Citation 74 | If you find mano_pybullet useful in your research, please cite the repository using the following BibTeX entry. 75 | ``` 76 | @Misc{kalevatykh2020mano_pybullet, 77 | author = {Kalevatykh, Igor et al.}, 78 | title = {mano_pybullet - porting the MANO hand model to the PyBullet simulator}, 79 | howpublished = {Github}, 80 | year = {2020}, 81 | url = {https://github.com/ikalevatykh/mano_pybullet} 82 | } 83 | ``` 84 | ## License 85 | mano_pybullet is released under the [GPLv3](https://github.com/ikalevatykh/mano_pybullet/blob/master/LICENSE). -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /mano_pybullet/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/mano_pybullet/__init__.py -------------------------------------------------------------------------------- /mano_pybullet/__version__.py: -------------------------------------------------------------------------------- 1 | """Porting the MANO hand model to the PyBullet physics simulation engine.""" 2 | 3 | __title__ = 'mano_pybullet' 4 | __description__ = 'MANO-based hand models for the PyBullet simulator.' 5 | __url__ = 'https://github.com/ikalevatykh/mano_pybullet' 6 | __author__ = 'Igor Kalevatykh' 7 | __author_email__ = 'kalevatykhia@gmail.com' 8 | __license__ = 'GPLv3' 9 | __copyright__ = 'Copyright 2020 Igor Kalevatykh' 10 | __version__ = '0.1.0' 11 | 12 | __all__ = ['__author__', '__author_email__', '__copyright__', 13 | '__description__', '__license__', '__title__', '__url__', '__version__'] 14 | -------------------------------------------------------------------------------- /mano_pybullet/envs/__init__.py: -------------------------------------------------------------------------------- 1 | """Hand environments.""" 2 | 3 | try: 4 | import gym 5 | except ModuleNotFoundError as err: 6 | raise RuntimeError('Package not found: gym. Use `pip install gym` to install.') from err 7 | 8 | 9 | gym.envs.registration.register( 10 | id='HandLiftEnv-v1', 11 | entry_point='mano_pybullet.envs:HandLiftEnv', 12 | ) 13 | 14 | gym.envs.registration.register( 15 | id='HandPushEnv-v1', 16 | entry_point='mano_pybullet.envs:HandPushEnv', 17 | ) 18 | -------------------------------------------------------------------------------- /mano_pybullet/envs/hand_env.py: -------------------------------------------------------------------------------- 1 | """Base Hand Environment.""" 2 | 3 | import gym 4 | import numpy as np 5 | import pybullet as pb 6 | import pybullet_data as pd 7 | from numpy.random import RandomState 8 | from pybullet_utils.bullet_client import BulletClient 9 | 10 | from ..hand_body import HandBody 11 | from ..hand_model import HandModel20 12 | 13 | __all__ = ('HandEnv') 14 | 15 | 16 | class HandEnv(gym.Env): 17 | """The base Hand Environment class.""" 18 | 19 | # The environment can have both or a single hand 20 | HAND_RIGHT = 1 21 | HAND_LEFT = 2 22 | HAND_BOTH = HAND_LEFT + HAND_RIGHT 23 | 24 | # The environment can be controlled in joint or MANO-pose spaces 25 | MODE_JOINT = 1 26 | MODE_MANO = 2 27 | MODE_LIST = (MODE_JOINT, MODE_MANO) 28 | 29 | # Shape betas magnitude 30 | SHAPE_BETAS_MAGNITUDE = 0.1 31 | 32 | metadata = { 33 | 'render.modes': ['rgb_array'], 34 | 'video.frames_per_second': 60.0, 35 | 'video.output_frames_per_second': 30.0, 36 | 'step_time': 1.0 / 60.0} 37 | 38 | def __init__(self, 39 | hand_side=HAND_RIGHT, 40 | control_mode=MODE_JOINT, 41 | hand_model_cls=HandModel20, 42 | randomize_hand_shape=False): 43 | """Constructor of a HandEnv. 44 | 45 | Keyword Arguments: 46 | hand_side {int} -- hand side: left, right or both (default: {HAND_BOTH}) 47 | control_mode {int} -- control modalities (default: {MODE_JOINT}) 48 | hand_model_cls {type} -- hand kinematic model (default: {HandModel20}) 49 | randomize_hand_shape {bool} -- randomize hand shape at reset (default: {True}) 50 | """ 51 | assert hand_side & self.HAND_BOTH, f'Wrong hand side flag: {hand_side}' 52 | assert control_mode in self.MODE_LIST, f'Wrong control mode flag: {control_mode}' 53 | 54 | self._hand_side = hand_side 55 | self._control_mode = control_mode 56 | self._randomize_hand_shape = randomize_hand_shape 57 | 58 | self._show_window = False 59 | self._random = None 60 | self._client = None 61 | self._hand_bodies = None 62 | self._camera_shape = (320, 240) 63 | self._camera_view = None 64 | self._camera_proj = None 65 | 66 | self._hand_models = [] 67 | if self.HAND_LEFT & hand_side: 68 | self._hand_models.append(hand_model_cls(left_hand=True)) 69 | if self.HAND_RIGHT & hand_side: 70 | self._hand_models.append(hand_model_cls(left_hand=False)) 71 | 72 | # if control in joint space 73 | if self.MODE_JOINT == control_mode: 74 | joint_low, joint_high = map(np.float32, self._hand_models[0].dofs_limits) 75 | self.action_space = gym.spaces.Tuple([ 76 | gym.spaces.Tuple(( 77 | gym.spaces.Box(-5.0, 5.0, shape=(3,)), # base position x,y,z 78 | gym.spaces.Box(-1.0, 1.0, shape=(4,)), # base quaternion x,y,z,w 79 | gym.spaces.Box(joint_low, joint_high), # joint angles 80 | )) for _ in self._hand_models]) 81 | self.observation_space = gym.spaces.Tuple([ 82 | gym.spaces.Tuple(( 83 | gym.spaces.Box(-5.0, 5.0, shape=(3,)), # base position x,y,z 84 | gym.spaces.Box(-1.0, 1.0, shape=(4,)), # base quaternion x,y,z,w 85 | gym.spaces.Box(-10.0, 10.0, shape=(6,)), # base constraint forces 86 | gym.spaces.Box(joint_low, joint_high), # joint angles 87 | gym.spaces.Box(-3.0, 3.0, shape=(len(joint_low),)), # joint velocities 88 | gym.spaces.Box(-1.0, 1.0, shape=(len(joint_low),)), # joint torques 89 | )) for _ in self._hand_models]) 90 | # if control in MANO space 91 | elif self.MODE_MANO == control_mode: 92 | self.action_space = gym.spaces.Tuple([ 93 | gym.spaces.Tuple(( 94 | gym.spaces.Box(-5.0, 5.0, shape=(3,)), # trans 95 | gym.spaces.Box(-np.pi, np.pi, shape=(16, 3)), # pose 96 | )) for _ in self._hand_models]) 97 | self.observation_space = gym.spaces.Tuple([ 98 | gym.spaces.Tuple(( 99 | gym.spaces.Box(-5.0, 5.0, shape=(3,)), # trans 100 | gym.spaces.Box(-np.pi, np.pi, shape=(16, 3)), # pose 101 | )) for _ in self._hand_models]) 102 | 103 | def show_window(self, show=True): 104 | """Show GUI window or not. 105 | 106 | Keyword Arguments: 107 | show {bool} -- show flag (default: {True}) 108 | """ 109 | self._show_window = show 110 | 111 | def reset(self, initial_hands_state=None, **_kwargs): 112 | """Resets the environment to an initial state and returns an initial observation. 113 | 114 | Keyword Arguments: 115 | initial_hands_state {int} -- override the initial hands state (default: {None}) 116 | 117 | Returns: 118 | observation (object): the initial observation. 119 | """ 120 | if self._client is None: 121 | self._client = BulletClient(pb.GUI if self._show_window else pb.DIRECT) 122 | self._client.configureDebugVisualizer(pb.COV_ENABLE_GUI, 0) 123 | self._setup_camera() 124 | 125 | self._client.resetSimulation() 126 | self._client.setAdditionalSearchPath(pd.getDataPath()) 127 | self._client.setPhysicsEngineParameter(deterministicOverlappingPairs=1) 128 | self._client.setGravity(0, 0, -10) 129 | self._client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 0) 130 | 131 | # randomize the handshape if needed 132 | betas = None 133 | if self._randomize_hand_shape: 134 | betas = self._random.rand(10) * self.SHAPE_BETAS_MAGNITUDE 135 | 136 | # spawn the hands 137 | self._hand_bodies = [] 138 | for i, model in enumerate(self._hand_models): 139 | hand_body = HandBody(self._client, model, shape_betas=betas) 140 | 141 | if initial_hands_state is not None: 142 | pos, orn, angles = initial_hands_state[i] 143 | else: 144 | pos_y, orn_z = (0.10, 0.0) if model.is_left_hand else (-0.10, -np.pi) 145 | pos, orn = (0.0, pos_y, 0.25), pb.getQuaternionFromEuler((np.pi/2, 0.0, orn_z)) 146 | angles = np.zeros(len(hand_body.joint_indices)) 147 | 148 | hand_body.reset(pos, orn, angles) 149 | hand_body.set_target(pos, orn, angles) 150 | self._hand_bodies.append(hand_body) 151 | 152 | self._client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) 153 | return self._get_observation() 154 | 155 | def step(self, action): 156 | """Run one timestep of the environment's dynamics. 157 | 158 | Args: 159 | action (object): an action provided by the agent 160 | 161 | Returns: 162 | observation (object): agent's observation of the current environment 163 | reward (float) : amount of reward returned after previous action 164 | done (bool): whether the episode has ended 165 | info (dict): contains auxiliary diagnostic information 166 | """ 167 | self._take_action(action) 168 | 169 | num_steps = int(self.metadata.get('step_time') * 240.0) 170 | for _ in range(num_steps): 171 | self._client.stepSimulation() 172 | 173 | observation = self._get_observation() 174 | reward = self._get_reward(observation) 175 | done = self._is_done(observation) 176 | info = {} 177 | return observation, reward, done, info 178 | 179 | def render(self, mode='human'): 180 | """Renders the environment. 181 | 182 | Args: 183 | mode (str): the mode to render with 184 | """ 185 | if mode == 'rgb_array': 186 | data = pb.getCameraImage(*self._camera_shape, self._camera_view, self._camera_proj) 187 | rgba = data[2] 188 | return rgba[:, :, :3] 189 | return super().render(mode=mode) 190 | 191 | def close(self): 192 | """Perform necessary cleanup. 193 | 194 | Environments will automatically close() themselves when 195 | garbage collected or when the program exits. 196 | """ 197 | if self._client.isConnected(): 198 | self._client.disconnect() 199 | 200 | def seed(self, seed=None): 201 | """Sets the seed for this env's random number generator(s). 202 | 203 | Args: 204 | seed (int): provided number generators seed 205 | """ 206 | self._random = RandomState(seed) 207 | return [seed] 208 | 209 | def _take_action(self, action): 210 | """Compute observation of the current environment. 211 | 212 | Args: 213 | action (object): an action provided by the agent 214 | """ 215 | if self.MODE_JOINT == self._control_mode: 216 | for hand, (pos, orn, angles) in zip(self._hand_bodies, action): 217 | hand.set_target(pos, orn, angles) 218 | elif self.MODE_MANO == self._control_mode: 219 | for hand, (trans, pose) in zip(self._hand_bodies, action): 220 | hand.set_target_from_mano(trans, pose) 221 | 222 | def _get_observation(self): 223 | """Compute observation of the current environment. 224 | 225 | Returns: 226 | observation (object): agent's observation of the current environment 227 | """ 228 | if self.MODE_JOINT == self._control_mode: 229 | return [hand.get_state() for hand in self._hand_bodies] 230 | if self.MODE_MANO == self._control_mode: 231 | return [hand.get_mano_state() for hand in self._hand_bodies] 232 | return None 233 | 234 | def _get_reward(self, observation): 235 | """Compute reward at the current environment state. 236 | 237 | Returns: 238 | observation (object): agent's observation of the current environment 239 | """ 240 | # pylint: disable=no-self-use, unused-argument 241 | return 0.0 242 | 243 | def _is_done(self, observation): 244 | """Check if the current environment state is final. 245 | 246 | Returns: 247 | observation (object): agent's observation of the current environment 248 | """ 249 | # pylint: disable=no-self-use, unused-argument 250 | return False 251 | 252 | def _setup_camera(self): 253 | """Setup virtual camera.""" 254 | self._client.resetDebugVisualizerCamera( 255 | cameraDistance=0.5, 256 | cameraYaw=-45.0, 257 | cameraPitch=-40.0, 258 | cameraTargetPosition=[0, 0, 0.1]) 259 | 260 | self._camera_view = self._client.computeViewMatrixFromYawPitchRoll( 261 | cameraTargetPosition=[0.0, 0.0, 0.1], 262 | distance=0.5, 263 | yaw=-45.0, 264 | pitch=-40.0, 265 | roll=0.0, 266 | upAxisIndex=2) 267 | 268 | self._camera_proj = self._client.computeProjectionMatrixFOV( 269 | fov=60.0, 270 | aspect=self._camera_shape[0] / self._camera_shape[1], 271 | nearVal=0.1, 272 | farVal=10.0) 273 | 274 | 275 | if __name__ == '__main__': 276 | import time 277 | 278 | env = HandEnv(HandEnv.HAND_BOTH) 279 | env.show_window() 280 | env.seed(0) 281 | env.reset() 282 | 283 | while pb.isConnected(): 284 | time.sleep(0.1) 285 | -------------------------------------------------------------------------------- /mano_pybullet/envs/hand_lift_env.py: -------------------------------------------------------------------------------- 1 | """Lift an object environment.""" 2 | 3 | from .hand_object_env import HandObjectEnv 4 | 5 | __all__ = ('HandLiftEnv') 6 | 7 | 8 | class HandLiftEnv(HandObjectEnv): 9 | """Lift an object environment class. """ 10 | 11 | def __init__(self, target_height=0.25, **kwargs): 12 | """Constructor of a HandLiftEnv. 13 | 14 | Keyword Arguments: 15 | target_height {float} -- target lift height (default: {0.25}) 16 | """ 17 | super().__init__(self, **kwargs) 18 | self._target_height = target_height 19 | 20 | def reset(self, **kwargs): 21 | """Resets the environment to an initial state and returns an initial observation. 22 | 23 | Returns: 24 | observation (object): the initial observation. 25 | """ 26 | # pylint: disable=arguments-differ 27 | observation = super().reset(**kwargs) 28 | 29 | # debug target marker 30 | self._client.addUserDebugLine( 31 | (0.1, 0.1, self._target_height), 32 | (-0.1, -0.1, self._target_height), 33 | (1.0, 0.0, 0.0), 2) 34 | self._client.addUserDebugLine( 35 | (0.1, -0.1, self._target_height), 36 | (-0.1, 0.1, self._target_height), 37 | (1.0, 0.0, 0.0), 4) 38 | 39 | return observation 40 | 41 | def _get_reward(self, observation): 42 | """Compute reward at the current environment state. 43 | 44 | Returns: 45 | observation (object): agent's observation of the current environment 46 | """ 47 | _hands_state, (object_pos, _object_orn) = observation 48 | return object_pos[2] 49 | 50 | def _is_done(self, observation): 51 | """Check if the current environment state is final. 52 | 53 | Returns: 54 | observation (object): agent's observation of the current environment 55 | """ 56 | _hands_state, (object_pos, _object_orn) = observation 57 | return object_pos[2] > self._target_height 58 | 59 | 60 | if __name__ == '__main__': 61 | from .wrappers.json_player import JSONPlayer 62 | 63 | env = HandLiftEnv() 64 | env.show_window(True) 65 | env = JSONPlayer(env, './data/lift_duck.json') 66 | env.reset() 67 | while True: 68 | _observation, _reward, done, _info = env.step() 69 | if done: 70 | break 71 | -------------------------------------------------------------------------------- /mano_pybullet/envs/hand_object_env.py: -------------------------------------------------------------------------------- 1 | """Base Hand with an Object Environment.""" 2 | 3 | import os 4 | 5 | import gym 6 | import numpy as np 7 | import pybullet as pb 8 | 9 | from .hand_env import HandEnv 10 | 11 | __all__ = ('HandObjectEnv') 12 | 13 | 14 | class HandObjectEnv(HandEnv): 15 | """The base Hand with Object Environment class. """ 16 | 17 | def __init__(self, model_path=None, up_axis='z', make_convex=True, **kwargs): 18 | """Constructor a HandObjectEnv. 19 | 20 | Keyword Arguments: 21 | model_path {str|list} -- path to an object model file(s) (default: {None}) 22 | up_axis {str} -- object up axis (default: {'z'}) 23 | make_convex {bool} -- generate a convex collision mesh (default: {True}) 24 | """ 25 | super().__init__(**kwargs) 26 | self._model_path = model_path 27 | self._up_axis = up_axis 28 | self._make_convex = make_convex 29 | self._body_id = -1 30 | self._table_id = -1 31 | 32 | self.observation_space = gym.spaces.Tuple(( 33 | self.observation_space, 34 | gym.spaces.Tuple(( 35 | gym.spaces.Box(-5.0, 5.0, shape=(3,)), # object's base position 36 | gym.spaces.Box(-1.0, 1.0, shape=(4,)), # object's base quaternion 37 | )))) 38 | 39 | def reset(self, model_path=None, up_axis=None, **kwargs): 40 | """Resets the environment to an initial state and returns an initial observation. 41 | 42 | Returns: 43 | observation (object): the initial observation. 44 | 45 | Keyword Arguments: 46 | model_path {str|list} -- override the path to an object model file (default: {None}) 47 | up_axis {str} -- override the object up axis (default: {None}) 48 | """ 49 | up_axis = up_axis or self._up_axis 50 | model_path = model_path or self._model_path 51 | self._body_id = -1 52 | 53 | super().reset(**kwargs) 54 | self._client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 0) 55 | 56 | # spawn the ground plane 57 | shape_id = self._client.createCollisionShape(pb.GEOM_PLANE) 58 | self._table_id = self._client.createMultiBody(0.0, shape_id) 59 | 60 | # spawn the object 61 | if isinstance(model_path, (list, tuple)): 62 | model_path = self._random.choice(model_path) 63 | self._body_id = self._load_model(model_path) 64 | self._client.changeDynamics( 65 | self._body_id, -1, linearDamping=0.5, angularDamping=0.5) 66 | 67 | # put the object onto the ground plane 68 | orig, _ = self._client.getBasePositionAndOrientation(self._body_id) 69 | bmin, _ = self._client.getAABB(self._body_id, -1) 70 | if up_axis == 'x': 71 | pose = (0.0, 0.0, orig[0]-bmin[0]), pb.getQuaternionFromEuler((0.0, np.pi/2, 0.0)) 72 | elif up_axis == 'y': 73 | pose = (0.0, 0.0, orig[1]-bmin[1]), pb.getQuaternionFromEuler((np.pi/2, 0.0, 0.0)) 74 | elif up_axis == 'z': 75 | pose = (0.0, 0.0, orig[2]-bmin[2]), (0.0, 0.0, 0.0, 1.0) 76 | self._client.resetBasePositionAndOrientation(self._body_id, *pose) 77 | 78 | self._client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) 79 | return self._get_observation() 80 | 81 | def _load_model(self, path): 82 | """Load model from file. 83 | 84 | Arguments: 85 | path {str} -- path to an object model file 86 | """ 87 | path = os.path.expandvars(path) 88 | root, ext = os.path.splitext(path) 89 | if ext.lower() == '.urdf': 90 | return self._client.loadURDF(path) 91 | if ext.lower() == '.obj': 92 | vid = self._client.createVisualShape(pb.GEOM_MESH, fileName=path) 93 | if self._make_convex: 94 | # generate the convex decomposed mesh and save it on disk 95 | in_path = path 96 | path = root + '_vhacd' + ext 97 | if not os.path.exists(path): 98 | self._client.vhacd(in_path, path, '') 99 | cid = self._client.createCollisionShape(pb.GEOM_MESH, fileName=path) 100 | return self._client.createMultiBody(0.2, cid, vid) 101 | raise RuntimeError(f'Cannot load model from: "{path}"') 102 | 103 | def _get_observation(self): 104 | """Compute observation of the current environment. 105 | 106 | Returns: 107 | observation (object): agent's observation of the current environment 108 | """ 109 | if self._body_id >= 0: 110 | hands_observation = super()._get_observation() 111 | base_pos, base_orn = self._client.getBasePositionAndOrientation(self._body_id) 112 | return hands_observation, (base_pos, base_orn) 113 | return None 114 | 115 | 116 | if __name__ == '__main__': 117 | import time 118 | 119 | env = HandObjectEnv() 120 | env.show_window() 121 | env.reset(model_path='duck_vhacd.urdf', up_axis='y') 122 | 123 | while pb.isConnected(): 124 | time.sleep(0.1) 125 | -------------------------------------------------------------------------------- /mano_pybullet/envs/hand_push_env.py: -------------------------------------------------------------------------------- 1 | """Push an object environment.""" 2 | 3 | from .hand_object_env import HandObjectEnv 4 | 5 | __all__ = ('HandPushEnv') 6 | 7 | 8 | class HandPushEnv(HandObjectEnv): 9 | """Push an object environment class.""" 10 | 11 | def __init__(self, target_distance=0.2, **kwargs): 12 | """Constructor of a HandObjectEnv. 13 | 14 | Keyword Arguments: 15 | target_distance {float} -- distance to the target (default: {0.2}) 16 | """ 17 | super().__init__(self, **kwargs) 18 | self._target_distance = target_distance 19 | 20 | def reset(self, **kwargs): 21 | """Resets the environment to an initial state and returns an initial observation. 22 | 23 | Returns: 24 | observation (object): the initial observation. 25 | """ 26 | observation = super().reset(**kwargs) 27 | 28 | # decrease the ground plane friction 29 | self._client.changeDynamics( 30 | self._table_id, -1, lateralFriction=0.04, spinningFriction=0.04) 31 | 32 | # debug target marker 33 | self._client.addUserDebugLine( 34 | (self._target_distance, -0.1, 0.0), 35 | (self._target_distance, 0.1, 0.0), 36 | (1.0, 0.0, 0.0), 4) 37 | 38 | return observation 39 | 40 | def _get_reward(self, observation): 41 | """Compute reward at the current environment state. 42 | 43 | Returns: 44 | observation (object): agent's observation of the current environment 45 | """ 46 | _hands_state, (object_pos, _object_orn) = observation 47 | return object_pos[0] 48 | 49 | def _is_done(self, observation): 50 | """Check if the current environment state is final. 51 | 52 | Returns: 53 | observation (object): agent's observation of the current environment 54 | """ 55 | _hands_state, (object_pos, _object_orn) = observation 56 | return object_pos[0] > self._target_distance 57 | 58 | 59 | if __name__ == '__main__': 60 | from .wrappers.json_player import JSONPlayer 61 | 62 | env = HandPushEnv() 63 | env.show_window(True) 64 | env = JSONPlayer(env, './data/push_teddy.json') 65 | env.reset() 66 | while True: 67 | _observation, _reward, done, _info = env.step() 68 | if done: 69 | break 70 | -------------------------------------------------------------------------------- /mano_pybullet/envs/wrappers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/mano_pybullet/envs/wrappers/__init__.py -------------------------------------------------------------------------------- /mano_pybullet/envs/wrappers/gif_recorder.py: -------------------------------------------------------------------------------- 1 | """Animated GIF recorder.""" 2 | 3 | try: 4 | import imageio 5 | except ModuleNotFoundError as module_not_found: 6 | raise RuntimeError( 7 | 'Package not found: imageio. Use `pip install imageio` to install.') from module_not_found 8 | 9 | import gym 10 | 11 | __all__ = ('GIFRecorder') 12 | 13 | 14 | class GIFRecorder(gym.Wrapper): 15 | """Animated GIF recorder.""" 16 | 17 | def __init__(self, env, filename_template, use_seed=False): 18 | """Constructor for a AnimRecorder. 19 | 20 | Arguments: 21 | env {gym.Env} -- environment to wrap 22 | filename_template {str} -- GIF filename template (like 'record_{:04d}.gif'). 23 | 24 | Keyword Arguments: 25 | use_seed {bool} -- use seed as file id (substitute in the template) (default: {False}). 26 | """ 27 | super().__init__(env) 28 | self.env.unwrapped.show_window(False) 29 | self._filename_template = filename_template 30 | self._use_seed = use_seed 31 | 32 | input_fps = self.env.unwrapped.metadata.get('video.frames_per_second', 30.0) 33 | output_fps = self.env.unwrapped.metadata.get('video.output_frames_per_second', 30.0) 34 | self._frames_per_second = output_fps 35 | self._steps_per_frame = max(1, input_fps // output_fps) 36 | 37 | self._reset_counter = 0 38 | self._step_counter = 0 39 | self._writer = None 40 | 41 | def reset(self, **kwargs): 42 | """Resets the environment to an initial state. 43 | 44 | Open a GIF file writer. 45 | """ 46 | if self._writer is not None: 47 | self._writer.close() 48 | 49 | uid = self._seed if self._use_seed else self._reset_counter 50 | filename = self._filename_template.format(uid) 51 | self._writer = imageio.get_writer(filename, mode='I', fps=self._frames_per_second) 52 | 53 | self._reset_counter += 1 54 | self._step_counter = 0 55 | return self.env.reset(**kwargs) 56 | 57 | def step(self, action): 58 | """Run one timestep of the environment's dynamics. 59 | 60 | Render an image and write it to the file. 61 | """ 62 | if self._step_counter % self._steps_per_frame == 0: 63 | image_rgb = self.env.render('rgb_array') 64 | self._writer.append_data(image_rgb) 65 | self._step_counter += 1 66 | return self.env.step(action) 67 | 68 | def close(self): 69 | """Close the environment. 70 | 71 | Flush recorded data to file. 72 | """ 73 | if self._writer is not None: 74 | self._writer.close() 75 | return self.env.close() 76 | -------------------------------------------------------------------------------- /mano_pybullet/envs/wrappers/json_player.py: -------------------------------------------------------------------------------- 1 | """Dataset playing helper wrapper.""" 2 | 3 | import glob 4 | import json 5 | import os 6 | 7 | import gym 8 | 9 | __all__ = ('JSONPlayer') 10 | 11 | 12 | class JSONPlayer(gym.Wrapper): 13 | """Wraps the environment to allow play actions from file.""" 14 | 15 | def __init__(self, env, path): 16 | """Constructor for a Player. 17 | 18 | Arguments: 19 | env {gym.Env} -- environment to wrap. 20 | path {str} -- path to the recorded JSON file or to the directory with files. 21 | """ 22 | super().__init__(env) 23 | if os.path.isdir(path): 24 | self._filenames = list(glob.glob(os.path.join(path, '*.json'))) 25 | else: 26 | self._filenames = [path] 27 | self._action_iter = None 28 | self._counter = 0 29 | 30 | @property 31 | def records(self): 32 | """Number of records in the dataset. 33 | 34 | Returns: 35 | int -- files count in the dataset 36 | """ 37 | return len(self._filenames) 38 | 39 | def reset(self, **kwargs_override): 40 | """Resets the environment to an initial state. 41 | 42 | Load recorded data from file, apply recorded arguments and seed. 43 | """ 44 | seed, kwargs = self._load() 45 | if seed is not None: 46 | self.seed(seed) 47 | kwargs.update(kwargs_override) 48 | return self.env.reset(**kwargs) 49 | 50 | def step(self, action=None): 51 | """Run one timestep of the environment's dynamics. 52 | 53 | Load action from file. 54 | """ 55 | action = next(self._action_iter, None) 56 | if action is None: 57 | raise RuntimeError('Environment was not completed during playback.') 58 | return self.env.step(action) 59 | 60 | def _load(self): 61 | filename = self._filenames[self._counter] 62 | with open(filename, 'r') as json_file: 63 | data = json.load(json_file) 64 | self._action_iter = iter(self.env.action_space.from_jsonable(data.get('actions'))) 65 | self._counter += 1 66 | return data.get('seed'), data.get('kwargs') 67 | -------------------------------------------------------------------------------- /mano_pybullet/envs/wrappers/json_recorder.py: -------------------------------------------------------------------------------- 1 | """Dataset recording helper wrapper.""" 2 | 3 | import json 4 | 5 | import gym 6 | import numpy as np 7 | 8 | __all__ = ('JSONRecorder') 9 | 10 | 11 | class JSONRecorder(gym.Wrapper): 12 | """Wraps the environment to allow recording actions and observations to file.""" 13 | 14 | def __init__(self, env, filename_template, use_seed=False): 15 | """Constructor for a Recorder. 16 | 17 | Arguments: 18 | env {gym.Env} -- environment to wrap. 19 | filename_template {str} -- JSON filename template (like 'record_{:04d}.json'). 20 | 21 | Keyword Arguments: 22 | use_seed {bool} -- use seed as file id (substitute in the template) (default: {False}). 23 | """ 24 | super().__init__(env) 25 | self._filename_template = filename_template 26 | self._use_seed = use_seed 27 | self._seed = None 28 | self._kwargs = {} 29 | self._observations = [] 30 | self._actions = [] 31 | self._counter = 0 32 | 33 | def reset(self, **kwargs): 34 | """Resets the environment to an initial state. 35 | 36 | Dump recorded data to file, cleanup records, save reset arguments. 37 | """ 38 | if self._observations: 39 | self._dump() 40 | self._kwargs = kwargs 41 | observation = self.env.reset(**kwargs) 42 | self._observations.append(observation) 43 | return observation 44 | 45 | def step(self, action): 46 | """Run one timestep of the environment's dynamics. 47 | 48 | Record an action and observation. 49 | """ 50 | self._actions.append(action) 51 | observation, reward, done, info = self.env.step(action) 52 | self._observations.append(observation) 53 | return observation, reward, done, info 54 | 55 | def close(self): 56 | """Close the environment. 57 | 58 | Dump recorded data to file. 59 | """ 60 | if self._observations: 61 | self._dump() 62 | return self.env.close() 63 | 64 | def seed(self, seed=None): 65 | """Sets the seed for this env's random number generator(s). 66 | 67 | Record the seed value. 68 | """ 69 | self._seed = seed 70 | return self.env.seed(seed) 71 | 72 | def _dump(self): 73 | uid = self._seed if self._use_seed else self._counter 74 | filename = self._filename_template.format(uid) 75 | data = dict( 76 | version=1.0, 77 | kwargs=self._kwargs, 78 | seed=self._seed, 79 | observations=self.env.observation_space.to_jsonable(self._observations), 80 | actions=self.env.action_space.to_jsonable(self._actions), 81 | ) 82 | with open(filename, 'w') as json_file: 83 | json.dump(data, json_file, cls=_SafeJSONEncoder) 84 | self._counter += 1 85 | self._observations = [] 86 | self._actions = [] 87 | 88 | 89 | class _SafeJSONEncoder(json.JSONEncoder): 90 | def default(self, obj): 91 | if isinstance(obj, np.ndarray): 92 | return obj.tolist() 93 | return json.JSONEncoder.default(self, obj) 94 | -------------------------------------------------------------------------------- /mano_pybullet/hand_body.py: -------------------------------------------------------------------------------- 1 | """Rigid hand body.""" 2 | import contextlib 3 | import tempfile 4 | 5 | import numpy as np 6 | import pybullet as pb 7 | 8 | from .math_utils import mat2pb, pb2mat 9 | from .mesh_utils import filter_mesh, save_mesh_obj 10 | 11 | __all__ = ('HandBody') 12 | 13 | 14 | class HandBody: 15 | """Rigid multi-link hand body.""" 16 | 17 | FLAG_STATIC = 1 # create static (fixed) body 18 | FLAG_ENABLE_COLLISION_SHAPES = 2 # enable colllision shapes 19 | FLAG_ENABLE_VISUAL_SHAPES = 4 # enable visual shapes 20 | FLAG_JOINT_LIMITS = 8 # apply joint limits 21 | FLAG_DYNAMICS = 16 # overide default dynamics parameters 22 | FLAG_USE_SELF_COLLISION = 32 # enable self collision 23 | FLAG_DEFAULT = sum([FLAG_ENABLE_COLLISION_SHAPES, 24 | FLAG_ENABLE_VISUAL_SHAPES, 25 | FLAG_JOINT_LIMITS, 26 | FLAG_DYNAMICS, 27 | FLAG_USE_SELF_COLLISION]) 28 | 29 | def __init__(self, client, hand_model, flags=FLAG_DEFAULT, shape_betas=None): 30 | """HandBody constructor. 31 | 32 | Arguments: 33 | client {PybulletClient} -- pybullet client 34 | hand_model {HandModel} -- rigid hand model 35 | 36 | Keyword Arguments: 37 | flags {int} -- configuration flags (default: {FLAG_DEFAULT}) 38 | color {list} -- color RGBA (default: {None}) 39 | shape_betas {array} -- MANO shape beta parameters (default: {None}) 40 | """ 41 | self._client = client 42 | self._model = hand_model 43 | self._flags = flags 44 | self._vertices = hand_model.vertices(betas=shape_betas) 45 | self._origin = self._model.origins()[0] 46 | self._joint_indices = [] 47 | self._joint_limits = [] 48 | self._link_mapping = {} 49 | self._body_id = self._make_body() 50 | self._constraint_id = self._make_constraint() 51 | self._apply_joint_limits() 52 | self._apply_dynamics() 53 | 54 | @ property 55 | def body_id(self): 56 | """Body unique id in the simulator. 57 | 58 | Returns: 59 | int -- body unique id in PyBullet 60 | """ 61 | return self._body_id 62 | 63 | @ property 64 | def joint_indices(self): 65 | """Articulated joint indices. 66 | 67 | Returns: 68 | list -- list of joint indices 69 | """ 70 | return self._joint_indices 71 | 72 | @ property 73 | def joint_limits(self): 74 | """Articulated joints angle bounds. 75 | 76 | Returns: 77 | list -- list of tuples (lower limit, upper limit) 78 | """ 79 | return self._joint_limits 80 | 81 | def get_state(self): 82 | """Get current hand state. 83 | 84 | Returns: 85 | tuple -- base position, orientation, forces, joint positions, velocities, torques 86 | """ 87 | base_pos, base_orn = self._client.getBasePositionAndOrientation(self._body_id) 88 | if self._constraint_id != -1: 89 | constraint_forces = self._client.getConstraintState(self._constraint_id) 90 | else: 91 | constraint_forces = [0.0] * 6 92 | joint_states = self._client.getJointStates(self._body_id, self._joint_indices) 93 | joints_pos, joints_vel, _, joints_torque = zip(*joint_states) 94 | return base_pos, base_orn, constraint_forces, joints_pos, joints_vel, joints_torque 95 | 96 | def reset(self, position, orientation, joint_angles=None): 97 | """Reset base pose and joint angles. 98 | 99 | Arguments: 100 | position {vec3} -- position 101 | orientation {vec4} -- quaternion x,y,z,w 102 | 103 | Keyword Arguments: 104 | joint_angles {list} -- new angles for all articulated joints (default: {None}) 105 | """ 106 | self._client.resetBasePositionAndOrientation(self._body_id, position, orientation) 107 | if joint_angles is not None: 108 | for i, angle in zip(self._joint_indices, joint_angles): 109 | self._client.resetJointState(self._body_id, i, angle) 110 | 111 | def set_target(self, position, orientation, joint_angles=None): 112 | """Set target base pose and joint angles. 113 | 114 | Arguments: 115 | position {vec3} -- position 116 | orientation {vec4} -- quaternion x,y,z,w 117 | 118 | Keyword Arguments: 119 | joint_angles {list} -- new angles for all articulated joints (default: {None}) 120 | """ 121 | if self._constraint_id != -1: 122 | self._client.changeConstraint( 123 | self._constraint_id, 124 | jointChildPivot=position, 125 | jointChildFrameOrientation=orientation, 126 | maxForce=10.0) 127 | if joint_angles is not None: 128 | self._client.setJointMotorControlArray( 129 | bodyUniqueId=self._body_id, 130 | jointIndices=self._joint_indices, 131 | controlMode=pb.POSITION_CONTROL, 132 | targetPositions=joint_angles, 133 | forces=[0.5]*len(joint_angles)) 134 | 135 | def get_mano_state(self): 136 | """Get current hand state as a MANO model state. 137 | 138 | Returns: 139 | tuple -- trans, pose 140 | """ 141 | base_pos, base_orn, _, angles, _, _ = self.get_state() 142 | basis = pb2mat(base_orn) 143 | trans = base_pos - self._origin + basis @ self._origin 144 | mano_pose = self._model.angles_to_mano(angles, basis) 145 | return trans, mano_pose 146 | 147 | def reset_from_mano(self, trans, mano_pose): 148 | """Reset hand state from a Mano pose. 149 | 150 | Arguments: 151 | mano_pose {array} -- pose of the Mano model 152 | trans {vec3} -- hand translation 153 | """ 154 | angles, basis = self._model.mano_to_angles(mano_pose) 155 | trans = trans + self._origin - basis @ self._origin 156 | self.reset(trans, mat2pb(basis), angles) 157 | 158 | def set_target_from_mano(self, trans, mano_pose): 159 | """Set target hand state from a Mano pose. 160 | 161 | Arguments: 162 | mano_pose {array} -- pose of the Mano model 163 | trans {vec3} -- hand translation 164 | """ 165 | angles, basis = self._model.mano_to_angles(mano_pose) 166 | trans = trans + self._origin - basis @ self._origin 167 | self.set_target(trans, mat2pb(basis), angles) 168 | 169 | def _make_body(self): 170 | joints = self._model.joints 171 | link_masses = [0.2] 172 | link_collision_indices = [self._make_collision_shape(0, joints[0].basis.T)] 173 | link_visual_indices = [self._make_visual_shape(0, joints[0].basis.T)] 174 | link_positions = [joints[0].origin] 175 | link_orientations = [mat2pb(joints[0].basis)] 176 | link_parent_indices = [0] 177 | link_joint_types = [pb.JOINT_FIXED] 178 | link_joint_axis = [[0.0, 0.0, 0.0]] 179 | self._link_mapping[0] = 0 180 | 181 | for i, j in self._model.kintree_table.T[1:]: 182 | parent_index = self._link_mapping[i] 183 | origin_rel = joints[i].basis.T @ (joints[j].origin - joints[i].origin) 184 | basis_rel = joints[i].basis.T @ joints[j].basis 185 | 186 | for axis, limits in zip(joints[j].axes, joints[j].limits): 187 | link_masses.append(0.0) 188 | link_collision_indices.append(-1) 189 | link_visual_indices.append(-1) 190 | link_positions.append(origin_rel) 191 | link_orientations.append(mat2pb(basis_rel)) 192 | link_parent_indices.append(parent_index+1) 193 | link_joint_types.append(pb.JOINT_REVOLUTE) 194 | link_joint_axis.append(np.eye(3)[ord(axis) - ord('x')]) 195 | origin_rel, basis_rel = [0.0, 0.0, 0.0], np.eye(3) 196 | parent_index = len(link_masses) - 1 197 | self._link_mapping[j] = parent_index 198 | self._joint_indices.append(parent_index) 199 | self._joint_limits.append(limits) 200 | 201 | link_masses[-1] = 0.02 202 | link_visual_indices[-1] = self._make_visual_shape(j, joints[j].basis.T) 203 | link_collision_indices[-1] = self._make_collision_shape(j, joints[j].basis.T) 204 | 205 | flags = pb.URDF_INITIALIZE_SAT_FEATURES 206 | if self.FLAG_USE_SELF_COLLISION & self._flags: 207 | flags |= pb.URDF_USE_SELF_COLLISION 208 | flags |= pb.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS 209 | 210 | base_mass = 0.01 211 | if self.FLAG_STATIC & self._flags: 212 | base_mass = 0.0 213 | 214 | return self._client.createMultiBody( 215 | baseMass=base_mass, 216 | baseCollisionShapeIndex=-1, 217 | baseVisualShapeIndex=-1, 218 | basePosition=[0.0, 0.0, 0.0], 219 | baseOrientation=[0.0, 0.0, 0.0, 1.0], 220 | linkMasses=link_masses, 221 | linkCollisionShapeIndices=link_collision_indices, 222 | linkVisualShapeIndices=link_visual_indices, 223 | linkPositions=link_positions, 224 | linkOrientations=link_orientations, 225 | linkInertialFramePositions=[[0.0, 0.0, 0.0]] * len(link_masses), 226 | linkInertialFrameOrientations=[[0.0, 0.0, 0.0, 1.0]] * len(link_masses), 227 | linkParentIndices=link_parent_indices, 228 | linkJointTypes=link_joint_types, 229 | linkJointAxis=link_joint_axis, 230 | flags=flags) 231 | 232 | def _make_collision_shape(self, link_index, basis): 233 | if self.FLAG_ENABLE_COLLISION_SHAPES & self._flags: 234 | with self._temp_link_mesh(link_index, True) as filename: 235 | return self._client.createCollisionShape( 236 | pb.GEOM_MESH, 237 | fileName=filename, 238 | meshScale=[1.0, 1.0, 1.0], 239 | collisionFramePosition=[0, 0, 0], 240 | collisionFrameOrientation=mat2pb(basis)) 241 | return -1 242 | 243 | def _make_visual_shape(self, link_index, basis): 244 | if self.FLAG_ENABLE_VISUAL_SHAPES & self._flags: 245 | with self._temp_link_mesh(link_index, False) as filename: 246 | return self._client.createVisualShape( 247 | pb.GEOM_MESH, 248 | fileName=filename, 249 | meshScale=[1.0, 1.0, 1.0], 250 | rgbaColor=[0.0, 1.0, 0.0, 1.0], 251 | specularColor=[1.0, 1.0, 1.0], 252 | visualFramePosition=[0.0, 0.0, 0.0], 253 | visualFrameOrientation=mat2pb(basis)) 254 | return -1 255 | 256 | def _make_constraint(self): 257 | if not self.FLAG_STATIC & self._flags: 258 | return self._client.createConstraint( 259 | parentBodyUniqueId=self._body_id, 260 | parentLinkIndex=-1, 261 | childBodyUniqueId=-1, 262 | childLinkIndex=-1, 263 | jointType=pb.JOINT_FIXED, 264 | jointAxis=[0.0, 0.0, 0.0], 265 | parentFramePosition=[0.0, 0.0, 0.0], 266 | childFramePosition=[0.0, 0.0, 0.0]) 267 | return -1 268 | 269 | def _apply_joint_limits(self): 270 | if self.FLAG_JOINT_LIMITS & self._flags: 271 | for i, limits in zip(self._joint_indices, self._joint_limits): 272 | self._client.changeDynamics( 273 | bodyUniqueId=self._body_id, 274 | linkIndex=i, 275 | jointLowerLimit=limits[0], 276 | jointUpperLimit=limits[1]) 277 | 278 | def _apply_dynamics(self): 279 | if self.FLAG_DYNAMICS & self._flags: 280 | self._client.changeDynamics( 281 | bodyUniqueId=self._body_id, 282 | linkIndex=-1, 283 | linearDamping=10.0, 284 | angularDamping=10.0) 285 | 286 | for i in [0] + self._joint_indices: 287 | self._client.changeDynamics( 288 | bodyUniqueId=self._body_id, 289 | linkIndex=i, 290 | restitution=0.5, 291 | lateralFriction=5.0, 292 | spinningFriction=5.0) 293 | 294 | @contextlib.contextmanager 295 | def _temp_link_mesh(self, link_index, collision): 296 | with tempfile.NamedTemporaryFile('w', suffix='.obj') as temp_file: 297 | threshold = 0.2 298 | if collision and link_index in [4, 7, 10]: 299 | threshold = 0.7 300 | vertex_mask = self._model.weights[:, link_index] > threshold 301 | vertices, faces = filter_mesh(self._vertices, self._model.faces, vertex_mask) 302 | vertices -= self._model.joints[link_index].origin 303 | save_mesh_obj(temp_file.name, vertices, faces) 304 | yield temp_file.name 305 | -------------------------------------------------------------------------------- /mano_pybullet/hand_model.py: -------------------------------------------------------------------------------- 1 | """Hand models.""" 2 | 3 | import collections 4 | 5 | import numpy as np 6 | 7 | from .mano_model import ManoModel 8 | from .math_utils import joint2mat, mat2joint, mat2rvec, rvec2mat 9 | 10 | __all__ = ('HandModel', 'HandModel20', 'HandModel45') 11 | 12 | Joint = collections.namedtuple('Joint', ['origin', 'basis', 'axes', 'limits']) 13 | 14 | 15 | class HandModel(ManoModel): 16 | """Base rigid hand model. 17 | 18 | The model provides rigid hand kinematics description and math_utils 19 | from the joint space to the MANO model pose. 20 | """ 21 | 22 | def __init__(self, left_hand=False, models_dir=None): 23 | """Initialize a HandModel. 24 | 25 | Keyword Arguments: 26 | left_hand {bool} -- create a left hand model (default: {False}) 27 | models_dir {str} -- path to the pickled model files (default: {None}) 28 | """ 29 | super().__init__(left_hand=left_hand, models_dir=models_dir) 30 | self._joints = self._make_joints() 31 | self._basis = [joint.basis for joint in self._joints] 32 | self._axes = [joint.axes for joint in self._joints] 33 | self._dofs = [(u-len(self._axes[i]), u) 34 | for i, u in enumerate(np.cumsum([len(joint.axes) for joint in self._joints]))] 35 | 36 | assert len(self._joints) == len(self.origins()), 'Wrong joints number' 37 | assert all([len(j.axes) == len(j.limits) for j in self._joints]), 'Wrong limits number' 38 | assert not self._joints[0].axes, 'Palm joint is not fixed' 39 | 40 | @property 41 | def joints(self): 42 | """Joint descriptions. 43 | 44 | Returns: 45 | list -- list of Joint structures 46 | """ 47 | return self._joints 48 | 49 | @property 50 | def dofs_number(self): 51 | """Number of degrees of freedom. 52 | 53 | Returns: 54 | int -- sum of degrees of freedom of all joints 55 | """ 56 | return sum([len(joint.axes) for joint in self._joints[1:]]) 57 | 58 | @property 59 | def dofs_limits(self): 60 | """Limits corresponding to degrees of freedom. 61 | 62 | Returns: 63 | tuple -- lower limits list, upper limits list 64 | """ 65 | return list(zip(*[limits for joint in self._joints[1:] for limits in joint.limits])) 66 | 67 | def angles_to_mano(self, angles, palm_basis=None): 68 | """Convert joint angles to a MANO pose. 69 | 70 | Arguments: 71 | angles {array} -- rigid model's dofs angles 72 | 73 | Keyword Arguments: 74 | palm_basis {mat3} -- palm basis (default: {None}) 75 | 76 | Returns: 77 | array -- MANO pose, array of size N*3 where N - number of links 78 | """ 79 | if len(angles) != self.dofs_number: 80 | raise ValueError(f'Expected {self.dofs_number} angles (got {len(angles)}).') 81 | 82 | def joint_to_rvec(i, angles): 83 | return mat2rvec(self._basis[i] @ joint2mat(self._axes[i], angles) @ self._basis[i].T) 84 | 85 | rvecs = [joint_to_rvec(i, angles[d0:d1]) for i, (d0, d1) in enumerate(self._dofs)] 86 | if palm_basis is not None: 87 | rvecs[0] = mat2rvec(palm_basis) 88 | return np.ravel(rvecs) 89 | 90 | def mano_to_angles(self, mano_pose): 91 | """Convert a mano pose to joint angles of the rigid model. 92 | 93 | It is not guaranteed that the rigid model can ideally 94 | recover a mano pose. 95 | 96 | Arguments: 97 | mano_pose {array} -- MANO pose, array of size N*3 where N - number of links 98 | 99 | Returns: 100 | tuple -- dofs angles, palm_basis 101 | """ 102 | rvecs = np.asarray(mano_pose).reshape((-1, 3)) 103 | if rvecs.size != 48: 104 | raise ValueError(f'Expected 48 items in the MANO pose (got {rvecs.size}).') 105 | 106 | def rvec_to_joint(i, rvec): 107 | return mat2joint(self._basis[i].T @ rvec2mat(rvec) @ self._basis[i], self._axes[i]) 108 | 109 | angles = [angle for i, rvec in enumerate(rvecs) for angle in rvec_to_joint(i, rvec)] 110 | palm_basis = rvec2mat(rvecs[0]) 111 | return angles, palm_basis 112 | 113 | def _make_joints(self): 114 | """Compute joints parameters. 115 | 116 | Returns: 117 | list -- list of joints parameters 118 | """ 119 | raise NotImplementedError 120 | 121 | 122 | class HandModel20(HandModel): 123 | """Heuristic rigid model with 20 degrees of freedom.""" 124 | 125 | def _make_joints(self): 126 | """Compute joints parameters. 127 | 128 | Returns: 129 | list -- list of joints parameters 130 | """ 131 | origin = dict(zip(self.link_names, self.origins())) 132 | basis = {'palm': np.eye(3)} 133 | 134 | def make_basis(yvec, zvec): 135 | mat = np.vstack([np.cross(yvec, zvec), yvec, zvec]) 136 | return mat.T / np.linalg.norm(mat.T, axis=0) 137 | 138 | zvec = origin['index2'] - origin['index3'] 139 | yvec = np.cross(zvec, [0.0, 0.0, 1.0]) 140 | basis['index'] = make_basis(yvec, zvec) 141 | 142 | zvec = origin['middle2'] - origin['middle3'] 143 | yvec = np.cross(zvec, origin['index1'] - origin['ring1']) 144 | basis['middle'] = make_basis(yvec, zvec) 145 | 146 | zvec = origin['ring2'] - origin['ring3'] 147 | yvec = np.cross(zvec, origin['middle1'] - origin['ring1']) 148 | basis['ring'] = make_basis(yvec, zvec) 149 | 150 | zvec = origin['pinky2'] - origin['pinky3'] 151 | yvec = np.cross(zvec, origin['ring1'] - origin['pinky1']) 152 | basis['pinky'] = make_basis(yvec, zvec) 153 | 154 | yvec = origin['thumb1'] - origin['index1'] 155 | zvec = np.cross(yvec, origin['thumb1'] - origin['thumb2']) 156 | basis['thumb0'] = make_basis(yvec, zvec) 157 | 158 | zvec = origin['thumb2'] - origin['thumb3'] 159 | yvec = np.cross(zvec, [0, -np.sin(0.96), np.cos(0.96)]) 160 | basis['thumb'] = make_basis(yvec, zvec) 161 | 162 | if self.is_left_hand: 163 | rot = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) 164 | basis = {key: mat @ rot for key, mat in basis.items()} 165 | 166 | return [ 167 | Joint(origin['palm'], basis['palm'], '', []), 168 | Joint(origin['index1'], basis['index'], 'yx', np.deg2rad([(-20, 20), (-10, 90)])), 169 | Joint(origin['index2'], basis['index'], 'x', np.deg2rad([(0, 100)])), 170 | Joint(origin['index3'], basis['index'], 'x', np.deg2rad([(0, 100)])), 171 | Joint(origin['middle1'], basis['middle'], 'yx', np.deg2rad([(-30, 20), (-10, 90)])), 172 | Joint(origin['middle2'], basis['middle'], 'x', np.deg2rad([(0, 100)])), 173 | Joint(origin['middle3'], basis['middle'], 'x', np.deg2rad([(0, 100)])), 174 | Joint(origin['pinky1'], basis['pinky'], 'yx', np.deg2rad([(-40, 20), (-10, 90)])), 175 | Joint(origin['pinky2'], basis['pinky'], 'x', np.deg2rad([(0, 100)])), 176 | Joint(origin['pinky3'], basis['pinky'], 'x', np.deg2rad([(0, 100)])), 177 | Joint(origin['ring1'], basis['ring'], 'yx', np.deg2rad([(-30, 20), (-10, 90)])), 178 | Joint(origin['ring2'], basis['ring'], 'x', np.deg2rad([(0, 100)])), 179 | Joint(origin['ring3'], basis['ring'], 'x', np.deg2rad([(0, 100)])), 180 | Joint(origin['thumb1'], basis['thumb0'], 'yz', np.deg2rad([(-10, 150), (-40, 40)])), 181 | Joint(origin['thumb2'], basis['thumb'], 'x', np.deg2rad([(0, 100)])), 182 | Joint(origin['thumb3'], basis['thumb'], 'x', np.deg2rad([(0, 100)])), 183 | ] 184 | 185 | 186 | class HandModel45(HandModel): 187 | """Rigid model with 45 degrees of freedom.""" 188 | 189 | def _make_joints(self): 190 | """Compute joints parameters. 191 | 192 | Returns: 193 | list -- list of joints parameters 194 | """ 195 | origin = dict(zip(self.link_names, self.origins())) 196 | limits = [(-np.pi, np.pi), (-np.pi/2, np.pi/2), (-np.pi, np.pi)] 197 | 198 | return [ 199 | Joint(origin['palm'], np.eye(3), '', []), 200 | Joint(origin['index1'], np.eye(3), 'xyz', limits), 201 | Joint(origin['index2'], np.eye(3), 'xyz', limits), 202 | Joint(origin['index3'], np.eye(3), 'xyz', limits), 203 | Joint(origin['middle1'], np.eye(3), 'xyz', limits), 204 | Joint(origin['middle2'], np.eye(3), 'xyz', limits), 205 | Joint(origin['middle3'], np.eye(3), 'xyz', limits), 206 | Joint(origin['pinky1'], np.eye(3), 'xyz', limits), 207 | Joint(origin['pinky2'], np.eye(3), 'xyz', limits), 208 | Joint(origin['pinky3'], np.eye(3), 'xyz', limits), 209 | Joint(origin['ring1'], np.eye(3), 'xyz', limits), 210 | Joint(origin['ring2'], np.eye(3), 'xyz', limits), 211 | Joint(origin['ring3'], np.eye(3), 'xyz', limits), 212 | Joint(origin['thumb1'], np.eye(3), 'xyz', limits), 213 | Joint(origin['thumb2'], np.eye(3), 'xyz', limits), 214 | Joint(origin['thumb3'], np.eye(3), 'xyz', limits), 215 | ] 216 | -------------------------------------------------------------------------------- /mano_pybullet/mano_model.py: -------------------------------------------------------------------------------- 1 | """This module describes the ManoModel.""" 2 | 3 | import functools 4 | import os 5 | import pickle 6 | import warnings 7 | 8 | import numpy as np 9 | 10 | from .math_utils import rvec2mat 11 | 12 | __all__ = ('ManoModel') 13 | 14 | 15 | class ManoModel: 16 | """The helper class to work with a MANO hand model.""" 17 | 18 | def __init__(self, left_hand=False, models_dir=None): 19 | """Load the hand model from a pickled file. 20 | 21 | Keyword Arguments: 22 | left_hand {bool} -- create a left hand model (default: {False}) 23 | models_dir {str} -- path to the pickled model files (default: {None}) 24 | """ 25 | if models_dir is None: 26 | models_dir = os.path.expandvars('$MANO_MODELS_DIR') 27 | 28 | fname = f'MANO_{["RIGHT", "LEFT"][left_hand]}.pkl' 29 | self._model = self._load(os.path.join(models_dir, fname)) 30 | self._is_left_hand = left_hand 31 | 32 | @staticmethod 33 | @functools.lru_cache(maxsize=2) 34 | def _load(path): 35 | """Load the model from disk. 36 | 37 | Arguments: 38 | path {str} -- path to the pickled model file 39 | 40 | Returns: 41 | chumpy array -- MANO model 42 | """ 43 | with open(path, 'rb') as pick_file: 44 | with warnings.catch_warnings(): # suppress chumpy warnings 45 | warnings.filterwarnings("ignore", category=DeprecationWarning) 46 | return pickle.load(pick_file, encoding='latin1') 47 | 48 | @property 49 | def is_left_hand(self): 50 | """This is the model of a left hand. 51 | 52 | Returns: 53 | bool -- left hand flag 54 | """ 55 | return self._is_left_hand 56 | 57 | @property 58 | def faces(self): 59 | """Hand mesh faces indices. 60 | 61 | Returns: 62 | np.ndarray -- matrix Nf x 3, where Nf - number of faces 63 | """ 64 | return self._model.get('f') 65 | 66 | @property 67 | def weights(self): 68 | """Vertex weights. 69 | 70 | Returns: 71 | array -- matrix Nv x Nl, where Nv - number of vertices, Nl - number of links 72 | """ 73 | return self._model.get('weights') 74 | 75 | @property 76 | def kintree_table(self): 77 | """Kinematic tree. 78 | 79 | Returns: 80 | array -- matrix 2 x Nl, where Nl - number of links 81 | """ 82 | return np.int32(self._model.get('kintree_table')) 83 | 84 | @property 85 | def shapedirs(self): 86 | """Shape mapping matrix. 87 | 88 | Returns: 89 | array -- matrix Nv x 3 x Nb, where Nv - vertices number, Nb - shape coeffs number 90 | """ 91 | return self._model.get('shapedirs') 92 | 93 | @property 94 | def posedirs(self): 95 | """Pose mapping matrix. 96 | 97 | Returns: 98 | array -- matrix Nv x 3 x ((Nl-1)*9), where Nv - vertices number, Nl - links number 99 | """ 100 | return self._model.get('posedirs') 101 | 102 | @property 103 | def link_names(self): 104 | """Human readable link names. 105 | 106 | Returns: 107 | list -- list of link names of size Nl, where Nl - number of links 108 | """ 109 | fingers = ('index', 'middle', 'pinky', 'ring', 'thumb') 110 | return ['palm'] + ['{}{}'.format(f, i) for f in fingers for i in range(1, 4)] 111 | 112 | @property 113 | def tip_links(self): 114 | """Tip link indices. 115 | 116 | Returns: 117 | list -- list of tip link indices 118 | """ 119 | return [3, 6, 12, 9, 15] 120 | 121 | def origins(self, betas=None, pose=None, trans=None): 122 | """Joint origins. 123 | 124 | Keyword Arguments: 125 | betas {array} -- shape coefficients, vector 1 x 10 (default: {None}) 126 | pose {array} -- hand pose, matrix Nl x 3 (default: {None}) 127 | trans {array} -- translation, vector 1 x 3 (default: {None}) 128 | 129 | Returns: 130 | array -- matrix Nl x 3, where Nl - number of links 131 | """ 132 | origins = self._model.get('J') 133 | if betas is not None: 134 | regressor = self._model.get('J_regressor') 135 | origins = regressor.dot(self.vertices(betas=betas)) 136 | if pose is not None: 137 | raise NotImplementedError 138 | if trans is not None: 139 | origins = origins + trans 140 | return origins 141 | 142 | def vertices(self, betas=None, pose=None, trans=None): 143 | """Hand mesh verticies. 144 | 145 | Keyword Arguments: 146 | betas {array} -- shape coefficients, vector 1 x 10 (default: {None}) 147 | pose {array} -- hand pose, matrix Nl x 3 (default: {None}) 148 | trans {array} -- translation, vector 1 x 3 (default: {None}) 149 | 150 | Returns: 151 | array -- matrix Nv x 3, where Nv - number of vertices 152 | """ 153 | vertices = self._model.get('v_template') 154 | if betas is not None: 155 | vertices = vertices + np.dot(self.shapedirs, betas) 156 | if pose is not None: 157 | pose = np.ravel([rvec2mat(rvec) - np.eye(3) for rvec in pose[1:]]) 158 | vertices = vertices + np.dot(self.posedirs, pose) 159 | raise NotImplementedError 160 | if trans is not None: 161 | vertices = vertices + trans 162 | return vertices 163 | -------------------------------------------------------------------------------- /mano_pybullet/math_utils.py: -------------------------------------------------------------------------------- 1 | """Math conversion utility functions.""" 2 | 3 | import numpy as np 4 | from transforms3d.axangles import axangle2mat, mat2axangle 5 | from transforms3d.euler import euler2mat, mat2euler 6 | from transforms3d.quaternions import mat2quat, quat2mat 7 | 8 | __all__ = ('mat2rvec', 'rvec2mat', 'joint2mat', 'mat2joint', 'mat2pb', 'pb2mat') 9 | 10 | 11 | def mat2rvec(mat): 12 | """Convert rotation matrix to rotation vector.""" 13 | axis, angle = mat2axangle(mat, unit_thresh=1e-05) 14 | return axis * angle 15 | 16 | 17 | def rvec2mat(rvec): 18 | """Convert rotation vector to rotation matrix.""" 19 | angle = np.linalg.norm(rvec) 20 | axis = rvec if angle != 0.0 else [0.0, 0.0, 1.0] 21 | mat = axangle2mat(axis, angle) 22 | return mat 23 | 24 | 25 | def joint2mat(axes, angles): 26 | """Compose rotation matrix of a multi-dof joint. 27 | 28 | Arguments: 29 | axes {str} -- joint axes 30 | angles {list} -- joint angles 31 | 32 | Returns: 33 | array -- rotation matrix 34 | """ 35 | rest = ''.join([i for i in 'xyz' if i not in axes]) 36 | euler = [0.0, 0.0, 0.0] 37 | euler[:len(axes)] = angles[:len(axes)] 38 | return euler2mat(*euler, 'r' + axes + rest) 39 | 40 | 41 | def mat2joint(mat, axes): 42 | """Decompose rotation matrix of a multi-dof joint. 43 | 44 | Arguments: 45 | mat {mat3} -- rotation matrix 46 | axes {str} -- joint axes 47 | 48 | Returns: 49 | list -- rotation angles about joint axes 50 | """ 51 | rest = ''.join([i for i in 'xyz' if i not in axes]) 52 | euler = mat2euler(mat, 'r' + axes + rest) 53 | return euler[:len(axes)] 54 | 55 | 56 | def mat2pb(mat): 57 | """Convert rotation matrix to quaternion in PyBullet's format.""" 58 | quat = mat2quat(mat) 59 | return quat[1], quat[2], quat[3], quat[0] 60 | 61 | 62 | def pb2mat(orn): 63 | """Convert quaternion in PyBullet's format to rotation matrix.""" 64 | quat = orn[3], orn[0], orn[1], orn[2] 65 | return quat2mat(quat) 66 | -------------------------------------------------------------------------------- /mano_pybullet/mesh_utils.py: -------------------------------------------------------------------------------- 1 | """Mesh manipulating uility functions.""" 2 | 3 | import numpy as np 4 | 5 | __all__ = ('filter_mesh', 'save_mesh_obj') 6 | 7 | 8 | def filter_mesh(vertices, faces, vertex_mask): 9 | """Get a submesh from a mesh using vertex mask. 10 | 11 | Arguments: 12 | vertices {array} -- whole mesh vertices 13 | faces {array} -- whole mesh faces 14 | vertex_mask {boolean array} -- vertex filter 15 | """ 16 | index_map = np.cumsum(vertex_mask) - 1 17 | faces_mask = np.all(vertex_mask[faces], axis=1) 18 | vertices_sub = vertices[vertex_mask] 19 | faces_sub = index_map[faces[faces_mask]] 20 | return vertices_sub, faces_sub 21 | 22 | 23 | def save_mesh_obj(filename, vertices, faces): 24 | """Save a mesh as an obj file. 25 | 26 | Arguments: 27 | filename {str} -- output file name 28 | vertices {array} -- mesh vertices 29 | faces {array} -- mesh faces 30 | """ 31 | with open(filename, 'w') as obj: 32 | for vert in vertices: 33 | obj.write('v {:f} {:f} {:f}\n'.format(*vert)) 34 | for face in faces + 1: # Faces are 1-based, not 0-based in obj files 35 | obj.write('f {:d} {:d} {:d}\n'.format(*face)) 36 | -------------------------------------------------------------------------------- /mano_pybullet/tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/mano_pybullet/tools/__init__.py -------------------------------------------------------------------------------- /mano_pybullet/tools/gui_control.py: -------------------------------------------------------------------------------- 1 | """GUI joint control test application.""" 2 | 3 | import argparse 4 | 5 | import numpy as np 6 | import pybullet as pb 7 | from pybullet_utils.bullet_client import BulletClient 8 | 9 | from ..hand_body import HandBody 10 | from ..hand_model import HandModel20, HandModel45 11 | 12 | parser = argparse.ArgumentParser('GUI debug tool') 13 | parser.add_argument('--dofs', type=int, default=20, 14 | help='Number of degrees of freedom (20 or 45)') 15 | 16 | parser.add_argument('--left-hand', dest='left_hand', action='store_true', 17 | help='Show left hand') 18 | parser.add_argument('--right-hand', dest='left_hand', action='store_false', 19 | help='Show right hand') 20 | parser.set_defaults(left_hand=False) 21 | 22 | parser.add_argument('--visual-shapes', dest='visual', action='store_true', 23 | help='Show visual shapes') 24 | parser.add_argument('--no-visual-shapes', dest='visual', action='store_false', 25 | help='Hide visual shapes') 26 | parser.set_defaults(visual=True) 27 | 28 | parser.add_argument('--self-collisions', dest='self_collisions', action='store_true', 29 | help='Enable self collisions') 30 | parser.add_argument('--no-self-collisions', dest='self_collisions', action='store_false', 31 | help='Disable self collisions') 32 | parser.set_defaults(self_collisions=True) 33 | 34 | 35 | def main(args): 36 | """Test GUI application.""" 37 | client = BulletClient(pb.GUI) 38 | client.setGravity(0, 0, -10) 39 | 40 | client.resetDebugVisualizerCamera( 41 | cameraDistance=0.5, 42 | cameraYaw=-40.0, 43 | cameraPitch=-40.0, 44 | cameraTargetPosition=[0.0, 0.0, 0.0] 45 | ) 46 | 47 | if args.dofs == 20: 48 | hand_model = HandModel20(left_hand=args.left_hand) 49 | elif args.dofs == 45: 50 | hand_model = HandModel45(left_hand=args.left_hand) 51 | else: 52 | raise ValueError('Only 20 and 45 DoF models are supported.') 53 | 54 | flags = sum([ 55 | HandBody.FLAG_ENABLE_COLLISION_SHAPES, 56 | HandBody.FLAG_ENABLE_VISUAL_SHAPES * args.visual, 57 | HandBody.FLAG_JOINT_LIMITS, 58 | HandBody.FLAG_DYNAMICS, 59 | HandBody.FLAG_USE_SELF_COLLISION * args.self_collisions]) 60 | 61 | client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 0) 62 | hand = HandBody(client, hand_model, flags=flags) 63 | client.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) 64 | 65 | slider_ids = [] 66 | for coord in ('X', 'Y', 'Z'): 67 | uid = client.addUserDebugParameter(f'base_{coord}', -0.5, 0.5, 0) 68 | slider_ids.append(uid) 69 | for coord in ('R', 'P', 'Y'): 70 | uid = client.addUserDebugParameter(f'base_{coord}', -3.14, 3.14, 0) 71 | slider_ids.append(uid) 72 | for i, joint in enumerate(hand_model.joints): 73 | name = hand_model.link_names[i] 74 | for axis, (lower, upper) in zip(joint.axes, joint.limits): 75 | uid = client.addUserDebugParameter(f'{name}[{axis}]', lower, upper, 0) 76 | slider_ids.append(uid) 77 | 78 | client.setRealTimeSimulation(True) 79 | 80 | try: 81 | while client.isConnected(): 82 | values = [client.readUserDebugParameter(uid) for uid in slider_ids] 83 | 84 | position = values[0:3] 85 | rotation = client.getQuaternionFromEuler(values[3:6]) 86 | angles = values[6:] 87 | 88 | hand.set_target(position, rotation, angles) 89 | except pb.error as err: 90 | if str(err) not in ['Not connected to physics server.', 'Failed to read parameter.']: 91 | raise 92 | 93 | 94 | if __name__ == '__main__': 95 | main(parser.parse_args()) 96 | -------------------------------------------------------------------------------- /media/lift_duck.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/media/lift_duck.gif -------------------------------------------------------------------------------- /media/push_teddy.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/media/push_teddy.gif -------------------------------------------------------------------------------- /media/tea_time.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/media/tea_time.gif -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [pylint] 2 | disable = c-extension-no-member, too-many-instance-attributes, too-many-locals, arguments-differ 3 | output-format = colorized 4 | 5 | [tool:pytest] 6 | minversion = 2.0 7 | norecursedirs = .git .tox build dist tmp* 8 | testpaths = tests 9 | python_files = test*.py 10 | 11 | [flake8] 12 | max-line-length = 99 13 | 14 | [yapf] 15 | column_limit = 99 16 | 17 | [isort] 18 | line_length = 99 19 | 20 | [pycodestyle] 21 | max-line-length = 99 22 | statistics = True 23 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """A setuptools based setup module.""" 2 | 3 | from os import path 4 | 5 | from setuptools import find_packages, setup 6 | 7 | here = path.abspath(path.dirname(__file__)) 8 | 9 | # Get the long description from the README file 10 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 11 | long_description = f.read() 12 | 13 | 14 | setup( 15 | name='mano_pybullet', 16 | version='0.1.0', 17 | description='MANO-based hand models for the PyBullet simulator.', 18 | long_description=long_description, 19 | long_description_content_type='text/markdown', 20 | url='https://github.com/ikalevatykh/mano_pybullet', 21 | author='Igor Kalevatykh', 22 | author_email='kalevatykhia@gmail.com', 23 | license='MIT', 24 | classifiers=[ 25 | 'Development Status :: 4 - Beta', 26 | 'License :: OSI Approved :: MIT License', 27 | 'Programming Language :: Python :: 3.6', 28 | 'Programming Language :: Python :: 3.7', 29 | 'Programming Language :: Python :: 3.8', 30 | 'Programming Language :: Python :: Implementation :: PyPy', 31 | 'Topic :: Scientific/Engineering', 32 | ], 33 | keywords='PyBullet MANO VR robotics', 34 | python_requires='>=3.6', 35 | packages=find_packages(), 36 | install_requires=[ 37 | 'numpy', 38 | 'chumpy', 39 | 'transforms3d', 40 | 'pybullet>=3.0.6', 41 | ], 42 | extras_require={ 43 | 'gym': ['gym>=0.17.3', 'imageio'] 44 | } 45 | ) 46 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/tests/__init__.py -------------------------------------------------------------------------------- /tests/envs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ikalevatykh/mano_pybullet/960c257cf465f8966e770562b66150beaa359230/tests/envs/__init__.py -------------------------------------------------------------------------------- /tests/envs/test_hand_env.py: -------------------------------------------------------------------------------- 1 | """Test hand_env module.""" 2 | 3 | import itertools 4 | import unittest 5 | 6 | import numpy as np 7 | import pybullet as pb 8 | from numpy.random import RandomState 9 | 10 | from mano_pybullet.envs.hand_env import HandEnv 11 | from mano_pybullet.hand_model import HandModel20, HandModel45 12 | 13 | 14 | class TestHandEnv(unittest.TestCase): 15 | """Test hand_env module.""" 16 | 17 | def setUp(self): 18 | self.random = RandomState(7) 19 | 20 | def test_constructor_default(self): 21 | env = HandEnv() 22 | self.assertEqual(env._hand_side, HandEnv.HAND_RIGHT) 23 | self.assertEqual(env._control_mode, HandEnv.MODE_JOINT) 24 | self.assertIsInstance(env._hand_models[0], HandModel20) 25 | 26 | def test_constructor_args(self): 27 | hand_side_list = (HandEnv.HAND_LEFT, HandEnv.HAND_RIGHT, HandEnv.HAND_BOTH) 28 | control_mode_list = (HandEnv.MODE_JOINT, HandEnv.MODE_MANO) 29 | model_cls_list = (HandModel20, HandModel45) 30 | args = itertools.product(hand_side_list, control_mode_list, model_cls_list) 31 | 32 | for hand_side, control_mode, model_cls in args: 33 | env = HandEnv(hand_side=hand_side, control_mode=control_mode, hand_model_cls=model_cls) 34 | env.reset() 35 | env.close() 36 | 37 | def test_reset_args(self): 38 | env = HandEnv() 39 | pos = self.random.uniform(-1.0, 1.0, size=(3,)) 40 | orn = pb.getQuaternionFromEuler( 41 | self.random.uniform([-np.pi, -np.pi/2, -np.pi], [np.pi, np.pi/2, np.pi])) 42 | angles = self.random.uniform(*env._hand_models[0].dofs_limits) 43 | observation = env.reset(initial_hands_state=[[pos, orn, angles]]) 44 | env.close() 45 | np.testing.assert_almost_equal(observation[0][0], pos) 46 | np.testing.assert_almost_equal(observation[0][1], orn) 47 | np.testing.assert_almost_equal(observation[0][3], angles) 48 | 49 | def test_show_window(self): 50 | env = HandEnv() 51 | self.assertFalse(env._show_window) 52 | env.show_window(True) 53 | self.assertTrue(env._show_window) 54 | 55 | 56 | if __name__ == "__main__": 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /tests/envs/test_hand_lift_env.py: -------------------------------------------------------------------------------- 1 | """Test hand_lift_env module.""" 2 | 3 | import unittest 4 | 5 | from mano_pybullet.envs.hand_lift_env import HandLiftEnv 6 | from mano_pybullet.envs.wrappers.json_player import JSONPlayer 7 | 8 | 9 | class TestHandLiftEnv(unittest.TestCase): 10 | """Test hand_lift_env module.""" 11 | 12 | def test_trajectory_playing(self): 13 | env = HandLiftEnv() 14 | env = JSONPlayer(env, './data/lift_duck.json') 15 | env.reset() 16 | done = False 17 | while not done: 18 | _observation, _reward, done, _info = env.step() 19 | env.close() 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /tests/envs/test_hand_object_env.py: -------------------------------------------------------------------------------- 1 | """Test hand_object_env module.""" 2 | 3 | import itertools 4 | import unittest 5 | 6 | from mano_pybullet.envs.hand_object_env import HandObjectEnv 7 | 8 | 9 | class TestHandObjectEnv(unittest.TestCase): 10 | """Test hand_object_env module.""" 11 | 12 | def test_constructor(self): 13 | model_path_list = ('duck_vhacd.urdf', 'teddy_vhacd.urdf') 14 | up_axis_list = ('x', 'y', 'z') 15 | args = itertools.product(model_path_list, up_axis_list) 16 | 17 | for model_path, up_axis in args: 18 | env = HandObjectEnv(model_path=model_path, up_axis=up_axis) 19 | env.reset() 20 | env.close() 21 | 22 | def test_reset_args(self): 23 | env = HandObjectEnv() 24 | env.reset(model_path='duck_vhacd.urdf', up_axis='z') 25 | env.close() 26 | 27 | 28 | if __name__ == "__main__": 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /tests/envs/test_hand_push_env.py: -------------------------------------------------------------------------------- 1 | """Test hand_push_env module.""" 2 | 3 | import unittest 4 | 5 | from mano_pybullet.envs.hand_push_env import HandPushEnv 6 | from mano_pybullet.envs.wrappers.json_player import JSONPlayer 7 | 8 | 9 | class TestHandPushEnv(unittest.TestCase): 10 | """Test hand_push_env module.""" 11 | 12 | def test_trajectory_playing(self): 13 | env = HandPushEnv() 14 | env = JSONPlayer(env, './data/push_teddy.json') 15 | env.reset() 16 | done = False 17 | while not done: 18 | _observation, _reward, done, _info = env.step() 19 | env.close() 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() -------------------------------------------------------------------------------- /tests/test_hand_body.py: -------------------------------------------------------------------------------- 1 | """Test kinematics module.""" 2 | 3 | import itertools 4 | import unittest 5 | 6 | import numpy as np 7 | import pybullet as pb 8 | from numpy.random import RandomState 9 | from pybullet_utils import bullet_client 10 | 11 | from mano_pybullet.hand_body import HandBody 12 | from mano_pybullet.hand_model import HandModel20, HandModel45 13 | from mano_pybullet.math_utils import pb2mat 14 | 15 | 16 | class TestHandBody(unittest.TestCase): 17 | """Test kinematics module.""" 18 | 19 | def setUp(self): 20 | self.random = RandomState(7) 21 | 22 | def test_model_matching(self): 23 | model_type_list = [HandModel20, HandModel45] 24 | 25 | for model_type, left_hand in itertools.product(model_type_list, (False, True)): 26 | with self.subTest(f'{model_type.__name__}(left_hand={left_hand})'): 27 | client = bullet_client.BulletClient(pb.DIRECT) 28 | hand_model = model_type(left_hand) 29 | hand = HandBody(client, hand_model) 30 | 31 | body_origins, body_basises = [], [] 32 | hand_origins, hand_basises = [], [] 33 | for hand_index, joint_index in hand._link_mapping.items(): 34 | state = client.getLinkState(hand.body_id, joint_index) 35 | body_origins.append(state[0]) 36 | hand_origins.append(hand_model.joints[hand_index].origin) 37 | body_basises.append(pb2mat(state[1])) 38 | hand_basises.append(hand_model.joints[hand_index].basis) 39 | client.disconnect() 40 | 41 | np.testing.assert_almost_equal(body_origins, hand_origins) 42 | np.testing.assert_almost_equal(body_basises, hand_basises) 43 | 44 | def test_self_collision(self): 45 | client = bullet_client.BulletClient(pb.DIRECT) 46 | hand_model = HandModel20() 47 | flags = HandBody.FLAG_DEFAULT | HandBody.FLAG_USE_SELF_COLLISION 48 | hand = HandBody(client, hand_model, flags=flags) 49 | 50 | client.stepSimulation() 51 | points1 = client.getContactPoints() 52 | 53 | hand.reset([0, 0, 0], [0, 0, 0, 1], [0.35] + [0.0] * 19) 54 | client.stepSimulation() 55 | points2 = client.getContactPoints() 56 | client.disconnect() 57 | 58 | self.assertEqual(len(points1), 0) 59 | self.assertGreater(len(points2), 0) 60 | 61 | def test_mano_state_conversion(self): 62 | client = bullet_client.BulletClient(pb.DIRECT) 63 | hand_model = HandModel45() 64 | hand = HandBody(client, hand_model) 65 | 66 | pos = self.random.uniform(-1, 1, size=3) 67 | orn = self.random.uniform(-1, 1, size=4) 68 | dofs = self.random.uniform(*hand_model.dofs_limits) 69 | hand.reset(pos, orn, dofs) 70 | 71 | trans, pose = hand.get_mano_state() 72 | hand.reset_from_mano(trans, pose) 73 | trans2, pose2 = hand.get_mano_state() 74 | client.disconnect() 75 | 76 | np.testing.assert_almost_equal(trans, trans2) 77 | np.testing.assert_almost_equal(pose, pose2) 78 | 79 | 80 | if __name__ == "__main__": 81 | unittest.main() 82 | -------------------------------------------------------------------------------- /tests/test_hand_model.py: -------------------------------------------------------------------------------- 1 | """Test kinematics module.""" 2 | 3 | import itertools 4 | import unittest 5 | 6 | import numpy as np 7 | from numpy.random import RandomState 8 | from transforms3d.quaternions import quat2mat 9 | 10 | from mano_pybullet.hand_model import HandModel20, HandModel45 11 | 12 | 13 | class TestHandModel(unittest.TestCase): 14 | """Test kinematics module.""" 15 | 16 | def setUp(self): 17 | self.random = RandomState(7) 18 | 19 | def test_constructor(self): 20 | model_type_list = [(HandModel20, 20), (HandModel45, 45)] 21 | 22 | for model_type, dofs_number in model_type_list: 23 | hand_model = model_type() 24 | self.assertEqual(hand_model.dofs_number, dofs_number) 25 | self.assertEqual(len(hand_model.dofs_limits[0]), dofs_number) 26 | self.assertEqual(len(hand_model.dofs_limits[1]), dofs_number) 27 | self.assertEqual(len(hand_model.joints), len(hand_model.origins())) 28 | 29 | def test_conversions(self): 30 | """Test mano pose <-> joint angles conversion.""" 31 | model_type_list = [HandModel20, HandModel45] 32 | 33 | for model_type, left_hand in itertools.product(model_type_list, (False, True)): 34 | with self.subTest(f"{model_type.__name__}(left_hand={left_hand})"): 35 | hand_model = model_type(left_hand) 36 | 37 | ang1 = self.random.uniform(*hand_model.dofs_limits) 38 | mat1 = quat2mat(self.random.uniform(-1, 1, size=(4,))) 39 | pose1 = hand_model.angles_to_mano(ang1, mat1) 40 | ang2, mat2 = hand_model.mano_to_angles(pose1) 41 | np.testing.assert_almost_equal(mat1, mat2) 42 | np.testing.assert_almost_equal(ang1, ang2) 43 | 44 | pose2 = hand_model.angles_to_mano(ang2, mat2) 45 | np.testing.assert_almost_equal(pose1, pose2) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /tests/test_mano_model.py: -------------------------------------------------------------------------------- 1 | """Test kinematics module.""" 2 | 3 | import unittest 4 | 5 | import numpy as np 6 | from numpy.random import RandomState 7 | 8 | from mano_pybullet.mano_model import ManoModel 9 | 10 | 11 | class TestManoModel(unittest.TestCase): 12 | """Test kinematics module.""" 13 | 14 | def setUp(self): 15 | self.random = RandomState(7) 16 | 17 | def test_constructor(self): 18 | for left_hand in False, True: 19 | with self.subTest(f"ManoModel(left_hand={left_hand})"): 20 | mano_model = ManoModel(left_hand) 21 | self.assertEqual(mano_model.is_left_hand, left_hand) 22 | self.assertIsNotNone(mano_model.faces) 23 | self.assertIsNotNone(mano_model.weights) 24 | self.assertIsNotNone(mano_model.kintree_table) 25 | self.assertIsNotNone(mano_model.shapedirs) 26 | self.assertIsNotNone(mano_model.posedirs) 27 | self.assertIsNotNone(mano_model.origins()) 28 | self.assertIsNotNone(mano_model.vertices()) 29 | self.assertEqual(len(mano_model.link_names), len(mano_model.origins())) 30 | self.assertEqual(len(mano_model.tip_links), 5) 31 | 32 | def test_origins(self): 33 | """Test the MANO joints transformation.""" 34 | mano_model = ManoModel() 35 | origins = mano_model.vertices( 36 | # pose=self.random.uniform((16, 3)), 37 | trans=self.random.random((3,))) 38 | self.assertIsNotNone(origins) 39 | 40 | def test_vertices(self): 41 | """Test the MANO vertices transformation.""" 42 | mano_model = ManoModel() 43 | vertices = mano_model.vertices( 44 | betas=self.random.random(10) * 0.1, 45 | # pose=self.random.random((16, 3)), 46 | trans=self.random.random(3)) 47 | self.assertIsNotNone(vertices) 48 | 49 | 50 | if __name__ == "__main__": 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /tests/test_math_utils.py: -------------------------------------------------------------------------------- 1 | """Test utils module.""" 2 | 3 | import itertools 4 | import unittest 5 | 6 | import numpy as np 7 | 8 | from mano_pybullet.math_utils import joint2mat, mat2joint, mat2pb, mat2rvec, pb2mat, rvec2mat 9 | 10 | 11 | class TestUtils(unittest.TestCase): 12 | """Test utils module.""" 13 | 14 | def test_joint_mat_conversion(self): 15 | """Test joint to/from mat conversion.""" 16 | angles1 = [1.1, 0.2, 2.3] 17 | for num in range(1, 4): 18 | for axes in itertools.combinations('xyz', num): 19 | mat = joint2mat(''.join(axes), angles1) 20 | angles2 = mat2joint(mat, ''.join(axes)) 21 | np.testing.assert_almost_equal(angles1[:len(axes)], angles2[:len(axes)]) 22 | 23 | def test_rvec_mat_conversion(self): 24 | """Test rotation vector to/from mat conversion.""" 25 | mat = np.eye(3) 26 | np.testing.assert_almost_equal(mat, rvec2mat(mat2rvec(mat))) 27 | rvec = [1.1, 0.2, 2.3] 28 | np.testing.assert_almost_equal(rvec, mat2rvec(rvec2mat(rvec))) 29 | 30 | def test_pb_mat_conversion(self): 31 | """Test pybullet quaternion to/from mat conversion.""" 32 | mat = np.eye(3) 33 | np.testing.assert_almost_equal(mat, pb2mat(mat2pb(mat))) 34 | orn = [0.1, 0.2, 0.3, 0.4] / np.linalg.norm([0.1, 0.2, 0.3, 0.4]) 35 | np.testing.assert_almost_equal(orn, mat2pb(pb2mat(orn))) 36 | --------------------------------------------------------------------------------