pax_global_header00006660000000000000000000000064136442333170014520gustar00rootroot0000000000000052 comment=04eda2722157dd43ebc93b0b351398e5e26a1cfa Py3ODE-1.2.0.dev15/000077500000000000000000000000001364423331700134465ustar00rootroot00000000000000Py3ODE-1.2.0.dev15/.gitignore000077500000000000000000000001501364423331700154350ustar00rootroot00000000000000build ode_notrimesh.c ode_trimesh.c _trimesh_switch.pyx MANIFEST dist ode_build .cache *.pyc *.egg-info Py3ODE-1.2.0.dev15/.travis.yml000066400000000000000000000017401364423331700155610ustar00rootroot00000000000000language: python python: - "3.6" # - "3.7" install: # cython # - pip install cython -vvv # ODE # - ./install_ode.sh # py3ode - pip install . script: pytest deploy: provider: pypi user: filipeabperes password: secure: "hVtAPyYTgPDG6EYRKcbKHs8zi/7JJH+xElz0Iktgn/TS/bMnDmhoiZKBN0NNrX+SNX5CowaCzyXCQhxF9E6Ddjgc7XUQaMtHblg9A2RZlLdyTrrnWWvR38WbsXN3TEn5RanYRvX1x916ZWfgA1ujZVGvuKcRcMlYP2FK835WEjpiiNLf+KQKP7pjXlA4oXjTdB07vFlM23Z/VyZAJLQtaOv93hJ47SOG4NuqdcfbRtkeJbqBbG1UMMCv/3b0/ia+T4t83dNTj2Ku1IlzpVYNh27Vn+IClhyESFYjOhr1HTDSF/EadWf1C1ZZzbO4nGgtCCm+MvZVVN8ZYmenPyFDsrrjfMx9u8krhgFJLrGng4Zpj1Chc/YXdNaI56SA0An+ehwNc2ezhYlI2MlADN/ndayVXsnJg3mBJOHMu7uo0SQsEDS8wCFL3RXxlZJ/lFMwHLyxjut2MoMjegGBCfNVTs2n8s7pEdn09Xi+7CsIgWrySUOQhQ3DcAe60ADojGtj/mR3hYaxIAvf0m7TKcufy3WyuQm2g9et7vyVJ+/7+0sAMnMGZItz8cfWl55zazJkSpwPCWKn16uXIN7aoTCd8O4krJQYfdpc1FsA4kT7AL1ZsBP6M6w2F1yDXVW9lSouCe2JLps8jAltlT9NVmvcbXa5V9WjA/3szI3upCKZAOM=" on: distributions: sdist repo: filipeabperes/Py3ODE Py3ODE-1.2.0.dev15/AUTHORS000077500000000000000000000002311364423331700145150ustar00rootroot00000000000000Timothy Stranex Matthias Baas Brett Hartshorn Bernie Roehl Ported for Python 3 by Filipe de Avila Belbute-Peres Py3ODE-1.2.0.dev15/INSTALL000077500000000000000000000020611364423331700145010ustar00rootroot00000000000000Installation instructions for all systems ========================================= Requirements: ------------- - Python v3.7 (or higher) http://www.python.org/ - ODE 0.16 http://ode.org/ - Cython 0.26.1 ODE can be installed by running the install_ode.sh script. Cython is installed automatically by pip as a dependency. Installation: ------------- The package uses the Python distutils, so you can build it by calling python setup.py build and install it by calling python setup.py install which installs the package on your system. See the "Installing Python Modules" manual inside your Python documentation or at http://docs.python.org/inst/inst.html if you want to customize the build process or the target location. Note: It is assumed that the ODE library is already compiled and installed somewhere on your system. The setup script will try to find the ODE installation on your system by trying several common locations. However, if the installation can not be found, you will have to modify the setup.py script and add the appropriate paths. Py3ODE-1.2.0.dev15/LICENSE000077500000000000000000000636361364423331700144740ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! Py3ODE-1.2.0.dev15/LICENSE-BSD000077500000000000000000000032241364423331700150650ustar00rootroot00000000000000 This is the BSD-style license for the Python Open Dynamics Engine Wrapper ------------------------------------------------------------------------- Python Open Dynamics Engine Wrapper Copyright (c) 2004, PyODE developers (see file AUTHORS) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the names of ODE's copyright owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Py3ODE-1.2.0.dev15/MANIFEST.in000077500000000000000000000004031364423331700152040ustar00rootroot00000000000000include AUTHORS include INSTALL include README include LICENSE include LICENSE-BSD include ChangeLog include ode_trimesh.c include ode_notrimesh.c include install_ode.sh recursive-include src *.pyx recursive-include examples *.py recursive-include tests *.py Py3ODE-1.2.0.dev15/README.rst000077500000000000000000000026431364423331700151450ustar00rootroot00000000000000Py3ODE ====== |travis| |pypi| |license| .. |travis| image:: https://travis-ci.org/filipeabperes/Py3ODE.svg :target: https://travis-ci.org/filipeabperes/Py3ODE .. |pypi| image:: https://img.shields.io/pypi/v/Py3ODE.svg :target: https://pypi.python.org/pypi/Py3ODE/ .. |license| image:: https://img.shields.io/badge/License-LGPL%20v2.1-blue.svg :target: https://www.gnu.org/licenses/lgpl-2.1 Py3ODE is a port of PyODE for Python 3. PyODE is a set of open-source Python bindings for The Open Dynamics Engine, an open-source physics engine. PyODE also includes an XODE parser. This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file LICENSE.TXT. (2) The BSD-style license that is included with this library in the file LICENSE-BSD.TXT. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files LICENSE and LICENSE-BSD for more details. * Installation instructions are in the INSTALL file * The PyODE web pages are at http://pyode.sourceforge.net/ Py3ODE-1.2.0.dev15/examples/000077500000000000000000000000001364423331700152645ustar00rootroot00000000000000Py3ODE-1.2.0.dev15/examples/transforms.py000077500000000000000000000135511364423331700200440ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # PyODE Example: Transforms # This example demonstrates the way object transforms are calculated relative # to the parent element's transform in XODE. from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from cgtypes import * import pygame import math import ode import xode.parser doc = ''' ''' def prepare_GL(c): """Prepare drawing. """ # Viewport glViewport(0, 0, 640, 480) # Initialize glClearColor(0.8, 0.8, 0.9, 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glEnable(GL_LIGHTING) glEnable(GL_NORMALIZE) glShadeModel(GL_FLAT) # Projection glMatrixMode(GL_PROJECTION) glLoadIdentity() P = mat4(1).perspective(45,1.3333,0.2,20) glMultMatrixd(P.toList()) # Initialize ModelView matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Light source glLightfv(GL_LIGHT0,GL_POSITION,[0,0,1,0]) glLightfv(GL_LIGHT0,GL_DIFFUSE,[1,1,1,1]) glLightfv(GL_LIGHT0,GL_SPECULAR,[1,1,1,1]) glEnable(GL_LIGHT0) # View transformation V = mat4(1).lookAt(1.2*vec3(0.5*c,0.7*c,c),(1.0,1.0,0), up=(0,1,0)) V.rotate(math.pi,vec3(0,1,0)) V = V.inverse() glMultMatrixd(V.toList()) def draw_body(body): """Draw an ODE body. """ x,y,z = body.getPosition() R = body.getRotation() T = mat4() T[0,0] = R[0] T[0,1] = R[1] T[0,2] = R[2] T[1,0] = R[3] T[1,1] = R[4] T[1,2] = R[5] T[2,0] = R[6] T[2,1] = R[7] T[2,2] = R[8] T[3] = (x,y,z,1.0) glPushMatrix() glMultMatrixd(T.toList()) if body.shape=="box": sx,sy,sz = body.boxsize glScale(sx, sy, sz) glutSolidCube(1) glPopMatrix() ###################################################################### # Initialize pygame passed, failed = pygame.init() # Open a window srf = pygame.display.set_mode((640,480), pygame.OPENGL | pygame.DOUBLEBUF) root = xode.parser.Parser().parseString(doc) world = root.namedChild('world1').getODEObject() world.setGravity( (0, 0, 0) ) # Add all ODE bodies from the XODE document into bodies. def transverse(node): obj = node.getODEObject() if (isinstance(obj, ode.Body)): # Set attributes for draw_body() obj.shape = 'box' obj.boxsize = (0.4, 0.4, 0.4) bodies.append(obj) for node in node.getChildren(): transverse(node) bodies = [] transverse(root) # Some variables used inside the simulation loop fps = 50 dt = 1.0/fps counter = 0.0 running = True clk = pygame.time.Clock() while running: events = pygame.event.get() for e in events: if e.type==pygame.QUIT: running=False if (counter < 5): counter = counter + 0.1 # Draw the scene prepare_GL(counter) for b in bodies: draw_body(b) pygame.display.flip() # Simulate n = 2 for i in range(n): world.step(dt/n) clk.tick(fps) Py3ODE-1.2.0.dev15/examples/tutorial1.py000077500000000000000000000043631364423331700175730ustar00rootroot00000000000000#!/usr/bin/env python3 """ Py3ODE example 1 Create a plane and a ball somwhere higher, let the ball fall, bounce, end. """ import faulthandler import ode import sys class Tutorial1: def __init__(self, trace = False): self.trace = trace def trace_func(self, frame, event, arg): print("{0}, {1}, {2}".format(frame, event, arg)) def body_callback(self, body): print("{0} - position: {1}, velocity: {2}, joints: {3}".format(body, body.getPosition(), body.getLinearVel(), body.getNumJoints())) def collision_callback(self, args, geom1, geom2): world, contactgroup = args body1, body2 = geom1.getBody(), geom2.getBody() if (body1 is None): body1 = ode.environment if (body2 is None): body2 = ode.environment contacts = ode.collide(geom1, geom2) for c in contacts: c.setBounce(0.5) c.setMu(10000) j = ode.ContactJoint(world, contactgroup, c) j.attach(body1, body2) def run_simulation(self): if self.trace: faulthandler.enable() sys.settrace(module.trace_func) # dynamics world world = ode.World() world.setGravity((0,0,-10)) # ODE uses Z as height by default # collision space space = ode.SimpleSpace() # SimpleSpace is slow-ish # contact group contactgroup = ode.JointGroup() # mass M = ode.Mass() M.setSphere(2500, 1) M.mass = 1.0 # dynamic body body = ode.Body(world) body.setMass(M) body.setPosition((0, 0, 10)) body.setMovedCallback(self.body_callback) # collision geom geom = ode.GeomSphere(space, 1) geom.setBody(body) # plane plane = ode.GeomPlane(space) # run simulation total_time = 0.0 dt = 0.04 while total_time < 4.5: print(total_time) space.collide((world, contactgroup), self.collision_callback) # collision detection world.quickStep(dt) # dynamics step contactgroup.empty() total_time += dt if __name__ == '__main__': #module = Tutorial1(True) module = Tutorial1() module.run_simulation() Py3ODE-1.2.0.dev15/examples/tutorial2.py000077500000000000000000000070701364423331700175720ustar00rootroot00000000000000# ODE Demo import sys import pygame from pygame.locals import * import ode import xode.parser doc = ''' ''' def coord(x,y): "Convert world coordinates to pixel coordinates." return int(320+170*x), int(400-170*y) def buildObjects(): world = ode.World() world.setGravity((0,-9.81,0)) body1 = ode.Body(world) M = ode.Mass() M.setSphere(2500, 0.05) body1.setMass(M) body1.setPosition((1,2,0)) body2 = ode.Body(world) M = ode.Mass() M.setSphere(2500, 0.05) body2.setMass(M) body2.setPosition((2,2,0)) j1 = ode.BallJoint(world) j1.attach(body1, ode.environment) j1.setAnchor( (0,2,0) ) #j1 = ode.HingeJoint(world) #j1.attach(body1, ode.environment) #j1.setAnchor( (0,2,0) ) #j1.setAxis( (0,0,1) ) #j1.setParam(ode.ParamVel, 3) #j1.setParam(ode.ParamFMax, 22) j2 = ode.BallJoint(world) j2.attach(body1, body2) j2.setAnchor( (1,2,0) ) return world, body1, body2, j1, j2 def buildObjectsXODE(): p = xode.parser.Parser() root = p.parseString(doc) world = root.namedChild('world').getODEObject() body1 = root.namedChild('body1').getODEObject() body2 = root.namedChild('body2').getODEObject() j1 = root.namedChild('joint1').getODEObject() j2 = root.namedChild('joint2').getODEObject() world.setGravity((0,-9.81,0)) #body1.setPosition((1,2,0)) #body2.setPosition((2,2,0)) #j1 = ode.BallJoint(world) #j1.attach(body1, ode.environment) #j1.setAnchor( (0,2,0) ) #j2 = ode.BallJoint(world) #j2.attach(body1, body2) #j2.setAnchor( (1,2,0) ) return world, body1, body2, j1, j2 def simulate(world, body1, body2): # Initialize pygame pygame.init() # Open a display srf = pygame.display.set_mode((640,480)) clk = pygame.time.Clock() # Keep the window open and wait for a key fps = 50 dt = 1.0/fps loopFlag = True while loopFlag: events = pygame.event.get() for e in events: if e.type==QUIT: loopFlag=False # Clear the screen srf.fill((255,255,255)) x1,y1,z1 = body1.getPosition() x2,y2,z2 = body2.getPosition() pygame.draw.circle(srf, (55,0,200), coord(x1,y1), 20, 0) pygame.draw.line(srf, (55,0,200), coord(0,2), coord(x1,y1), 2) pygame.draw.circle(srf, (55,0,200), coord(x2,y2), 20, 0) pygame.draw.line(srf, (55,0,200), coord(x1,y1), coord(x2,y2), 2) pygame.display.flip() world.step(dt) clk.tick(fps) #print "fps: %2.1f dt:%d rawdt:%d"%(clk.get_fps(), clk.get_time(), clk.get_rawtime()) world, body1, body2, j1, j2 = buildObjectsXODE() simulate(world, body1, body2) Py3ODE-1.2.0.dev15/examples/tutorial3.py000077500000000000000000000143451364423331700175760ustar00rootroot00000000000000# pyODE example 3: Collision detection # Originally by Matthias Baas. # Updated by Pierre Gay to work without pygame or cgkit. import sys, os, random, time from math import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import ode # geometric utility functions def scalp (vec, scal): vec[0] *= scal vec[1] *= scal vec[2] *= scal def length (vec): return sqrt (vec[0]**2 + vec[1]**2 + vec[2]**2) # prepare_GL def prepare_GL(): """Prepare drawing. """ # Viewport glViewport(0,0,640,480) # Initialize glClearColor(0.8,0.8,0.9,0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glEnable(GL_LIGHTING) glEnable(GL_NORMALIZE) glShadeModel(GL_FLAT) # Projection glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective (45,1.3333,0.2,20) # Initialize ModelView matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Light source glLightfv(GL_LIGHT0,GL_POSITION,[0,0,1,0]) glLightfv(GL_LIGHT0,GL_DIFFUSE,[1,1,1,1]) glLightfv(GL_LIGHT0,GL_SPECULAR,[1,1,1,1]) glEnable(GL_LIGHT0) # View transformation gluLookAt (2.4, 3.6, 4.8, 0.5, 0.5, 0, 0, 1, 0) # draw_body def draw_body(body): """Draw an ODE body. """ x,y,z = body.getPosition() R = body.getRotation() rot = [R[0], R[3], R[6], 0., R[1], R[4], R[7], 0., R[2], R[5], R[8], 0., x, y, z, 1.0] glPushMatrix() glMultMatrixd(rot) if body.shape=="box": sx,sy,sz = body.boxsize glScalef(sx, sy, sz) glutSolidCube(1) glPopMatrix() # create_box def create_box(world, space, density, lx, ly, lz): """Create a box body and its corresponding geom.""" # Create body body = ode.Body(world) M = ode.Mass() M.setBox(density, lx, ly, lz) body.setMass(M) # Set parameters for drawing the body body.shape = "box" body.boxsize = (lx, ly, lz) # Create a box geom for collision detection geom = ode.GeomBox(space, lengths=body.boxsize) geom.setBody(body) return body, geom # drop_object def drop_object(): """Drop an object into the scene.""" global bodies, geom, counter, objcount body, geom = create_box(world, space, 1000, 1.0,0.2,0.2) body.setPosition( (random.gauss(0,0.1),3.0,random.gauss(0,0.1)) ) theta = random.uniform(0,2*pi) ct = cos (theta) st = sin (theta) body.setRotation([ct, 0., -st, 0., 1., 0., st, 0., ct]) bodies.append(body) geoms.append(geom) counter=0 objcount+=1 # explosion def explosion(): """Simulate an explosion. Every object is pushed away from the origin. The force is dependent on the objects distance from the origin. """ global bodies for b in bodies: l=b.getPosition () d = length (l) a = max(0, 40000*(1.0-0.2*d*d)) l = [l[0] / 4, l[1], l[2] /4] scalp (l, a / length (l)) b.addForce(l) # pull def pull(): """Pull the objects back to the origin. Every object will be pulled back to the origin. Every couple of frames there'll be a thrust upwards so that the objects won't stick to the ground all the time. """ global bodies, counter for b in bodies: l=list (b.getPosition ()) scalp (l, -1000 / length (l)) b.addForce(l) if counter%60==0: b.addForce((0,10000,0)) # Collision callback def near_callback(args, geom1, geom2): """Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do. """ # Check if the objects do collide contacts = ode.collide(geom1, geom2) # Create contact joints world,contactgroup = args for c in contacts: c.setBounce(0.2) c.setMu(5000) j = ode.ContactJoint(world, contactgroup, c) j.attach(geom1.getBody(), geom2.getBody()) ###################################################################### # Initialize Glut glutInit ([]) # Open a window glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE) x = 0 y = 0 width = 640 height = 480 glutInitWindowPosition (x, y); glutInitWindowSize (width, height); glutCreateWindow ("testode") # Create a world object world = ode.World() world.setGravity( (0,-9.81,0) ) world.setERP(0.8) world.setCFM(1E-5) # Create a space object space = ode.Space() # Create a plane geom which prevent the objects from falling forever floor = ode.GeomPlane(space, (0,1,0), 0) # A list with ODE bodies bodies = [] # The geoms for each of the bodies geoms = [] # A joint group for the contact joints that are generated whenever # two bodies collide contactgroup = ode.JointGroup() # Some variables used inside the simulation loop fps = 50 dt = 1.0/fps running = True state = 0 counter = 0 objcount = 0 lasttime = time.time() # keyboard callback def _keyfunc (c, x, y): sys.exit (0) glutKeyboardFunc (_keyfunc) # draw callback def _drawfunc (): # Draw the scene prepare_GL() for b in bodies: draw_body(b) glutSwapBuffers () glutDisplayFunc (_drawfunc) # idle callback def _idlefunc (): global counter, state, lasttime t = dt - (time.time() - lasttime) if (t > 0): time.sleep(t) counter += 1 if state==0: if counter==20: drop_object() if objcount==30: state=1 counter=0 # State 1: Explosion and pulling back the objects elif state==1: if counter==100: explosion() if counter>300: pull() if counter==500: counter=20 glutPostRedisplay () # Simulate n = 2 for i in range(n): # Detect collisions and create contact joints space.collide((world,contactgroup), near_callback) # Simulation step world.step(dt/n) # Remove all contact joints contactgroup.empty() lasttime = time.time() glutIdleFunc (_idlefunc) glutMainLoop () Py3ODE-1.2.0.dev15/examples/tutorial_heightmap.png000066400000000000000000000004161364423331700216640ustar00rootroot00000000000000‰PNG  IHDR((Œþ¸mÕIDATXÃí˜Aƒ0E“LOÔcp'V܉ëµ{§SÉ"¶a©2¾üÓŸ­½Zá­xl@o<<Étr_ûL“P 2ZÝbФ;Öà1äÃ56,Z½5HØ è7H *ó$äX ‡ä/±æÓ,àUëRP*J%³í•Ì&ÙÛ­3@*RÛâ4@†}äLþ]‹y±z‚¼¶˜ÁŽ´X!­Ï*²£¶Ìd R: ðŠX™òOz×ïàeGÖfìÈ&-‚ƒ½šeñÞnmÀ|Ö|+m+IEND®B`‚Py3ODE-1.2.0.dev15/examples/tutorial_heightmap.py000066400000000000000000000062221364423331700215310ustar00rootroot00000000000000#!/usr/bin/env python3 """ Py3ODE heightmap example Load an image, extract its red channel, construct an ODE heightmap from the extracted data, add a ball somewhere higher and let it bounce on the heightmap. """ import faulthandler import numpy as np # pip install numpy import ode import sys from PIL import Image # pip install pillow class Tutorial_Heightmap: def __init__(self, trace = False): self.trace = trace def trace_func(self, frame, event, arg): print("{0}, {1}, {2}".format(frame, event, arg)) def body_callback(self, body): print("{0} - position: {1}, velocity: {2}, joints: {3}".format(body, body.getPosition(), body.getLinearVel(), body.getNumJoints())) def collision_callback(self, args, geom1, geom2): world, contactgroup = args body1, body2 = geom1.getBody(), geom2.getBody() if (body1 is None): body1 = ode.environment if (body2 is None): body2 = ode.environment contacts = ode.collide(geom1, geom2) for c in contacts: c.setBounce(0.5) c.setMu(10000) j = ode.ContactJoint(world, contactgroup, c) j.attach(body1, body2) def run_simulation(self): if self.trace: faulthandler.enable() sys.settrace(module.trace_func) # dynamics world world = ode.World() world.setGravity((0,-10, 0)) # heightmaps consider Y as up # collision space space = ode.SimpleSpace() # SimpleSpace is slow-ish # contact group contactgroup = ode.JointGroup() # mass M = ode.Mass() M.setSphere(2500, 1) M.mass = 1.0 # dynamic body body = ode.Body(world) body.setMass(M) body.setPosition((0, 260, 0)) body.setMovedCallback(self.body_callback) # collision geom geom = ode.GeomSphere(space, 1) geom.setBody(body) # heightmap h_data = ode.HeightfieldData() im = Image.open(sys.path[0] + "/tutorial_heightmap.png", "r") width, height = im.size pixel_values = list(im.getdata(0)) # 0 is the index of the Red channel in RGB / RGBA images - returns a list of longs for some reason tho height_data = np.array(pixel_values) height_data = height_data.astype(np.ubyte) # convert array to unsigned bytes as ODE expects so height_data = np.ascontiguousarray(height_data) # convert to a contiguous array so C code can read it and store data in variable to prevent garbage collection h_data.buildByte(height_data, False, width, height, width, height, 1, 0, 1, True) h_geom = ode.GeomHeightfield(data = h_data, space = space) # run simulation total_time = 0.0 dt = 0.04 while total_time < 4.5: print(total_time) space.collide((world, contactgroup), self.collision_callback) # collision detection world.quickStep(dt) # dynamics step contactgroup.empty() total_time += dt if __name__ == '__main__': #module = Tutorial_Heightmap(True) module = Tutorial_Heightmap() module.run_simulation() Py3ODE-1.2.0.dev15/examples/vehicle.py000077500000000000000000000330651364423331700172670ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # PyODE Example: VehicleDemo import ode, xode.parser import pygame from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * info = """VehicleDemo Controls: Left mouse button click: Apply upward force to the vehicle's chassis. W Key: Move forward. S Key: Move backward. A Key: Turn left. D Key: Turn right. Escape Key: Exit. """ # This XODE document contains the description of the vehicle, the ground plane # and the ramp. The stack of boxes are created at runtime. doc = ''' ''' class VehicleDemo: """ Vehicle Demo """ fps = 50.0 cameraDistance = 10.0 vel = 50.0 turn = 1.0 clip = 100.0 res = (640, 480) def __init__(self): """ Initialises this. """ self._initOpenGL() self._loadObjects() self._buildWall() self._cjoints = ode.JointGroup() self._xRot = 0.0 self._yRot = 0.0 self._xCoeff = 360.0 / 480.0 self._yCoeff = 360.0 / 640.0 self._vel = 0.0 self._turn = 0.0 def _loadObjects(self): p = xode.parser.Parser() root = p.parseString(doc) self.world = root.namedChild('world').getODEObject() self.space = root.namedChild('space').getODEObject() self.ground = root.namedChild('ground').getODEObject() self.chassis = root.namedChild('chassis').getODEObject() self.wheel1 = root.namedChild('wheel1').getODEObject() self.wheel2 = root.namedChild('wheel2').getODEObject() self.wheel3 = root.namedChild('wheel3').getODEObject() self.root = root self.world.setGravity((0, -9.81, 0)) # transverse the xode parse tree to make a list of all geoms and joints self._geoms = [] self._joints = [] def transverse(node): obj = node.getODEObject() if (isinstance(obj, ode.GeomObject)): self._geoms.append(obj) if (isinstance(obj, ode.Joint)): self._joints.append(obj) for child in node.getChildren(): transverse(child) transverse(root) def _buildWall(self): """ Create the wall of stacked boxes. """ def makeBox(x, y): body = ode.Body(self.world) body.setPosition((x, y, -40)) geom = ode.GeomBox(self.space, lengths=(0.5, 0.5, 0.5)) geom.setBody(body) self._geoms.append(geom) for x in range(-4, 5): for y in range(7): makeBox(x, y) def _initOpenGL(self): """ Initialise the scene. """ # Create a window pygame.init() screen = pygame.display.set_mode(self.res, pygame.OPENGL | pygame.DOUBLEBUF) pygame.display.set_caption('PyODE Vehicle Demo') pygame.mouse.set_visible(False) glViewport(0, 0, self.res[0], self.res[1]) glClearColor(0.8, 0.8, 0.9, 0) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEnable(GL_NORMALIZE) glShadeModel(GL_FLAT) def _extractMatrix(self, geom): """ Return a 4x4 matrix (represented by a 16-element tuple) created by combining the geom's rotation matrix and position. """ x, y, z = geom.getPosition() rot = geom.getRotation() return (rot[0], rot[3], rot[6], 0.0, rot[1], rot[4], rot[7], 0.0, rot[2], rot[5], rot[8], 0.0, x, y, z, 1.0) def _renderGeom(self, geom): """ Render either a ode.GeomBox or ode.GeomSphere object. """ allowed = [ode.GeomBox, ode.GeomSphere] ok = False for klass in allowed: ok = ok or isinstance(geom, klass) if (not ok): return glPushMatrix() glMultMatrixd(self._extractMatrix(geom)) glMaterialfv(GL_FRONT, GL_SPECULAR, (0.0, 0.0, 0.0)) if (isinstance(geom, ode.GeomBox)): sx, sy, sz = geom.getLengths() glScale(sx, sy, sz) glutSolidCube(1) elif (isinstance(geom, ode.GeomSphere)): r = geom.getRadius() glutSolidSphere(r, 20, 20) glPopMatrix() def _renderGround(self): """ Renders the ground plane. """ # Draw a quad at the position of the vehicle that extends to the # clipping planes. normal, d = self.ground.getParams() x, y, z = self.chassis.getPosition() glPushMatrix() glTranslate(x, 0.0, z) glMaterialfv(GL_FRONT, GL_SPECULAR, (0.0, 1.0, 0.0)) glBegin(GL_QUADS) glColor3(0.0, 1.0, 0.0) glNormal3f(*normal) glVertex3f(-self.clip, d, -self.clip) glNormal3f(*normal) glVertex3f(self.clip, d, -self.clip) glNormal3f(*normal) glVertex3f(self.clip, d, self.clip) glNormal3f(*normal) glVertex3f(-self.clip, d, self.clip) glEnd() glPopMatrix() def _setCamera(self): """ Position the camera to C{self.cameraDistance} units behind the vehicle's current position and rotated depending on the mouse position. """ aspect = float(self.res[0]) / float(self.res[1]) x, y = pygame.mouse.get_pos() self._xRot = (y - self.res[1]/2) * self._xCoeff self._yRot = (x - self.res[0]/2) * self._yCoeff if (self._xRot < 0): self._xRot = 0 glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(-aspect, aspect, -1.0, 1.0, 1.5, self.clip) glLightfv(GL_LIGHT0, GL_POSITION, (-5.0, 10.0, 0, 0)) glLightfv(GL_LIGHT0,GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0)) glLightfv(GL_LIGHT0,GL_SPECULAR, (1.0, 1.0, 1.0, 1.0)) glEnable(GL_LIGHT0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Set the camera angle to view the vehicle glTranslate(0.0, 0.0, -self.cameraDistance) glRotate(self._xRot, 1, 0, 0) glRotate(self._yRot, 0, 1, 0) # Set the camera so that the vehicle is drawn in the correct place. x, y, z = self.chassis.getPosition() glTranslate(-x, -y, -z) def render(self): """ Render the current simulation state. """ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self._renderGround() self._setCamera() for geom in self._geoms: self._renderGeom(geom) glFlush() pygame.display.flip() def _keyDown(self, key): if (key == pygame.K_w): self._vel = self.vel elif (key == pygame.K_a): self._turn = -self.turn elif (key == pygame.K_d): self._turn = self.turn elif (key == pygame.K_s): self._vel = -self.vel elif (key == pygame.K_ESCAPE): self._running = False def _keyUp(self, key): if (key == pygame.K_w): self._vel = 0.0 elif (key == pygame.K_a): self._turn = 0.0 elif (key == pygame.K_d): self._turn = 0.0 elif (key == pygame.K_s): self._vel = 0.0 def doEvents(self): """ Process any input events. """ events = pygame.event.get() for e in events: if (e.type == pygame.QUIT): self._running = False elif (e.type == pygame.KEYDOWN): self._keyDown(e.key) elif (e.type == pygame.KEYUP): self._keyUp(e.key) elif (e.type == pygame.MOUSEBUTTONDOWN): if (e.button == 1): self.chassis.addForce((0.0, 500000, 0.0)) def _nearcb(self, args, geom1, geom2): """ Create contact joints between colliding geoms. """ body1, body2 = geom1.getBody(), geom2.getBody() if (body1 is None): body1 = ode.environment if (body2 is None): body2 = ode.environment if (ode.areConnected(body1, body2)): return contacts = ode.collide(geom1, geom2) for c in contacts: c.setBounce(0.2) c.setMu(10000) j = ode.ContactJoint(self.world, self._cjoints, c) j.attach(body1, body2) def run(self): """ Start the demo. This method will block until the demo exits. """ clock = pygame.time.Clock() self._running = True while self._running: self.doEvents() # Steering self.wheel1.setParam(ode.ParamVel, self._turn) # Engine self.wheel1.setParam(ode.ParamVel2, self._vel) self.wheel2.setParam(ode.ParamVel2, self._vel) self.wheel3.setParam(ode.ParamVel2, self._vel) self.space.collide((), self._nearcb) self.world.step(1/self.fps) self._cjoints.empty() self.render() # Limit the FPS. clock.tick(self.fps) if (__name__ == '__main__'): print info demo = VehicleDemo() demo.run() Py3ODE-1.2.0.dev15/install_ode.sh000077500000000000000000000007701364423331700163060ustar00rootroot00000000000000#!/bin/bash set -e # Pass install dir as first argument. Defaults to $HOME/ode INSTALL_DIR=${1:-${HOME}/ode} ODE_VERSION=0.16 ODE_DIR=ode-${ODE_VERSION} ODE_TAR=${ODE_DIR}.tar.gz BUILD_DIR=ode_build pip install cython rm -rf $BUILD_DIR mkdir $BUILD_DIR cd $BUILD_DIR wget https://bitbucket.org/odedevs/ode/downloads/${ODE_TAR} tar -xvf $ODE_TAR rm $ODE_TAR cd $ODE_DIR ./configure CFLAGS="$CFLAGS -fPIC" CXXFLAGS="$CXXFLAGS -fPIC" --prefix=${INSTALL_DIR} make make install cd ../.. rm -rf $BUILD_DIR Py3ODE-1.2.0.dev15/setup.py000077500000000000000000000131401364423331700151620ustar00rootroot00000000000000###################################################################### # setup script for the Python wrapper of ODE ###################################################################### from distutils.core import setup, Extension import distutils.sysconfig import shutil, os, os.path, sys, glob, subprocess, pip from stat import * def system(cmd): f = os.popen(cmd) return f.read() # Directory for pip package PIP_DIR = os.path.join(os.path.split(os.path.split(pip.__file__)[0])[0], 'xode', 'ode') # Include directories INC_DIRS = [] # Library directories LIB_DIRS = [] # Libraries to link with LIBS = [] # Additional compiler arguments CC_ARGS = [] CC_ARGS.extend(system("ode-config --cflags").split()) # Additional linker arguments LINK_ARGS = [] LINK_ARGS.extend(system("ode-config --libs").split()) # If your version of ODE was compiled with OPCODE (trimesh support) enabled, # this should be set to True. TRIMESH_ENABLE = True ###################################################################### # Windows specific settings ###################################################################### if sys.platform=="win32": ODE_BASE = r"insert_your_path_here" INC_DIRS += [os.path.join(ODE_BASE, "include")] LIB_DIRS += [os.path.join(ODE_BASE, "lib", "releaselib")] LIBS += ["ode", "user32"] # user32 because of the MessageBox() call CC_ARGS += ["/ML"] LINK_ARGS += ["/NODEFAULTLIB:LIBCMT"] ###################################################################### # Linux (and other) specific settings ###################################################################### else: for base in ["/usr", "/usr/local", "/opt/local", os.path.expanduser("~/ode"), PIP_DIR]: INC_DIRS += [os.path.join(base, "include")] LIB_DIRS += [os.path.join(base, "lib")] LIBS += ["ode", "stdc++"] ###################################################################### ###################################################################### ###################################################################### def info(msg): """Output an info message. """ print("INFO:",msg) def warning(msg): """Output a warning message. """ print("WARNING:",msg) def error(msg, errorcode=1): """Output an error message and abort. """ print("ERROR:",msg) sys.exit(errorcode) # Generate the C source file (if necessary) def generate(name, trimesh_support): """Run Cython to generate the extension module source code. """ # Generate the trimesh_switch file f = open("_trimesh_switch.pyx", "wt") print('# This file was generated by the setup script and is included in ode.pyx.\n', file=f) if (trimesh_support): print('include "trimeshdata.pyx"', file=f) print('include "trimesh.pyx"', file=f) else: print('include "trimesh_dummy.pyx"', file=f) f.close() cmd = "cython -o %s -I. -Isrc src/ode.pyx" % name cython_out = name # Check if the cython output is still up to date or if it has to be generated # (ode.c will be updated if any of the *.pyx files in the directory "src" # is newer than ode.c) if os.access(cython_out, os.F_OK): ctime = os.stat(cython_out)[ST_MTIME] for pyx in glob.glob("src/*.pyx"): pytime = os.stat(pyx)[ST_MTIME] if pytime>ctime: info("Updating %s"%cython_out) print(cmd) err = os.system(cmd) break else: info("%s is up to date"%cython_out) err = 0 else: info("Creating %s"%cython_out) print(cmd) err = os.system(cmd) # Check if calling cython produced an error if err!=0: error("An error occured while generating the C source file.", err) def install_ode(install_dir='${HOME}/ode'): """Download and install ODE. """ if install_dir: os.makedirs(install_dir, exist_ok=True) subprocess.check_call(['./install_ode.sh', install_dir]) ###################################################################### # Check if ode.h can be found # (if it is not found it might not be an error because it may be located # in any of the include paths that are built into the compiler) num = 0 for path in INC_DIRS: ode_h = os.path.join(path, "ode", "ode.h") if os.path.exists(ode_h): info(" found in %s"%path) num += 1 if num==0: warning(" not found. Downloading and installing it now to your home directory." "\nIf it's already installed you may have to adjust INC_DIRS in setup.py.") install_ode() elif num>1: warning("ode.h was found more than once. Make sure the header and lib matches.") # Generate all possible source code versions so that they can be # packaged with the source archive and a user doesn't require Cython generate('ode_trimesh.c', True) generate('ode_notrimesh.c', False) if (TRIMESH_ENABLE): info("Installing with trimesh support.") install = 'ode_trimesh.c' else: info("INFO: Installing without trimesh support.") install = 'ode_notrimesh.c' # Compile the module setup(name = "Py3ODE", version = "1.2.0.dev15", description = "Port of PyODE for Python 3", author = "see file AUTHORS", author_email = "filipeabperes@gmail.com", license = "BSD or LGPL", url = "https://github.com/filipeabperes/Py3ODE", packages = ["xode"], python_requires='>=3', install_requires=['cython'], ext_modules = [Extension("ode", [install] ,libraries=LIBS ,include_dirs=INC_DIRS ,library_dirs=LIB_DIRS ,extra_compile_args=CC_ARGS ,extra_link_args=LINK_ARGS) ]) Py3ODE-1.2.0.dev15/src/000077500000000000000000000000001364423331700142355ustar00rootroot00000000000000Py3ODE-1.2.0.dev15/src/body.pyx000077500000000000000000000444631364423331700157520ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef class Body: """The rigid body class encapsulating the ODE body. This class represents a rigid body that has a location and orientation in space and that stores the mass properties of an object. When creating a Body object you have to pass the world it belongs to as argument to the constructor:: >>> import ode >>> w = ode.World() >>> b = ode.Body(w) """ cdef dBodyID bid # A reference to the world so that the world won't be destroyed while # there are still joints using it. cdef object world # A dictionary with user attributes # (set via __getattr__ and __setattr__) cdef object userattribs cdef object __weakref__ def __cinit__(self, World world not None): self.bid = dBodyCreate(world.wid) _geom_c2py_lut[self.bid] = self def __init__(self, World world not None): """Constructor. @param world: The world in which the body should be created. @type world: World """ self.world = world self.userattribs = {} self.callback = None def __dealloc__(self): if self.bid!=NULL: dBodyDestroy(self.bid) def __getattr__(self, name): try: return self.userattribs[name] except: raise AttributeError, "Body object has no attribute '%s'"%name def __setattr__(self, name, value): self.userattribs[name] = value def __delattr__(self, name): try: del self.userattribs[name] except: raise AttributeError, "Body object has no attribute '%s'"%name # setPosition def setPosition(self, pos): """setPosition(pos) Set the position of the body. @param pos: The new position @type pos: 3-sequence of floats """ dBodySetPosition(self.bid, pos[0], pos[1], pos[2]) # getPosition def getPosition(self): """getPosition() -> 3-tuple Return the current position of the body. """ cdef dReal* p # The "const" in the original return value is cast away p = dBodyGetPosition(self.bid) return (p[0],p[1],p[2]) # setRotation def setRotation(self, R): """setRotation(R) Set the orientation of the body. The rotation matrix must be given as a sequence of 9 floats which are the elements of the matrix in row-major order. @param R: Rotation matrix @type R: 9-sequence of floats """ cdef dMatrix3 m m[0] = R[0] m[1] = R[1] m[2] = R[2] m[3] = 0 m[4] = R[3] m[5] = R[4] m[6] = R[5] m[7] = 0 m[8] = R[6] m[9] = R[7] m[10] = R[8] m[11] = 0 dBodySetRotation(self.bid, m) # getRotation def getRotation(self): """getRotation() -> 9-tuple Return the current rotation matrix as a tuple of 9 floats (row-major order). """ cdef dReal* m # The "const" in the original return value is cast away m = dBodyGetRotation(self.bid) return (m[0],m[1],m[2],m[4],m[5],m[6],m[8],m[9],m[10]) # getQuaternion def getQuaternion(self): """getQuaternion() -> 4-tuple Return the current rotation as a quaternion. The return value is a list of 4 floats. """ cdef dReal* q q = dBodyGetQuaternion(self.bid) return (q[0], q[1], q[2], q[3]) # setQuaternion def setQuaternion(self, q): """setQuaternion(q) Set the orientation of the body. The quaternion must be given as a sequence of 4 floats. @param q: Quaternion @type q: 4-sequence of floats """ cdef dQuaternion w w[0] = q[0] w[1] = q[1] w[2] = q[2] w[3] = q[3] dBodySetQuaternion(self.bid, w) # setLinearVel def setLinearVel(self, vel): """setLinearVel(vel) Set the linear velocity of the body. @param vel: New velocity @type vel: 3-sequence of floats """ dBodySetLinearVel(self.bid, vel[0], vel[1], vel[2]) # getLinearVel def getLinearVel(self): """getLinearVel() -> 3-tuple Get the current linear velocity of the body. """ cdef dReal* p # The "const" in the original return value is cast away p = dBodyGetLinearVel(self.bid) return (p[0],p[1],p[2]) # setAngularVel def setAngularVel(self, vel): """setAngularVel(vel) Set the angular velocity of the body. @param vel: New angular velocity @type vel: 3-sequence of floats """ dBodySetAngularVel(self.bid, vel[0], vel[1], vel[2]) # getAngularVel def getAngularVel(self): """getAngularVel() -> 3-tuple Get the current angular velocity of the body. """ cdef dReal* p # The "const" in the original return value is cast away p = dBodyGetAngularVel(self.bid) return (p[0],p[1],p[2]) # setMass def setMass(self, Mass mass): """setMass(mass) Set the mass properties of the body. The argument mass must be an instance of a Mass object. @param mass: Mass properties @type mass: Mass """ dBodySetMass(self.bid, &mass._mass) # getMass def getMass(self): """getMass() -> mass Return the mass properties as a Mass object. """ cdef Mass m m=Mass() dBodyGetMass(self.bid, &m._mass) return m # addForce def addForce(self, f): """addForce(f) Add an external force f given in absolute coordinates. The force is applied at the center of mass. @param f: Force @type f: 3-sequence of floats """ dBodyAddForce(self.bid, f[0], f[1], f[2]) # addTorque def addTorque(self, t): """addTorque(t) Add an external torque t given in absolute coordinates. @param t: Torque @type t: 3-sequence of floats """ dBodyAddTorque(self.bid, t[0], t[1], t[2]) # addRelForce def addRelForce(self, f): """addRelForce(f) Add an external force f given in relative coordinates (relative to the body's own frame of reference). The force is applied at the center of mass. @param f: Force @type f: 3-sequence of floats """ dBodyAddRelForce(self.bid, f[0], f[1], f[2]) # addRelTorque def addRelTorque(self, t): """addRelTorque(t) Add an external torque t given in relative coordinates (relative to the body's own frame of reference). @param t: Torque @type t: 3-sequence of floats """ dBodyAddRelTorque(self.bid, t[0], t[1], t[2]) # addForceAtPos def addForceAtPos(self, f, p): """addForceAtPos(f, p) Add an external force f at position p. Both arguments must be given in absolute coordinates. @param f: Force @param p: Position @type f: 3-sequence of floats @type p: 3-sequence of floats """ dBodyAddForceAtPos(self.bid, f[0], f[1], f[2], p[0], p[1], p[2]) # addForceAtRelPos def addForceAtRelPos(self, f, p): """addForceAtRelPos(f, p) Add an external force f at position p. f is given in absolute coordinates and p in absolute coordinates. @param f: Force @param p: Position @type f: 3-sequence of floats @type p: 3-sequence of floats """ dBodyAddForceAtRelPos(self.bid, f[0], f[1], f[2], p[0], p[1], p[2]) # addRelForceAtPos def addRelForceAtPos(self, f, p): """addRelForceAtPos(f, p) Add an external force f at position p. f is given in relative coordinates and p in relative coordinates. @param f: Force @param p: Position @type f: 3-sequence of floats @type p: 3-sequence of floats """ dBodyAddRelForceAtPos(self.bid, f[0], f[1], f[2], p[0], p[1], p[2]) # addRelForceAtRelPos def addRelForceAtRelPos(self, f, p): """addRelForceAtRelPos(f, p) Add an external force f at position p. Both arguments must be given in relative coordinates. @param f: Force @param p: Position @type f: 3-sequence of floats @type p: 3-sequence of floats """ dBodyAddRelForceAtRelPos(self.bid, f[0], f[1], f[2], p[0], p[1], p[2]) # getForce def getForce(self): """getForce() -> 3-tuple Return the current accumulated force. """ cdef dReal* f # The "const" in the original return value is cast away f = dBodyGetForce(self.bid) return (f[0],f[1],f[2]) # getTorque def getTorque(self): """getTorque() -> 3-tuple Return the current accumulated torque. """ cdef dReal* f # The "const" in the original return value is cast away f = dBodyGetTorque(self.bid) return (f[0],f[1],f[2]) # setForce def setForce(self, f): """setForce(f) Set the body force accumulation vector. @param f: Force @type f: 3-tuple of floats """ dBodySetForce(self.bid, f[0], f[1], f[2]) # setTorque def setTorque(self, t): """setTorque(t) Set the body torque accumulation vector. @param t: Torque @type t: 3-tuple of floats """ dBodySetTorque(self.bid, t[0], t[1], t[2]) # getRelPointPos def getRelPointPos(self, p): """getRelPointPos(p) -> 3-tuple Utility function that takes a point p on a body and returns that point's position in global coordinates. The point p must be given in body relative coordinates. @param p: Body point (local coordinates) @type p: 3-sequence of floats """ cdef dVector3 res dBodyGetRelPointPos(self.bid, p[0], p[1], p[2], res) return (res[0], res[1], res[2]) # getRelPointVel def getRelPointVel(self, p): """getRelPointVel(p) -> 3-tuple Utility function that takes a point p on a body and returns that point's velocity in global coordinates. The point p must be given in body relative coordinates. @param p: Body point (local coordinates) @type p: 3-sequence of floats """ cdef dVector3 res dBodyGetRelPointVel(self.bid, p[0], p[1], p[2], res) return (res[0], res[1], res[2]) # getPointVel def getPointVel(self, p): """getPointVel(p) -> 3-tuple Utility function that takes a point p on a body and returns that point's velocity in global coordinates. The point p must be given in global coordinates. @param p: Body point (global coordinates) @type p: 3-sequence of floats """ cdef dVector3 res dBodyGetPointVel(self.bid, p[0], p[1], p[2], res) return (res[0], res[1], res[2]) # getPosRelPoint def getPosRelPoint(self, p): """getPosRelPoint(p) -> 3-tuple This is the inverse of getRelPointPos(). It takes a point p in global coordinates and returns the point's position in body-relative coordinates. @param p: Body point (global coordinates) @type p: 3-sequence of floats """ cdef dVector3 res dBodyGetPosRelPoint(self.bid, p[0], p[1], p[2], res) return (res[0], res[1], res[2]) # vectorToWorld def vectorToWorld(self, v): """vectorToWorld(v) -> 3-tuple Given a vector v expressed in the body coordinate system, rotate it to the world coordinate system. @param v: Vector in body coordinate system @type v: 3-sequence of floats """ cdef dVector3 res dBodyVectorToWorld(self.bid, v[0], v[1], v[2], res) return (res[0], res[1], res[2]) # vectorFromWorld def vectorFromWorld(self, v): """vectorFromWorld(v) -> 3-tuple Given a vector v expressed in the world coordinate system, rotate it to the body coordinate system. @param v: Vector in world coordinate system @type v: 3-sequence of floats """ cdef dVector3 res dBodyVectorFromWorld(self.bid, v[0], v[1], v[2], res) return (res[0], res[1], res[2]) # Enable def enable(self): """enable() Manually enable a body. """ dBodyEnable(self.bid) # Disable def disable(self): """disable() Manually disable a body. Note that a disabled body that is connected through a joint to an enabled body will be automatically re-enabled at the next simulation step. """ dBodyDisable(self.bid) # isEnabled def isEnabled(self): """isEnabled() -> bool Check if a body is currently enabled. """ return dBodyIsEnabled(self.bid) # setFiniteRotationMode def setFiniteRotationMode(self, mode): """setFiniteRotationMode(mode) This function controls the way a body's orientation is updated at each time step. The mode argument can be: - 0: An "infinitesimal" orientation update is used. This is fast to compute, but it can occasionally cause inaccuracies for bodies that are rotating at high speed, especially when those bodies are joined to other bodies. This is the default for every new body that is created. - 1: A "finite" orientation update is used. This is more costly to compute, but will be more accurate for high speed rotations. Note however that high speed rotations can result in many types of error in a simulation, and this mode will only fix one of those sources of error. @param mode: Rotation mode (0/1) @type mode: int """ dBodySetFiniteRotationMode(self.bid, mode) # getFiniteRotationMode def getFiniteRotationMode(self): """getFiniteRotationMode() -> mode (0/1) Return the current finite rotation mode of a body (0 or 1). See setFiniteRotationMode(). """ return dBodyGetFiniteRotationMode(self.bid) # setFiniteRotationAxis def setFiniteRotationAxis(self, a): """setFiniteRotationAxis(a) Set the finite rotation axis of the body. This axis only has a meaning when the finite rotation mode is set (see setFiniteRotationMode()). @param a: Axis @type a: 3-sequence of floats """ dBodySetFiniteRotationAxis(self.bid, a[0], a[1], a[2]) # getFiniteRotationAxis def getFiniteRotationAxis(self): """getFiniteRotationAxis() -> 3-tuple Return the current finite rotation axis of the body. """ cdef dVector3 p # The "const" in the original return value is cast away dBodyGetFiniteRotationAxis(self.bid, p) return (p[0],p[1],p[2]) # getNumJoints def getNumJoints(self): """getNumJoints() -> int Return the number of joints that are attached to this body. """ return dBodyGetNumJoints(self.bid) # setGravityMode def setGravityMode(self, mode): """setGravityMode(mode) Set whether the body is influenced by the world's gravity or not. If mode is True it is, otherwise it isn't. Newly created bodies are always influenced by the world's gravity. @param mode: Gravity mode @type mode: bool """ dBodySetGravityMode(self.bid, mode) # getGravityMode def getGravityMode(self): """getGravityMode() -> bool Return True if the body is influenced by the world's gravity. """ return dBodyGetGravityMode(self.bid) def setDynamic(self): """setDynamic() Set a body to the (default) "dynamic" state, instead of "kinematic". See setKinematic() for more information. """ dBodySetDynamic(self.bid) def setKinematic(self): """setKinematic() Set the kinematic state of the body (change it into a kinematic body) Kinematic bodies behave as if they had infinite mass. This means they don't react to any force (gravity, constraints or user-supplied); they simply follow velocity to reach the next position. [from ODE wiki] """ dBodySetKinematic(self.bid) def isKinematic(self): """isKinematic() -> bool Return True if the body is kinematic (not influenced by other forces). Kinematic bodies behave as if they had infinite mass. This means they don't react to any force (gravity, constraints or user-supplied); they simply follow velocity to reach the next position. [from ODE wiki] """ return dBodyIsKinematic(self.bid) def setMovedCallback(self, callback): """setMovedCallback() Use it to register a function callback that is invoked whenever the body moves (that is, while it is not disabled). This is useful for integrating ODE with 3D engines, where 3D entities must be moved whenever a ODE body move. """ self.callback = callback dBodySetMovedCallback(self.bid, body_callback) cdef void body_callback(dBodyID body_id): body = _geom_c2py_lut[body_id] body.callback(body) Py3ODE-1.2.0.dev15/src/contact.pyx000077500000000000000000000231011364423331700164320ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef class Contact: """This class represents a contact between two bodies in one point. A Contact object stores all the input parameters for a ContactJoint. This class wraps the ODE dContact structure which has 3 components:: struct dContact { dSurfaceParameters surface; dContactGeom geom; dVector3 fdir1; }; This wrapper class provides methods to get and set the items of those structures. """ cdef dContact _contact def __cinit__(self): self._contact.surface.mode = ContactBounce self._contact.surface.mu = dInfinity self._contact.surface.bounce = 0.1 # getMode def getMode(self): """getMode() -> flags Return the contact flags. """ return self._contact.surface.mode # setMode def setMode(self, flags): """setMode(flags) Set the contact flags. The argument m is a combination of the ContactXyz flags (ContactMu2, ContactBounce, ...). @param flags: Contact flags @type flags: int """ self._contact.surface.mode = flags # getMu def getMu(self): """getMu() -> float Return the Coulomb friction coefficient. """ return self._contact.surface.mu # setMu def setMu(self, mu): """setMu(mu) Set the Coulomb friction coefficient. @param mu: Coulomb friction coefficient (0..Infinity) @type mu: float """ self._contact.surface.mu = mu # getMu2 def getMu2(self): """getMu2() -> float Return the optional Coulomb friction coefficient for direction 2. """ return self._contact.surface.mu2 # setMu2 def setMu2(self, mu): """setMu2(mu) Set the optional Coulomb friction coefficient for direction 2. @param mu: Coulomb friction coefficient (0..Infinity) @type mu: float """ self._contact.surface.mu2 = mu # getBounce def getBounce(self): """getBounce() -> float Return the restitution parameter. """ return self._contact.surface.bounce # setBounce def setBounce(self, b): """setBounce(b) @param b: Restitution parameter (0..1) @type b: float """ self._contact.surface.bounce = b # getBounceVel def getBounceVel(self): """getBounceVel() -> float Return the minimum incoming velocity necessary for bounce. """ return self._contact.surface.bounce_vel # setBounceVel def setBounceVel(self, bv): """setBounceVel(bv) Set the minimum incoming velocity necessary for bounce. Incoming velocities below this will effectively have a bounce parameter of 0. @param bv: Velocity @type bv: float """ self._contact.surface.bounce_vel = bv # getSoftERP def getSoftERP(self): """getSoftERP() -> float Return the contact normal "softness" parameter. """ return self._contact.surface.soft_erp # setSoftERP def setSoftERP(self, erp): """setSoftERP(erp) Set the contact normal "softness" parameter. @param erp: Softness parameter @type erp: float """ self._contact.surface.soft_erp = erp # getSoftCFM def getSoftCFM(self): """getSoftCFM() -> float Return the contact normal "softness" parameter. """ return self._contact.surface.soft_cfm # setSoftCFM def setSoftCFM(self, cfm): """setSoftCFM(cfm) Set the contact normal "softness" parameter. @param cfm: Softness parameter @type cfm: float """ self._contact.surface.soft_cfm = cfm # getMotion1 def getMotion1(self): """getMotion1() -> float Get the surface velocity in friction direction 1. """ return self._contact.surface.motion1 # setMotion1 def setMotion1(self, m): """setMotion1(m) Set the surface velocity in friction direction 1. @param m: Surface velocity @type m: float """ self._contact.surface.motion1 = m # getMotion2 def getMotion2(self): """getMotion2() -> float Get the surface velocity in friction direction 2. """ return self._contact.surface.motion2 # setMotion2 def setMotion2(self, m): """setMotion2(m) Set the surface velocity in friction direction 2. @param m: Surface velocity @type m: float """ self._contact.surface.motion2 = m # getSlip1 def getSlip1(self): """getSlip1() -> float Get the coefficient of force-dependent-slip (FDS) for friction direction 1. """ return self._contact.surface.slip1 # setSlip1 def setSlip1(self, s): """setSlip1(s) Set the coefficient of force-dependent-slip (FDS) for friction direction 1. @param s: FDS coefficient @type s: float """ self._contact.surface.slip1 = s # getSlip2 def getSlip2(self): """getSlip2() -> float Get the coefficient of force-dependent-slip (FDS) for friction direction 2. """ return self._contact.surface.slip2 # setSlip2 def setSlip2(self, s): """setSlip2(s) Set the coefficient of force-dependent-slip (FDS) for friction direction 1. @param s: FDS coefficient @type s: float """ self._contact.surface.slip2 = s # getFDir1 def getFDir1(self): """getFDir1() -> (x, y, z) Get the "first friction direction" vector that defines a direction along which frictional force is applied. """ return (self._contact.fdir1[0], self._contact.fdir1[1], self._contact.fdir1[2]) # setFDir1 def setFDir1(self, fdir): """setFDir1(fdir) Set the "first friction direction" vector that defines a direction along which frictional force is applied. It must be of unit length and perpendicular to the contact normal (so it is typically tangential to the contact surface). @param fdir: Friction direction @type fdir: 3-sequence of floats """ self._contact.fdir1[0] = fdir[0] self._contact.fdir1[1] = fdir[1] self._contact.fdir1[2] = fdir[2] # getContactGeomParams def getContactGeomParams(self): """getContactGeomParams() -> (pos, normal, depth, geom1, geom2) Get the ContactGeom structure of the contact. The return value is a tuple (pos, normal, depth, geom1, geom2) where pos and normal are 3-tuples of floats and depth is a single float. geom1 and geom2 are the Geom objects of the geoms in contact. """ cdef long id1, id2 pos = (self._contact.geom.pos[0], self._contact.geom.pos[1], self._contact.geom.pos[2]) normal = (self._contact.geom.normal[0], self._contact.geom.normal[1], self._contact.geom.normal[2]) depth = self._contact.geom.depth id1 = self._contact.geom.g1 id2 = self._contact.geom.g2 g1 = _geom_c2py_lut[id1] g2 = _geom_c2py_lut[id2] return (pos,normal,depth,g1,g2) # setContactGeomParams def setContactGeomParams(self, pos, normal, depth, g1=None, g2=None): """setContactGeomParams(pos, normal, depth, geom1=None, geom2=None) Set the ContactGeom structure of the contact. @param pos: Contact position, in global coordinates @type pos: 3-sequence of floats @param normal: Unit length normal vector @type normal: 3-sequence of floats @param depth: Depth to which the two bodies inter-penetrate @type depth: float @param geom1: Geometry object 1 that collided @type geom1: Geom @param geom2: Geometry object 2 that collided @type geom2: Geom """ cdef long id self._contact.geom.pos[0] = pos[0] self._contact.geom.pos[1] = pos[1] self._contact.geom.pos[2] = pos[2] self._contact.geom.normal[0] = normal[0] self._contact.geom.normal[1] = normal[1] self._contact.geom.normal[2] = normal[2] self._contact.geom.depth = depth if g1!=None: id = g1._id() self._contact.geom.g1 = id else: self._contact.geom.g1 = 0 if g2!=None: id = g2._id() self._contact.geom.g2 = id else: self._contact.geom.g2 = 0 Py3ODE-1.2.0.dev15/src/declarations.pyx000077500000000000000000001121231364423331700174520ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef extern from "stdlib.h": void* malloc(long) void free(void*) cdef extern from "stdio.h": int printf(char*) cdef extern from "ode/ode.h": ctypedef double dReal # Dummy structs cdef struct dxWorld: int _dummy cdef struct dxSpace: int _dummy cdef struct dxBody: int _dummy cdef struct dxGeom: int _dummy cdef struct dxJoint: int _dummy cdef struct dxJointGroup: int _dummy cdef struct dxTriMeshData: int _dummy cdef struct dxHeightfieldData: int _dummy # Types ctypedef dxWorld* dWorldID ctypedef dxSpace* dSpaceID ctypedef dxBody* dBodyID ctypedef dxGeom* dGeomID ctypedef dxJoint* dJointID ctypedef dxJointGroup* dJointGroupID ctypedef dxTriMeshData* dTriMeshDataID ctypedef dxHeightfieldData* dHeightfieldDataID ctypedef dReal dVector3[4] ctypedef dReal dVector4[4] ctypedef dReal dMatrix3[4*3] ctypedef dReal dMatrix4[4*4] ctypedef dReal dMatrix6[8*6] ctypedef dReal dQuaternion[4] cdef extern dReal dInfinity cdef extern int dAMotorUser cdef extern int dAMotorEuler ctypedef struct dMass: dReal mass dVector4 c dMatrix3 I ctypedef struct dJointFeedback: dVector3 f1 dVector3 t1 dVector3 f2 dVector3 t2 ctypedef void dNearCallback(void* data, dGeomID o1, dGeomID o2) ctypedef dReal dHeightfieldGetHeight( void* p_user_data, int x, int z ) ctypedef void dGetAABBFn (dGeomID, dReal aabb[6]) ctypedef int dColliderFn (dGeomID o1, dGeomID o2, int flags, dContactGeom *contact, int skip) ctypedef dColliderFn * dGetColliderFnFn (int num) ctypedef void dGeomDtorFn (dGeomID o) ctypedef int dAABBTestFn (dGeomID o1, dGeomID o2, dReal aabb[6]) ctypedef struct dSurfaceParameters: int mode dReal mu dReal mu2 dReal bounce dReal bounce_vel dReal soft_erp dReal soft_cfm dReal motion1,motion2 dReal slip1,slip2 ctypedef struct dContactGeom: dVector3 pos dVector3 normal dReal depth dGeomID g1,g2 ctypedef struct dContact: dSurfaceParameters surface dContactGeom geom dVector3 fdir1 ctypedef struct dGeomClass: int bytes dGetColliderFnFn *collider dGetAABBFn *aabb dAABBTestFn *aabb_test dGeomDtorFn *dtor ctypedef struct dWorldStepReserveInfo: unsigned struct_size float reserve_factor unsigned reserve_minimum ctypedef struct dWorldStepMemoryFunctionsInfo: pass # unsigned struct_size # void *(*alloc_block)(dsizeint block_size) # void *(*shrink_block)(void *block_pointer, dsizeint block_current_size, dsizeint block_smaller_size) # void (*free_block)(void *block_pointer, dsizeint block_current_size) # ODE void dInitODE() void dCloseODE() # World dWorldID dWorldCreate() void dWorldDestroy (dWorldID) #not actually present in the manual void dWorldSetData (dWorldID world, void* data) void* dWorldGetData (dWorldID world) void dWorldSetGravity (dWorldID, dReal x, dReal y, dReal z) void dWorldGetGravity (dWorldID, dVector3 gravity) void dWorldSetERP (dWorldID, dReal erp) dReal dWorldGetERP (dWorldID) void dWorldSetCFM (dWorldID, dReal cfm) dReal dWorldGetCFM (dWorldID) # not present in the manual void dWorldSetStepIslandsProcessingMaxThreadCount(dWorldID w, unsigned count) unsigned dWorldGetStepIslandsProcessingMaxThreadCount(dWorldID w) # not present in the manual int dWorldUseSharedWorkingMemory(dWorldID w, dWorldID from_world) void dWorldCleanupWorkingMemory(dWorldID w) # not present in the manual int dWorldSetStepMemoryReservationPolicy(dWorldID w, const dWorldStepReserveInfo *policyinfo) # not present in the manual int dWorldSetStepMemoryManager(dWorldID w, const dWorldStepMemoryFunctionsInfo *memfuncs) # not present in the manual # TODO: no real idea where dThreadingImplementationID should come from #void dWorldSetStepThreadingImplementation(dWorldID w, const dThreadingFunctionsInfo *functions_info, dThreadingImplementationID threading_impl) void dWorldStep (dWorldID, dReal stepsize) void dWorldQuickStep (dWorldID, dReal stepsize) void dWorldImpulseToForce (dWorldID, dReal stepsize, dReal ix, dReal iy, dReal iz, dVector3 force) void dWorldSetQuickStepNumIterations (dWorldID, int num) int dWorldGetQuickStepNumIterations (dWorldID) void dWorldSetQuickStepW (dWorldID, dReal over_relaxation) dReal dWorldGetQuickStepW (dWorldID) void dWorldSetContactMaxCorrectingVel (dWorldID, dReal vel) dReal dWorldGetContactMaxCorrectingVel (dWorldID) void dWorldSetContactSurfaceLayer (dWorldID, dReal depth) dReal dWorldGetContactSurfaceLayer (dWorldID) dReal dWorldGetAutoDisableLinearThreshold (dWorldID) void dWorldSetAutoDisableLinearThreshold (dWorldID, dReal linear_threshold) dReal dWorldGetAutoDisableAngularThreshold (dWorldID) void dWorldSetAutoDisableAngularThreshold (dWorldID, dReal angular_threshold) # not present in the manual int dWorldGetAutoDisableAverageSamplesCount (dWorldID) void dWorldSetAutoDisableAverageSamplesCount (dWorldID, unsigned int average_samples_count) int dWorldGetAutoDisableSteps (dWorldID) void dWorldSetAutoDisableSteps (dWorldID, int steps) dReal dWorldGetAutoDisableTime (dWorldID) void dWorldSetAutoDisableTime (dWorldID, dReal time) int dWorldGetAutoDisableFlag (dWorldID) void dWorldSetAutoDisableFlag (dWorldID, int do_auto_disable) dReal dWorldGetLinearDampingThreshold (dWorldID w) void dWorldSetLinearDampingThreshold(dWorldID w, dReal threshold) dReal dWorldGetAngularDampingThreshold (dWorldID w) void dWorldSetAngularDampingThreshold(dWorldID w, dReal threshold) dReal dWorldGetLinearDamping (dWorldID) void dWorldSetLinearDamping (dWorldID, dReal scale) dReal dWorldGetAngularDamping (dWorldID) void dWorldSetAngularDamping (dWorldID, dReal scale) void dWorldSetDamping(dWorldID w, dReal linear_scale, dReal angular_scale) dReal dWorldGetMaxAngularSpeed (dWorldID w) void dWorldSetMaxAngularSpeed (dWorldID w, dReal max_speed) # Body dReal dBodyGetAutoDisableLinearThreshold (dBodyID) void dBodySetAutoDisableLinearThreshold (dBodyID, dReal linear_average_threshold) dReal dBodyGetAutoDisableAngularThreshold (dBodyID) void dBodySetAutoDisableAngularThreshold (dBodyID, dReal angular_average_threshold) int dBodyGetAutoDisableAverageSamplesCount (dBodyID) void dBodySetAutoDisableAverageSamplesCount (dBodyID, unsigned int average_samples_count) int dBodyGetAutoDisableSteps (dBodyID) void dBodySetAutoDisableSteps (dBodyID, int steps) dReal dBodyGetAutoDisableTime (dBodyID) void dBodySetAutoDisableTime (dBodyID, dReal time) int dBodyGetAutoDisableFlag (dBodyID) void dBodySetAutoDisableFlag (dBodyID, int do_auto_disable) void dBodySetAutoDisableDefaults (dBodyID) dWorldID dBodyGetWorld (dBodyID) dBodyID dBodyCreate (dWorldID) void dBodyDestroy (dBodyID) void dBodySetData (dBodyID, void *data) void *dBodyGetData (dBodyID) void dBodySetPosition (dBodyID, dReal x, dReal y, dReal z) void dBodySetRotation (dBodyID, dMatrix3 R) void dBodySetQuaternion (dBodyID, dQuaternion q) void dBodySetLinearVel (dBodyID, dReal x, dReal y, dReal z) void dBodySetAngularVel (dBodyID, dReal x, dReal y, dReal z) dReal * dBodyGetPosition (dBodyID) void dBodyCopyPosition (dBodyID body, dVector3 pos) dReal * dBodyGetRotation (dBodyID) void dBodyCopyRotation (dBodyID, dMatrix3 R) dReal * dBodyGetQuaternion (dBodyID) void dBodyCopyQuaternion(dBodyID body, dQuaternion quat) dReal * dBodyGetLinearVel (dBodyID) dReal * dBodyGetAngularVel (dBodyID) void dBodySetMass (dBodyID, dMass *mass) void dBodyGetMass (dBodyID, dMass *mass) void dBodyAddForce (dBodyID, dReal fx, dReal fy, dReal fz) void dBodyAddTorque (dBodyID, dReal fx, dReal fy, dReal fz) void dBodyAddRelForce (dBodyID, dReal fx, dReal fy, dReal fz) void dBodyAddRelTorque (dBodyID, dReal fx, dReal fy, dReal fz) void dBodyAddForceAtPos (dBodyID, dReal fx, dReal fy, dReal fz, dReal px, dReal py, dReal pz) void dBodyAddForceAtRelPos (dBodyID, dReal fx, dReal fy, dReal fz, dReal px, dReal py, dReal pz) void dBodyAddRelForceAtPos (dBodyID, dReal fx, dReal fy, dReal fz, dReal px, dReal py, dReal pz) void dBodyAddRelForceAtRelPos (dBodyID, dReal fx, dReal fy, dReal fz, dReal px, dReal py, dReal pz) dReal * dBodyGetForce (dBodyID) dReal * dBodyGetTorque (dBodyID) void dBodySetForce(dBodyID, dReal x, dReal y, dReal z) void dBodySetTorque(dBodyID, dReal x, dReal y, dReal z) void dBodyGetRelPointPos (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodyGetRelPointVel (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodyGetPointVel (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodyGetPosRelPoint (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodyVectorToWorld (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodyVectorFromWorld (dBodyID, dReal px, dReal py, dReal pz, dVector3 result) void dBodySetFiniteRotationMode (dBodyID, int mode) void dBodySetFiniteRotationAxis (dBodyID, dReal x, dReal y, dReal z) int dBodyGetFiniteRotationMode (dBodyID) void dBodyGetFiniteRotationAxis (dBodyID, dVector3 result) int dBodyGetNumJoints (dBodyID b) dJointID dBodyGetJoint (dBodyID, int index) void dBodySetDynamic (dBodyID) void dBodySetKinematic (dBodyID) int dBodyIsKinematic (dBodyID) void dBodyEnable (dBodyID) void dBodyDisable (dBodyID) int dBodyIsEnabled (dBodyID) void dBodySetGravityMode (dBodyID b, int mode) int dBodyGetGravityMode (dBodyID b) void dBodySetMovedCallback(dBodyID b, void (*callback)(dBodyID)) dGeomID dBodyGetFirstGeom (dBodyID b) dGeomID dBodyGetNextGeom (dGeomID g) void dBodySetDampingDefaults(dBodyID b) dReal dBodyGetLinearDamping (dBodyID b) void dBodySetLinearDamping(dBodyID b, dReal scale) dReal dBodyGetAngularDamping (dBodyID b) void dBodySetAngularDamping(dBodyID b, dReal scale) void dBodySetDamping(dBodyID b, dReal linear_scale, dReal angular_scale) dReal dBodyGetLinearDampingThreshold (dBodyID b) void dBodySetLinearDampingThreshold(dBodyID b, dReal threshold) dReal dBodyGetAngularDampingThreshold (dBodyID b) void dBodySetAngularDampingThreshold(dBodyID b, dReal threshold) dReal dBodyGetMaxAngularSpeed (dBodyID b) void dBodySetMaxAngularSpeed(dBodyID b, dReal max_speed) # not present in the manual int dBodyGetGyroscopicMode(dBodyID b); void dBodySetGyroscopicMode(dBodyID b, int enabled); # Joints dJointID dJointCreateBall (dWorldID, dJointGroupID) dJointID dJointCreateHinge (dWorldID, dJointGroupID) dJointID dJointCreateSlider (dWorldID, dJointGroupID) dJointID dJointCreateContact (dWorldID, dJointGroupID, dContact *) dJointID dJointCreateHinge2 (dWorldID, dJointGroupID) dJointID dJointCreateUniversal (dWorldID, dJointGroupID) dJointID dJointCreatePR (dWorldID, dJointGroupID) dJointID dJointCreatePU (dWorldID, dJointGroupID) dJointID dJointCreatePiston (dWorldID, dJointGroupID) dJointID dJointCreateFixed (dWorldID, dJointGroupID) dJointID dJointCreateNull (dWorldID, dJointGroupID) dJointID dJointCreateAMotor (dWorldID, dJointGroupID) dJointID dJointCreateLMotor (dWorldID, dJointGroupID) dJointID dJointCreatePlane2D (dWorldID, dJointGroupID) dJointID dJointCreateDBall (dWorldID, dJointGroupID) dJointID dJointCreateDHinge (dWorldID, dJointGroupID) dJointID dJointCreateTransmission (dWorldID, dJointGroupID) void dJointDestroy (dJointID) dJointGroupID dJointGroupCreate (int max_size) void dJointGroupDestroy (dJointGroupID) void dJointGroupEmpty (dJointGroupID) int dJointGetNumBodies(dJointID) void dJointAttach (dJointID, dBodyID body1, dBodyID body2) void dJointEnable (dJointID) void dJointDisable (dJointID) int dJointIsEnabled (dJointID) void dJointSetData (dJointID, void *data) void *dJointGetData (dJointID) int dJointGetType (dJointID) dBodyID dJointGetBody (dJointID, int index) void dJointSetFeedback (dJointID, dJointFeedback *) dJointFeedback *dJointGetFeedback (dJointID) void dJointSetBallAnchor (dJointID, dReal x, dReal y, dReal z) void dJointSetBallAnchor2 (dJointID, dReal x, dReal y, dReal z) void dJointSetBallParam (dJointID, int parameter, dReal value) void dJointSetHingeAnchor (dJointID, dReal x, dReal y, dReal z) void dJointSetHingeAnchorDelta (dJointID, dReal x, dReal y, dReal z, dReal ax, dReal ay, dReal az) void dJointSetHingeAxis (dJointID, dReal x, dReal y, dReal z) void dJointSetHingeAxisOffset (dJointID j, dReal x, dReal y, dReal z, dReal angle) void dJointSetHingeParam (dJointID, int parameter, dReal value) void dJointAddHingeTorque(dJointID joint, dReal torque) void dJointSetSliderAxis (dJointID, dReal x, dReal y, dReal z) void dJointSetSliderAxisDelta (dJointID, dReal x, dReal y, dReal z, dReal ax, dReal ay, dReal az) void dJointSetSliderParam (dJointID, int parameter, dReal value) void dJointAddSliderForce(dJointID joint, dReal force) void dJointSetHinge2Anchor (dJointID, dReal x, dReal y, dReal z) void dJointSetHinge2Axes (dJointID j, const dReal *axis1, const dReal *axis2) # ODE_API_DEPRECATED void dJointSetHinge2Axis1 (dJointID, dReal x, dReal y, dReal z) # ODE_API_DEPRECATED void dJointSetHinge2Axis2 (dJointID, dReal x, dReal y, dReal z) void dJointSetHinge2Param (dJointID, int parameter, dReal value) void dJointAddHinge2Torques(dJointID joint, dReal torque1, dReal torque2) void dJointSetUniversalAnchor (dJointID, dReal x, dReal y, dReal z) void dJointSetUniversalAxis1 (dJointID, dReal x, dReal y, dReal z) void dJointSetUniversalAxis1Offset (dJointID, dReal x, dReal y, dReal z, dReal offset1, dReal offset2) void dJointSetUniversalAxis2 (dJointID, dReal x, dReal y, dReal z) void dJointSetUniversalAxis2Offset (dJointID, dReal x, dReal y, dReal z, dReal offset1, dReal offset2) void dJointSetUniversalParam (dJointID, int parameter, dReal value) void dJointAddUniversalTorques(dJointID joint, dReal torque1, dReal torque2) void dJointSetPRAnchor (dJointID, dReal x, dReal y, dReal z) void dJointSetPRAxis1 (dJointID, dReal x, dReal y, dReal z) void dJointSetPRAxis2 (dJointID, dReal x, dReal y, dReal z) void dJointSetPRParam (dJointID, int parameter, dReal value) void dJointAddPRTorque (dJointID j, dReal torque) void dJointSetPUAnchor (dJointID, dReal x, dReal y, dReal z) # ODE_API_DEPRECATED - included for completeness' sake #void dJointSetPUAnchorDelta (dJointID, dReal x, dReal y, dReal z, dReal dx, # dReal dy, dReal dz) void dJointSetPUAnchorOffset (dJointID, dReal x, dReal y, dReal z, dReal dx, dReal dy, dReal dz) void dJointSetPUAxis1 (dJointID, dReal x, dReal y, dReal z) void dJointSetPUAxis2 (dJointID, dReal x, dReal y, dReal z) void dJointSetPUAxis3 (dJointID, dReal x, dReal y, dReal z) void dJointSetPUAxisP (dJointID id, dReal x, dReal y, dReal z) void dJointSetPUParam (dJointID, int parameter, dReal value) void dJointAddPUTorque (dJointID j, dReal torque) void dJointSetPistonAnchor (dJointID, dReal x, dReal y, dReal z) void dJointSetPistonAnchorOffset(dJointID j, dReal x, dReal y, dReal z, dReal dx, dReal dy, dReal dz) void dJointSetPistonAxis (dJointID, dReal x, dReal y, dReal z) # ODE_API_DEPRECATED - included for completeness' sake #void dJointSetPistonAxisDelta (dJointID j, dReal x, dReal y, dReal z, # dReal ax, dReal ay, dReal az) void dJointSetPistonParam (dJointID, int parameter, dReal value) void dJointAddPistonForce (dJointID joint, dReal force) void dJointSetFixed (dJointID) void dJointSetFixedParam (dJointID, int parameter, dReal value) void dJointSetAMotorNumAxes (dJointID, int num) void dJointSetAMotorAxis (dJointID, int anum, int rel, dReal x, dReal y, dReal z) void dJointSetAMotorAngle (dJointID, int anum, dReal angle) void dJointSetAMotorParam (dJointID, int parameter, dReal value) void dJointSetAMotorMode (dJointID, int mode) void dJointAddAMotorTorques (dJointID, dReal torque1, dReal torque2, dReal torque3) void dJointSetLMotorNumAxes (dJointID, int num) void dJointSetLMotorAxis (dJointID, int anum, int rel, dReal x, dReal y, dReal z) void dJointSetLMotorParam (dJointID, int parameter, dReal value) void dJointSetPlane2DXParam (dJointID, int parameter, dReal value) void dJointSetPlane2DYParam (dJointID, int parameter, dReal value) void dJointSetPlane2DAngleParam (dJointID, int parameter, dReal value) void dJointGetBallAnchor (dJointID, dVector3 result) void dJointGetBallAnchor2 (dJointID, dVector3 result) dReal dJointGetBallParam (dJointID, int parameter) void dJointGetHingeAnchor (dJointID, dVector3 result) void dJointGetHingeAnchor2 (dJointID, dVector3 result) void dJointGetHingeAxis (dJointID, dVector3 result) dReal dJointGetHingeParam (dJointID, int parameter) dReal dJointGetHingeAngle (dJointID) dReal dJointGetHingeAngleRate (dJointID) dReal dJointGetSliderPosition (dJointID) dReal dJointGetSliderPositionRate (dJointID) void dJointGetSliderAxis (dJointID, dVector3 result) dReal dJointGetSliderParam (dJointID, int parameter) void dJointGetHinge2Anchor (dJointID, dVector3 result) void dJointGetHinge2Anchor2 (dJointID, dVector3 result) void dJointGetHinge2Axis1 (dJointID, dVector3 result) void dJointGetHinge2Axis2 (dJointID, dVector3 result) dReal dJointGetHinge2Param (dJointID, int parameter) dReal dJointGetHinge2Angle1 (dJointID) dReal dJointGetHinge2Angle2 (dJointID); dReal dJointGetHinge2Angle1Rate (dJointID) dReal dJointGetHinge2Angle2Rate (dJointID) void dJointGetUniversalAnchor (dJointID, dVector3 result) void dJointGetUniversalAnchor2 (dJointID, dVector3 result) void dJointGetUniversalAxis1 (dJointID, dVector3 result) void dJointGetUniversalAxis2 (dJointID, dVector3 result) dReal dJointGetUniversalParam (dJointID, int parameter) void dJointGetUniversalAngles (dJointID, dReal *angle1, dReal *angle2) dReal dJointGetUniversalAngle1 (dJointID) dReal dJointGetUniversalAngle2 (dJointID) dReal dJointGetUniversalAngle1Rate (dJointID) dReal dJointGetUniversalAngle2Rate (dJointID) dReal dJointGetPRPosition (dJointID) dReal dJointGetPRPositionRate (dJointID) dReal dJointGetPRAngle (dJointID) dReal dJointGetPRAngleRate (dJointID) void dJointGetPRAxis1 (dJointID, dVector3 result) void dJointGetPRAxis2 (dJointID, dVector3 result) dReal dJointGetPRParam (dJointID, int parameter) void dJointGetPUAnchor (dJointID, dVector3 result) dReal dJointGetPUPosition (dJointID) dReal dJointGetPUPositionRate (dJointID) void dJointGetPUAxis1 (dJointID, dVector3 result) void dJointGetPUAxis2 (dJointID, dVector3 result) void dJointGetPUAxis3 (dJointID, dVector3 result) void dJointGetPUAxisP (dJointID id, dVector3 result) void dJointGetPUAngles (dJointID, dReal *angle1, dReal *angle2) dReal dJointGetPUAngle1 (dJointID) dReal dJointGetPUAngle1Rate (dJointID) dReal dJointGetPUAngle2 (dJointID) dReal dJointGetPUAngle2Rate (dJointID) dReal dJointGetPUParam (dJointID, int parameter) dReal dJointGetPistonPosition (dJointID) dReal dJointGetPistonPositionRate (dJointID) dReal dJointGetPistonAngle (dJointID) dReal dJointGetPistonAngleRate (dJointID) void dJointGetPistonAnchor (dJointID, dVector3 result) void dJointGetPistonAnchor2 (dJointID, dVector3 result) void dJointGetPistonAxis (dJointID, dVector3 result) dReal dJointGetPistonParam (dJointID, int parameter) int dJointGetAMotorNumAxes (dJointID) void dJointGetAMotorAxis (dJointID, int anum, dVector3 result) int dJointGetAMotorAxisRel (dJointID, int anum) dReal dJointGetAMotorAngle (dJointID, int anum) dReal dJointGetAMotorAngleRate (dJointID, int anum) dReal dJointGetAMotorParam (dJointID, int parameter) int dJointGetAMotorMode (dJointID) int dJointGetLMotorNumAxes (dJointID) void dJointGetLMotorAxis (dJointID, int anum, dVector3 result) dReal dJointGetLMotorParam (dJointID, int parameter) dReal dJointGetFixedParam (dJointID, int parameter) void dJointGetTransmissionContactPoint1(dJointID, dVector3 result) void dJointGetTransmissionContactPoint2(dJointID, dVector3 result) void dJointSetTransmissionAxis1(dJointID, dReal x, dReal y, dReal z) void dJointGetTransmissionAxis1(dJointID, dVector3 result) void dJointSetTransmissionAxis2(dJointID, dReal x, dReal y, dReal z) void dJointGetTransmissionAxis2(dJointID, dVector3 result) void dJointSetTransmissionAnchor1(dJointID, dReal x, dReal y, dReal z) void dJointGetTransmissionAnchor1(dJointID, dVector3 result) void dJointSetTransmissionAnchor2(dJointID, dReal x, dReal y, dReal z) void dJointGetTransmissionAnchor2(dJointID, dVector3 result) void dJointSetTransmissionParam(dJointID, int parameter, dReal value) dReal dJointGetTransmissionParam(dJointID, int parameter) void dJointSetTransmissionMode( dJointID j, int mode ) int dJointGetTransmissionMode( dJointID j ) void dJointSetTransmissionRatio( dJointID j, dReal ratio ) dReal dJointGetTransmissionRatio( dJointID j ) void dJointSetTransmissionAxis( dJointID j, dReal x, dReal y, dReal z ) void dJointGetTransmissionAxis( dJointID j, dVector3 result ) dReal dJointGetTransmissionAngle1( dJointID j ) dReal dJointGetTransmissionAngle2( dJointID j ) dReal dJointGetTransmissionRadius1( dJointID j ) dReal dJointGetTransmissionRadius2( dJointID j ) void dJointSetTransmissionRadius1( dJointID j, dReal radius ) void dJointSetTransmissionRadius2( dJointID j, dReal radius ) dReal dJointGetTransmissionBacklash( dJointID j ) void dJointSetTransmissionBacklash( dJointID j, dReal backlash ) void dJointSetDBallAnchor1(dJointID, dReal x, dReal y, dReal z) void dJointSetDBallAnchor2(dJointID, dReal x, dReal y, dReal z) void dJointGetDBallAnchor1(dJointID, dVector3 result) void dJointGetDBallAnchor2(dJointID, dVector3 result) dReal dJointGetDBallDistance(dJointID) void dJointSetDBallDistance(dJointID, dReal dist) void dJointSetDBallParam(dJointID, int parameter, dReal value) dReal dJointGetDBallParam(dJointID, int parameter) void dJointSetDHingeAxis(dJointID, dReal x, dReal y, dReal z) void dJointGetDHingeAxis(dJointID, dVector3 result) void dJointSetDHingeAnchor1(dJointID, dReal x, dReal y, dReal z) void dJointSetDHingeAnchor2(dJointID, dReal x, dReal y, dReal z) void dJointGetDHingeAnchor1(dJointID, dVector3 result) void dJointGetDHingeAnchor2(dJointID, dVector3 result) dReal dJointGetDHingeDistance(dJointID) void dJointSetDHingeParam(dJointID, int parameter, dReal value) dReal dJointGetDHingeParam(dJointID, int parameter) dJointID dConnectingJoint (dBodyID, dBodyID) int dConnectingJointList (dBodyID, dBodyID, dJointID*) int dAreConnected (dBodyID, dBodyID) int dAreConnectedExcluding (dBodyID body1, dBodyID body2, int joint_type) # Mass void dMassSetZero (dMass *) void dMassSetParameters (dMass *, dReal themass, dReal cgx, dReal cgy, dReal cgz, dReal I11, dReal I22, dReal I33, dReal I12, dReal I13, dReal I23) void dMassSetSphere (dMass *, dReal density, dReal radius) void dMassSetSphereTotal (dMass *, dReal total_mass, dReal radius) void dMassSetCappedCylinder (dMass *, dReal density, int direction, dReal a, dReal b) void dMassSetCappedCylinderTotal (dMass *, dReal total_mass, int direction, dReal a, dReal b) void dMassSetCylinder (dMass *, dReal density, int direction, dReal radius, dReal length) void dMassSetCylinderTotal (dMass *, dReal total_mass, int direction, dReal radius, dReal length) void dMassSetBox (dMass *, dReal density, dReal lx, dReal ly, dReal lz) void dMassSetBoxTotal (dMass *, dReal total_mass, dReal lx, dReal ly, dReal lz) void dMassAdjust (dMass *, dReal newmass) void dMassTranslate (dMass *, dReal x, dReal y, dReal z) void dMassRotate (dMass *, dMatrix3 R) void dMassAdd (dMass *a, dMass *b) # Space dSpaceID dSimpleSpaceCreate(dSpaceID space) dSpaceID dHashSpaceCreate(dSpaceID space) dSpaceID dQuadTreeSpaceCreate (dSpaceID space, dVector3 Center, dVector3 Extents, int Depth) # not present in the manual #define dSAP_AXES_XYZ ((0)|(1<<2)|(2<<4)) - 0 | 100 | 110000 = 110100 = 4 + 16 + 32 = 52 #define dSAP_AXES_XZY ((0)|(2<<2)|(1<<4)) - 0 | 1000 | 10000 = 11000 = 8 + 16 = 24 #define dSAP_AXES_YXZ ((1)|(0<<2)|(2<<4)) - 1 | 000 | 100000 = 100001 = 1 + 32 = 33 #define dSAP_AXES_YZX ((1)|(2<<2)|(0<<4)) - 1 | 1000 | 00000 = 01001 = 1 + 8 = 9 #define dSAP_AXES_ZXY ((2)|(0<<2)|(1<<4)) - 10 | 000 | 10000 = 10010 = 2 + 16 = 18 #define dSAP_AXES_ZYX ((2)|(1<<2)|(0<<4)) - 10 | 100 | 00000 = 00110 = 2 + 4 = 6 dSpaceID dSweepAndPruneSpaceCreate(dSpaceID space, int axisorder) void dSpaceDestroy (dSpaceID) void dHashSpaceSetLevels (dSpaceID space, int minlevel, int maxlevel) void dHashSpaceGetLevels (dSpaceID space, int *minlevel, int *maxlevel) void dSpaceSetCleanup (dSpaceID space, int mode) int dSpaceGetCleanup (dSpaceID space) void dSpaceSetSublevel (dSpaceID space, int sublevel) int dSpaceGetSublevel (dSpaceID space) # not present in the manual void dSpaceSetManualCleanup (dSpaceID space, int mode) int dSpaceGetManualCleanup (dSpaceID space) void dSpaceAdd (dSpaceID, dGeomID) void dSpaceRemove (dSpaceID, dGeomID) int dSpaceQuery (dSpaceID, dGeomID) # not present in the manual void dSpaceClean (dSpaceID) int dSpaceGetNumGeoms (dSpaceID) dGeomID dSpaceGetGeom (dSpaceID, int i) int dSpaceGetClass(dSpaceID space) # Collision Detection int dCollide (dGeomID o1, dGeomID o2, int flags, dContactGeom *contact, int skip) void dSpaceCollide (dSpaceID space, void *data, dNearCallback *callback) void dSpaceCollide2 (dGeomID o1, dGeomID o2, void *data, dNearCallback *callback) # Geom void dGeomDestroy (dGeomID) void dGeomSetData (dGeomID, void *) void *dGeomGetData (dGeomID) void dGeomSetBody (dGeomID, dBodyID) dBodyID dGeomGetBody (dGeomID) void dGeomSetPosition (dGeomID, dReal x, dReal y, dReal z) void dGeomSetRotation (dGeomID, dMatrix3 R) void dGeomSetQuaternion (dGeomID, dQuaternion) dReal * dGeomGetPosition (dGeomID) dReal * dGeomGetRotation (dGeomID) void dGeomGetQuaternion (dGeomID, dQuaternion result) # not present in the manual void dGeomCopyPosition (dGeomID geom, dVector3 pos) void dGeomCopyRotation(dGeomID geom, dMatrix3 R) void dGeomGetAABB (dGeomID, dReal aabb[6]) int dGeomIsSpace (dGeomID) dSpaceID dGeomGetSpace (dGeomID) int dGeomGetClass (dGeomID) void dGeomSetCategoryBits(dGeomID, unsigned long bits) void dGeomSetCollideBits(dGeomID, unsigned long bits) unsigned long dGeomGetCategoryBits(dGeomID) unsigned long dGeomGetCollideBits(dGeomID) void dGeomEnable (dGeomID) void dGeomDisable (dGeomID) int dGeomIsEnabled (dGeomID) # not present in the manual int dGeomLowLevelControl (dGeomID geom, int controlClass, int controlCode, void *dataValue, int *dataSize) # not present in the manual void dGeomGetRelPointPos (dGeomID geom, dReal px, dReal py, dReal pz, dVector3 result) void dGeomGetPosRelPoint (dGeomID geom, dReal px, dReal py, dReal pz, dVector3 result) # not present in the manual void dGeomVectorToWorld (dGeomID geom, dReal px, dReal py, dReal pz, dVector3 result) void dGeomVectorFromWorld (dGeomID geom, dReal px, dReal py, dReal pz, dVector3 result) void dGeomSetOffsetPosition (dGeomID geom, dReal x, dReal y, dReal z) void dGeomSetOffsetRotation (dGeomID geom, const dMatrix3 R) void dGeomSetOffsetQuaternion (dGeomID geom, const dQuaternion Q) void dGeomSetOffsetWorldPosition (dGeomID geom, dReal x, dReal y, dReal z) void dGeomSetOffsetWorldRotation (dGeomID geom, const dMatrix3 R) void dGeomSetOffsetWorldQuaternion (dGeomID geom, const dQuaternion) void dGeomClearOffset(dGeomID geom) # not present in the manual int dGeomIsOffset(dGeomID geom) const dReal * dGeomGetOffsetPosition (dGeomID geom) const dReal * dGeomGetOffsetRotation (dGeomID geom) void dGeomGetOffsetQuaternion (dGeomID geom, dQuaternion result) # not present in the manual void dGeomCopyOffsetPosition (dGeomID geom, dVector3 pos) void dGeomCopyOffsetRotation (dGeomID geom, dMatrix3 R) # Sphere dGeomID dCreateSphere (dSpaceID space, dReal radius) void dGeomSphereSetRadius (dGeomID sphere, dReal radius) dReal dGeomSphereGetRadius (dGeomID sphere) dReal dGeomSpherePointDepth (dGeomID sphere, dReal x, dReal y, dReal z) # Convex dGeomID dCreateConvex (dSpaceID space, const dReal *_planes, unsigned int _planecount, const dReal *_points, unsigned int _pointcount, const unsigned int *_polygons) void dGeomSetConvex (dGeomID g, const dReal *_planes, unsigned int _count, const dReal *_points, unsigned int _pointcount, const unsigned int *_polygons) # Box dGeomID dCreateBox (dSpaceID space, dReal lx, dReal ly, dReal lz) void dGeomBoxSetLengths (dGeomID box, dReal lx, dReal ly, dReal lz) void dGeomBoxGetLengths (dGeomID box, dVector3 result) dReal dGeomBoxPointDepth (dGeomID box, dReal x, dReal y, dReal z) # Plane dGeomID dCreatePlane (dSpaceID space, dReal a, dReal b, dReal c, dReal d) void dGeomPlaneSetParams (dGeomID plane, dReal a, dReal b, dReal c, dReal d) void dGeomPlaneGetParams (dGeomID plane, dVector4 result) dReal dGeomPlanePointDepth (dGeomID plane, dReal x, dReal y, dReal z) # Capsule dGeomID dCreateCapsule (dSpaceID space, dReal radius, dReal length) void dGeomCapsuleSetParams (dGeomID ccylinder, dReal radius, dReal length) void dGeomCapsuleGetParams (dGeomID ccylinder, dReal *radius, dReal *length) dReal dGeomCapsulePointDepth (dGeomID ccylinder, dReal x, dReal y, dReal z) # Cylinder dGeomID dCreateCylinder (dSpaceID space, dReal radius, dReal length) void dGeomCylinderSetParams (dGeomID ccylinder, dReal radius, dReal length) void dGeomCylinderGetParams (dGeomID ccylinder, dReal *radius, dReal *length) # Ray dGeomID dCreateRay (dSpaceID space, dReal length) void dGeomRaySetLength (dGeomID ray, dReal length) dReal dGeomRayGetLength (dGeomID ray) void dGeomRaySet (dGeomID ray, dReal px, dReal py, dReal pz, dReal dx, dReal dy, dReal dz) void dGeomRayGet (dGeomID ray, dVector3 start, dVector3 dir) void dGeomRaySetFirstContact (dGeomID g, int firstContact) int dGeomRayGetFirstContact (dGeomID g) void dGeomRaySetBackfaceCull (dGeomID g, int backfaceCull) int dGeomRayGetBackfaceCull (dGeomID g) void dGeomRaySetClosestHit (dGeomID g, int closestHit) int dGeomRayGetClosestHit (dGeomID g) # Heightfield dGeomID dCreateHeightfield (dSpaceID space, dHeightfieldDataID data, int bPlaceable) dHeightfieldDataID dGeomHeightfieldDataCreate() void dGeomHeightfieldDataDestroy(dHeightfieldDataID g) void dGeomHeightfieldDataBuildCallback(dHeightfieldDataID d, void* pUserData, dHeightfieldGetHeight* pCallback, dReal width, dReal depth, int widthSamples, int depthSamples, dReal scale, dReal offset, dReal thickness, int bWrap) void dGeomHeightfieldDataBuildByte( dHeightfieldDataID d, const unsigned char* pHeightData, int bCopyHeightData, dReal width, dReal depth, int widthSamples, int depthSamples, dReal scale, dReal offset, dReal thickness, int bWrap ) void dGeomHeightfieldDataBuildShort( dHeightfieldDataID d, const short* pHeightData, int bCopyHeightData, dReal width, dReal depth, int widthSamples, int depthSamples, dReal scale, dReal offset, dReal thickness, int bWrap ) void dGeomHeightfieldDataBuildSingle( dHeightfieldDataID d, const float* pHeightData, int bCopyHeightData, dReal width, dReal depth, int widthSamples, int depthSamples, dReal scale, dReal offset, dReal thickness, int bWrap ) void dGeomHeightfieldDataBuildDouble( dHeightfieldDataID d, const double* pHeightData, int bCopyHeightData, dReal width, dReal depth, int widthSamples, int depthSamples, dReal scale, dReal offset, dReal thickness, int bWrap ) void dGeomHeightfieldDataSetBounds( dHeightfieldDataID d, dReal minHeight, dReal maxHeight ) void dGeomHeightfieldSetHeightfieldData( dGeomID g, dHeightfieldDataID d ) dHeightfieldDataID dGeomHeightfieldGetHeightfieldData( dGeomID g ) # Utility void dClosestLineSegmentPoints (const dVector3 a1, const dVector3 a2, const dVector3 b1, const dVector3 b2, dVector3 cp1, dVector3 cp2) int dBoxTouchesBox (const dVector3 _p1, const dMatrix3 R1, const dVector3 side1, const dVector3 _p2, const dMatrix3 R2, const dVector3 side2) int dBoxBox (const dVector3 p1, const dMatrix3 R1, const dVector3 side1, const dVector3 p2, const dMatrix3 R2, const dVector3 side2, dVector3 normal, dReal *depth, int *return_code, int flags, dContactGeom *contact, int skip) void dInfiniteAABB (dGeomID geom, dReal aabb[6]) int dCreateGeomClass (const dGeomClass *classptr) void * dGeomGetClassData (dGeomID) dGeomID dCreateGeom (int classnum) void dSetColliderOverride (int i, int j, dColliderFn *fn) # ???? dGeomID dCreateGeomGroup (dSpaceID space) dReal *dGeomGetSpaceAABB (dGeomID) void dGeomGroupAdd (dGeomID group, dGeomID x) void dGeomGroupRemove (dGeomID group, dGeomID x) int dGeomGroupGetNumGeoms (dGeomID group) dGeomID dGeomGroupGetGeom (dGeomID group, int i) dGeomID dCreateGeomTransform (dSpaceID space) void dGeomTransformSetGeom (dGeomID g, dGeomID obj) dGeomID dGeomTransformGetGeom (dGeomID g) void dGeomTransformSetCleanup (dGeomID g, int mode) int dGeomTransformGetCleanup (dGeomID g) void dGeomTransformSetInfo (dGeomID g, int mode) int dGeomTransformGetInfo (dGeomID g) # Trimesh dTriMeshDataID dGeomTriMeshDataCreate() void dGeomTriMeshDataDestroy(dTriMeshDataID g) void dGeomTriMeshDataBuildSingle1 (dTriMeshDataID g, void* Vertices, int VertexStride, int VertexCount, void* Indices, int IndexCount, int TriStride, void* Normals) void dGeomTriMeshDataBuildSimple(dTriMeshDataID g, dReal* Vertices, int VertexCount, int* Indices, int IndexCount) dGeomID dCreateTriMesh (dSpaceID space, dTriMeshDataID Data, void* Callback, void* ArrayCallback, void* RayCallback) void dGeomTriMeshSetData (dGeomID g, dTriMeshDataID Data) void dGeomTriMeshClearTCCache (dGeomID g) void dGeomTriMeshGetTriangle (dGeomID g, int Index, dVector3 *v0, dVector3 *v1, dVector3 *v2) int dGeomTriMeshGetTriangleCount (dGeomID g) void dGeomTriMeshGetPoint (dGeomID g, int Index, dReal u, dReal v, dVector3 Out) void dGeomTriMeshEnableTC(dGeomID g, int geomClass, int enable) int dGeomTriMeshIsTCEnabled(dGeomID g, int geomClass) Py3ODE-1.2.0.dev15/src/geomobject.pyx000077500000000000000000000267131364423331700171310ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # Each geom object has to insert itself into the global dictionary # _geom_c2py_lut (key:address - value:Python object). # This lookup table is used in the near callback to translate the C # pointers into corresponding Python wrapper objects. # # Additionally, each geom object must have a method _id() that returns # the ODE geom id. This is used during collision detection. # # ########################## # # Obsolete: # # # # Each geom object has to register itself at its space as the # # space keeps a dictionary that's used as lookup table to translate # # C pointers into Python objects (this is used in the near callback). # Geom base class cdef class GeomObject: """This is the abstract base class for all geom objects. """ # The id of the geom object as returned by dCreateXxxx() cdef dGeomID gid # The space in which the geom was placed (or None). This reference # is kept so that the space won't be destroyed while there are still # geoms around that might use it. cdef object space # The body that the geom was attached to (or None). cdef object body # A dictionary with user defined attributes cdef public object attribs cdef object __weakref__ def __cinit__(self, *a, **kw): self.gid = NULL self.space = None self.body = None self.attribs = {} def __init__(self, *a, **kw): raise NotImplementedError, "The GeomObject base class can't be used directly." def __dealloc__(self): if self.gid!=NULL: dGeomDestroy(self.gid) self.gid = NULL def __getattr__(self, name): if name in self.attribs: return self.attribs[name] else: raise AttributeError, "geom has no attribute '%s'."%name def __setattr__(self, name, val): self.attribs[name]=val def __delattr__(self, name): if name in self.attribs: del self.attribs[name] else: raise AttributeError, "geom has no attribute '%s'."%name def _id(self): """_id() -> int Return the internal id of the geom (dGeomID) as returned by the dCreateXyz() functions. This method has to be overwritten in derived methods. """ raise NotImplementedError, "Bug: The _id() method is not implemented." def placeable(self): """placeable() -> bool Returns True if the geom object is a placeable geom. This method has to be overwritten in derived methods. """ return False def setBody(self, Body body): """setBody(body) Set the body associated with a placeable geom. @param body: The Body object or None. @type body: Body """ if not self.placeable(): raise ValueError, "Non-placeable geoms cannot have a body associated to them." if body==None: dGeomSetBody(self.gid, NULL) else: dGeomSetBody(self.gid, body.bid) self.body = body def getBody(self): """getBody() -> Body Get the body associated with this geom. """ if not self.placeable(): return environment return self.body def setPosition(self, pos): """setPosition(pos) Set the position of the geom. If the geom is attached to a body, the body's position will also be changed. @param pos: Position @type pos: 3-sequence of floats """ if not self.placeable(): raise ValueError, "Cannot set a position on non-placeable geoms." dGeomSetPosition(self.gid, pos[0], pos[1], pos[2]) def getPosition(self): """getPosition() -> 3-tuple Get the current position of the geom. If the geom is attached to a body the returned value is the body's position. """ if not self.placeable(): raise ValueError, "Non-placeable geoms do not have a position." cdef dReal* p p = dGeomGetPosition(self.gid) return (p[0],p[1],p[2]) def setRotation(self, R): """setRotation(R) Set the orientation of the geom. If the geom is attached to a body, the body's orientation will also be changed. @param R: Rotation matrix @type R: 9-sequence of floats """ if not self.placeable(): raise ValueError, "Cannot set a rotation on non-placeable geoms." cdef dMatrix3 m m[0] = R[0] m[1] = R[1] m[2] = R[2] m[3] = 0 m[4] = R[3] m[5] = R[4] m[6] = R[5] m[7] = 0 m[8] = R[6] m[9] = R[7] m[10] = R[8] m[11] = 0 dGeomSetRotation(self.gid, m) def getRotation(self): """getRotation() -> 9-tuple Get the current orientation of the geom. If the geom is attached to a body the returned value is the body's orientation. """ if not self.placeable(): raise ValueError, "Non-placeable geoms do not have a rotation." cdef dReal* m m = dGeomGetRotation(self.gid) return [m[0],m[1],m[2],m[4],m[5],m[6],m[8],m[9],m[10]] def getQuaternion(self): """getQuaternion() -> (w,x,y,z) Get the current orientation of the geom. If the geom is attached to a body the returned value is the body's orientation. """ if not self.placeable(): raise ValueError, "Non-placeable geoms do not have an orientation." cdef dQuaternion q dGeomGetQuaternion(self.gid, q) return (q[0],q[1],q[2],q[3]) def setQuaternion(self, q): """setQuaternion(q) Set the orientation of the geom. If the geom is attached to a body, the body's orientation will also be changed. @param q: Quaternion (w,x,y,z) @type q: 4-sequence of floats """ if not self.placeable(): raise ValueError, "Cannot set a quaternion on non-placeable geoms." cdef dQuaternion cq cq[0] = q[0] cq[1] = q[1] cq[2] = q[2] cq[3] = q[3] dGeomSetQuaternion(self.gid, cq) def getAABB(self): """getAABB() -> 6-tuple Return an axis aligned bounding box that surrounds the geom. The return value is a 6-tuple (minx, maxx, miny, maxy, minz, maxz). """ cdef dReal aabb[6] dGeomGetAABB(self.gid, aabb) return (aabb[0], aabb[1], aabb[2], aabb[3], aabb[4], aabb[5]) def isSpace(self): """isSpace() -> bool Return 1 if the given geom is a space, or 0 if not.""" return dGeomIsSpace(self.gid) def getSpace(self): """getSpace() -> Space Return the space that the given geometry is contained in, or return None if it is not contained in any space.""" return self.space def setCollideBits(self, bits): """setCollideBits(bits) Set the "collide" bitfields for this geom. @param bits: Collide bit field @type bits: int/long """ dGeomSetCollideBits(self.gid, long(bits)) def setCategoryBits(self, bits): """setCategoryBits(bits) Set the "category" bitfields for this geom. @param bits: Category bit field @type bits: int/long """ dGeomSetCategoryBits(self.gid, long(bits)) def getCollideBits(self): """getCollideBits() -> long Return the "collide" bitfields for this geom. """ return dGeomGetCollideBits(self.gid) def getCategoryBits(self): """getCategoryBits() -> long Return the "category" bitfields for this geom. """ return dGeomGetCategoryBits(self.gid) def setOffsetPosition(self, pos): """setOffsetPosition(pos) Set the offset position of a geom. The geom must be attached to a body. If the geom did not have an offset, it is automatically created. This sets up an additional (local) transformation for the geom, since geoms attached to a body share their global position and rotation. To disable the offset call dGeomClearOffset. @param pos: Position @type pos: 3-sequence (tuple) of floats """ dGeomSetOffsetPosition(self.gid, pos[0], pos[1], pos[2]); def setOffsetRotation(self, R): """setOffsetRotation(R) Set the offset rotation of a geom. The geom must be attached to a body. If the geom did not have an offset, it is automatically created. This sets up an additional (local) transformation for the geom, since geoms attached to a body share their global position and rotation. To disable the offset call dGeomClearOffset. @param R: Rotation matrix @type R: 9-sequence (tuple) of floats """ cdef dMatrix3 m m[0] = R[0] m[1] = R[1] m[2] = R[2] m[3] = 0 m[4] = R[3] m[5] = R[4] m[6] = R[5] m[7] = 0 m[8] = R[6] m[9] = R[7] m[10] = R[8] m[11] = 0 dGeomSetOffsetRotation(self.gid, m) def setOffsetQuaternion(self, q): """setOffsetQuaternion(q) Set the offset quaternion of a geom. The geom must be attached to a body. If the geom did not have an offset, it is automatically created. This sets up an additional (local) transformation for the geom, since geoms attached to a body share their global position and rotation. To disable the offset call dGeomClearOffset. @param q: Quaternion (w,x,y,z) @type q: 4-sequence of floats """ cdef dQuaternion cq cq[0] = q[0] cq[1] = q[1] cq[2] = q[2] cq[3] = q[3] dGeomSetOffsetQuaternion(self.gid, cq) def clearOffset(self): """clearOffset() Disable the geom's offset. The geom will be repositioned / oriented at the body's position / orientation. If the geom has no offset, this function does nothing. Note, that this will eliminate the offset and is more efficient than setting the offset to the identity transformation. """ dGeomClearOffset(self.gid) def enable(self): """enable() Enable the geom.""" dGeomEnable(self.gid) def disable(self): """disable() Disable the geom.""" dGeomDisable(self.gid) def isEnabled(self): """isEnabled() -> bool Return True if the geom is enabled.""" return dGeomIsEnabled(self.gid) Py3ODE-1.2.0.dev15/src/geoms.pyx000077500000000000000000000365431364423331700161270ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # The list of geom classes supported in ODE, and whether or not they # are placeable, is at # http://opende.sourceforge.net/wiki/index.php/Manual_%28Collision_Detection%29 # GeomSphere cdef class GeomSphere(GeomObject): """Sphere geometry. This class represents a sphere centered at the origin. Constructor:: GeomSphere(space=None, radius=1.0) """ def __cinit__(self, space=None, radius=1.0): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateSphere(sid, radius) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, radius=1.0): self.space = space self.body = None def placeable(self): return True def _id(self): cdef long id id = self.gid return id def setRadius(self, radius): """setRadius(radius) Set the radius of the sphere. @param radius: New radius @type radius: float """ dGeomSphereSetRadius(self.gid, radius) def getRadius(self): """getRadius() -> float Return the radius of the sphere. """ return dGeomSphereGetRadius(self.gid) def pointDepth(self, p): """pointDepth(p) -> float Return the depth of the point p in the sphere. Points inside the geom will have positive depth, points outside it will have negative depth, and points on the surface will have zero depth. @param p: Point @type p: 3-sequence of floats """ return dGeomSpherePointDepth(self.gid, p[0], p[1], p[2]) # GeomBox cdef class GeomBox(GeomObject): """Box geometry. This class represents a box centered at the origin. Constructor:: GeomBox(space=None, lengths=(1.0, 1.0, 1.0)) """ def __cinit__(self, space=None, lengths=(1.0, 1.0, 1.0)): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateBox(sid, lengths[0],lengths[1],lengths[2]) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, lengths=(1.0, 1.0, 1.0)): self.space = space self.body = None def placeable(self): return True def _id(self): cdef long id id = self.gid return id def setLengths(self, lengths): dGeomBoxSetLengths(self.gid, lengths[0], lengths[1], lengths[2]) def getLengths(self): cdef dVector3 res dGeomBoxGetLengths(self.gid, res) return (res[0], res[1], res[2]) def pointDepth(self, p): """pointDepth(p) -> float Return the depth of the point p in the box. Points inside the geom will have positive depth, points outside it will have negative depth, and points on the surface will have zero depth. @param p: Point @type p: 3-sequence of floats """ return dGeomBoxPointDepth(self.gid, p[0], p[1], p[2]) # GeomPlane cdef class GeomPlane(GeomObject): """Plane geometry. This class represents an infinite plane. The plane equation is: n.x*x + n.y*y + n.z*z = dist This object can't be attached to a body. If you call getBody() on this object it always returns ode.environment. Constructor:: GeomPlane(space=None, normal=(0,0,1), dist=0) """ def __cinit__(self, space=None, normal=(0,0,1), dist=0): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreatePlane(sid, normal[0], normal[1], normal[2], dist) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, normal=(0,0,1), dist=0): self.space = space def _id(self): cdef long id id = self.gid return id def setParams(self, normal, dist): dGeomPlaneSetParams(self.gid, normal[0], normal[1], normal[2], dist) def getParams(self): cdef dVector4 res dGeomPlaneGetParams(self.gid, res) return ((res[0], res[1], res[2]), res[3]) def pointDepth(self, p): """pointDepth(p) -> float Return the depth of the point p in the plane. Points inside the geom will have positive depth, points outside it will have negative depth, and points on the surface will have zero depth. @param p: Point @type p: 3-sequence of floats """ return dGeomPlanePointDepth(self.gid, p[0], p[1], p[2]) # GeomCapsule cdef class GeomCapsule(GeomObject): """Capped cylinder geometry. This class represents a capped cylinder aligned along the local Z axis and centered at the origin. Constructor:: GeomCapsule(space=None, radius=0.5, length=1.0) The length parameter does not include the caps. """ def __cinit__(self, space=None, radius=0.5, length=1.0): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateCapsule(sid, radius, length) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, radius=0.5, length=1.0): self.space = space self.body = None def placeable(self): return True def _id(self): cdef long id id = self.gid return id def setParams(self, radius, length): dGeomCapsuleSetParams(self.gid, radius, length) def getParams(self): cdef dReal radius, length dGeomCapsuleGetParams(self.gid, &radius, &length) return (radius, length) def pointDepth(self, p): """pointDepth(p) -> float Return the depth of the point p in the cylinder. Points inside the geom will have positive depth, points outside it will have negative depth, and points on the surface will have zero depth. @param p: Point @type p: 3-sequence of floats """ return dGeomCapsulePointDepth(self.gid, p[0], p[1], p[2]) GeomCCylinder = GeomCapsule # backwards compatibility # GeomCylinder cdef class GeomCylinder(GeomObject): """Plain cylinder geometry. This class represents an uncapped cylinder aligned along the local Z axis and centered at the origin. Constructor:: GeomCylinder(space=None, radius=0.5, length=1.0) """ def __cinit__(self, space=None, radius=0.5, length=1.0): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateCylinder(sid, radius, length) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, radius=0.5, length=1.0): self.space = space self.body = None def placeable(self): return True def _id(self): cdef long id id = self.gid return id def setParams(self, radius, length): dGeomCylinderSetParams(self.gid, radius, length) def getParams(self): cdef dReal radius, length dGeomCylinderGetParams(self.gid, &radius, &length) return (radius, length) ## dGeomCylinderPointDepth not implemented upstream in ODE 0.7 # GeomRay cdef class GeomRay(GeomObject): """Ray object. A ray is different from all the other geom classes in that it does not represent a solid object. It is an infinitely thin line that starts from the geom's position and extends in the direction of the geom's local Z-axis. Constructor:: GeomRay(space=None, rlen=1.0) """ def __cinit__(self, space=None, rlen=1.0): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateRay(sid, rlen) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None, rlen=1.0): self.space = space self.body = None def _id(self): cdef long id id = self.gid return id def placeable(self): return True def setLength(self, rlen): '''setLength(rlen) Set length of the ray. @param rlen: length of the ray @type rlen: float''' dGeomRaySetLength(self.gid, rlen) def getLength(self): '''getLength() -> length Get the length of the ray. @returns: length of the ray (float)''' return dGeomRayGetLength(self.gid) def set(self, p, u): '''set(p, u) Set the position and rotation of a ray. @param p: position @type p: 3-sequence of floats @param u: rotation @type u: 3-sequence of floats''' dGeomRaySet(self.gid, p[0],p[1],p[2], u[0],u[1],u[2]) def get(self): '''get() -> ((p[0], p[1], p[2]), (u[0], u[1], u[2])) Return the position and rotation as a pair of tuples. @returns: position and rotation''' cdef dVector3 start cdef dVector3 dir dGeomRayGet(self.gid, start, dir) return ((start[0],start[1],start[2]), (dir[0],dir[1],dir[2])) # GeomHeightfield cdef class GeomHeightfield(GeomObject): """Heightfield object. To construct the heightfield geom, you need a HeightfieldData object that stores the heightfield data. This object has to be passed as the first argument to the constructor. NOTE: Heightfields treat Y as the "UP" axis. """ cdef HeightfieldData data def __cinit__(self, HeightfieldData data not None, placeable = True, space = None): cdef SpaceBase sp cdef dSpaceID sid self.data = data sid = NULL if space != None: sp = space sid = sp.sid self.gid = dCreateHeightfield(sid, data.hfdid, placeable) _geom_c2py_lut[ self.gid] = self def __init__(self, HeightfieldData data not None, placeable = True, space = None): self.space = space self.body = None self.placeable = placeable def placeable(self): return self.placeable # GeomHeightfield can be set to be non-placeable which causes all attempts to apply transforms on it to fail def _id(self): cdef long id id = self.gid return id def setHeightfieldData(self, HeightfieldData data not None): """ Assigns a dHeightfieldDataID to a heightfield geom. Associates the given dHeightfieldDataID with a heightfield geom. This is done without affecting the GEOM_PLACEABLE flag. @param data: A HeightfieldData created by dGeomHeightfieldDataCreate """ dGeomHeightfieldSetHeightfieldData(self.gid, data.hfdid) # GeomTransform cdef class GeomTransform(GeomObject): """GeomTransform. A geometry transform "T" is a geom that encapsulates another geom "E", allowing E to be positioned and rotated arbitrarily with respect to its point of reference. Constructor:: GeomTransform(space=None) """ cdef object geom def __cinit__(self, space=None): cdef SpaceBase sp cdef dSpaceID sid sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateGeomTransform(sid) # Set cleanup mode to 0 as a contained geom will be deleted # by its Python wrapper class dGeomTransformSetCleanup(self.gid, 0) # if space!=None: # space._addgeom(self) _geom_c2py_lut[self.gid]=self def __init__(self, space=None): self.space = space self.body = None self.geom = None self.attribs={} def placeable(self): return True def _id(self): cdef long id id = self.gid return id def setGeom(self, GeomObject geom not None): """setGeom(geom) Set the geom that the geometry transform encapsulates. A ValueError exception is thrown if a) the geom is not placeable, b) the geom was already inserted into a space or c) the geom is already associated with a body. @param geom: Geom object to encapsulate @type geom: GeomObject """ cdef long id if not geom.placeable(): raise ValueError, "Only placeable geoms can be encapsulated by a GeomTransform" if dGeomGetSpace(geom.gid)!=0: raise ValueError, "The encapsulated geom was already inserted into a space." if dGeomGetBody(geom.gid)!=0: raise ValueError, "The encapsulated geom is already associated with a body." id = geom._id() dGeomTransformSetGeom(self.gid, id) self.geom = geom def getGeom(self): """getGeom() -> GeomObject Get the geom that the geometry transform encapsulates. """ return self.geom def setInfo(self, int mode): """setInfo(mode) Set the "information" mode of the geometry transform. With mode 0, when a transform object is collided with another object, the geom field of the ContactGeom structure is set to the geom that is encapsulated by the transform object. With mode 1, the geom field of the ContactGeom structure is set to the transform object itself. @param mode: Information mode (0 or 1) @type mode: int """ if mode<0 or mode>1: raise ValueError, "Invalid information mode (%d). Must be either 0 or 1."%mode dGeomTransformSetInfo(self.gid, mode) def getInfo(self): """getInfo() -> int Get the "information" mode of the geometry transform (0 or 1). With mode 0, when a transform object is collided with another object, the geom field of the ContactGeom structure is set to the geom that is encapsulated by the transform object. With mode 1, the geom field of the ContactGeom structure is set to the transform object itself. """ return dGeomTransformGetInfo(self.gid) Py3ODE-1.2.0.dev15/src/heightfielddata.pyx000077500000000000000000000423631364423331700201200ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef class HeightfieldData: """This class is used to store heightfield data. The dHeightfieldData is a storage class, similar to the dTrimeshData class, that holds all geom properties and optionally height sample data. NOTE: Heightfields treat Y as the "UP" axis. """ cdef dHeightfieldDataID hfdid # This attribute stores the tuple which gets passed to the height # callback. If we don't keep a reference, the tuple gets garbage # collected. cdef object calltup def __cinit__(self): self.hfdid = dGeomHeightfieldDataCreate() def __dealloc__(self): if self.hfdid != NULL: dGeomHeightfieldDataDestroy(self.hfdid) def buildByte(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap): """buildByte(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap) Configures a dHeightfieldDataID to use height data in byte format. Before a dHeightfieldDataID can be used by a geom it must be configured to specify the format of the height data. This call specifies that the heightfield data is stored as a rectangular array of bytes (8 bit unsigned) representing the height at each sample point. @param heightData: A list of len( widthSamples * depthSamples ) containing the height values. NOTE: This NEEDS to be a contigious array (easy to create one with numpy, see tutorial_heightmap.py) otherwise ODE won't be able to access it correctly, and it will likely lead to memory corruption. There isn't an automatic conversion built in here as that would bring another - often unnecessary - dependency into Py3ODE. @param copy: True / False, should ODE copy the heightData into it's internal memory or will it remain accessible (not garbage collected) for the lifetime of the heightfield? @param width: Specifies the total 'width' of the heightfield along the geom's local x axis. @param depth: Specifies the total 'depth' of the heightfield along the geom's local z axis. @param widthSamples: Specifies the number of vertices to sample along the width of the heightfield. Each vertex has a corresponding height value which forms the overall shape. Naturally this value must be at least two or more. @param depthSamples: Specifies the number of vertices to sample along the depth of the heightfield. @param scale: A uniform scale applied to all raw height data. @param offset: An offset applied to the scaled height data. @param thickness: A value subtracted from the lowest height value which in effect adds an additional cuboid to the base of the heightfield. This is used to prevent geoms from looping under the desired terrain and not registering as a collision. Note that the thickness is not affected by the scale or offset parameters. @param bWrap: If non-zero the heightfield will infinitely tile in both directions along the local x and z axes. If zero the heightfield is bounded from zero to width in the local x axis, and zero to depth in the local z axis. """ cdef unsigned char[::1] memview = heightData dGeomHeightfieldDataBuildByte(self.hfdid, &memview[0], copy, width, depth, widthSamples, depthSamples, scale, offset, thickness, bWrap) def buildShort(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap): """buildShort(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap) Configures a dHeightfieldDataID to use height data in byte format. Before a dHeightfieldDataID can be used by a geom it must be configured to specify the format of the height data. This call specifies that the heightfield data is stored as a rectangular array of shorts (16 bit signed) representing the height at each sample point. @param heightData: A list of len( widthSamples * depthSamples ) containing the height values. NOTE: This NEEDS to be a contigious array (easy to create one with numpy, see tutorial_heightmap.py) otherwise ODE won't be able to access it correctly, and it will likely lead to memory corruption. There isn't an automatic conversion built in here as that would bring another - often unnecessary - dependency into Py3ODE. @param copy: True / False, should ODE copy the heightData into it's internal memory or will it remain accessible (not garbage collected) for the lifetime of the heightfield? @param width: Specifies the total 'width' of the heightfield along the geom's local x axis. @param depth: Specifies the total 'depth' of the heightfield along the geom's local z axis. @param widthSamples: Specifies the number of vertices to sample along the width of the heightfield. Each vertex has a corresponding height value which forms the overall shape. Naturally this value must be at least two or more. @param depthSamples: Specifies the number of vertices to sample along the depth of the heightfield. @param scale: A uniform scale applied to all raw height data. @param offset: An offset applied to the scaled height data. @param thickness: A value subtracted from the lowest height value which in effect adds an additional cuboid to the base of the heightfield. This is used to prevent geoms from looping under the desired terrain and not registering as a collision. Note that the thickness is not affected by the scale or offset parameters. @param bWrap: If non-zero the heightfield will infinitely tile in both directions along the local x and z axes. If zero the heightfield is bounded from zero to width in the local x axis, and zero to depth in the local z axis. """ cdef short[::1] memview = heightData # yes this isn't unsigned - no IDK why dGeomHeightfieldDataBuildShort(self.hfdid, &memview[0], copy, width, depth, widthSamples, depthSamples, scale, offset, thickness, bWrap) def buildSingle(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap): """buildSingle(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap) Configures a dHeightfieldDataID to use height data in byte format. Before a dHeightfieldDataID can be used by a geom it must be configured to specify the format of the height data. This call specifies that the heightfield data is stored as a rectangular array of single precision floats representing the height at each sample point. @param heightData: A list of len( widthSamples * depthSamples ) containing the height values. NOTE: This NEEDS to be a contigious array (easy to create one with numpy, see tutorial_heightmap.py) otherwise ODE won't be able to access it correctly, and it will likely lead to memory corruption. There isn't an automatic conversion built in here as that would bring another - often unnecessary - dependency into Py3ODE. @param copy: True / False, should ODE copy the heightData into it's internal memory or will it remain accessible (not garbage collected) for the lifetime of the heightfield? @param width: Specifies the total 'width' of the heightfield along the geom's local x axis. @param depth: Specifies the total 'depth' of the heightfield along the geom's local z axis. @param widthSamples: Specifies the number of vertices to sample along the width of the heightfield. Each vertex has a corresponding height value which forms the overall shape. Naturally this value must be at least two or more. @param depthSamples: Specifies the number of vertices to sample along the depth of the heightfield. @param scale: A uniform scale applied to all raw height data. @param offset: An offset applied to the scaled height data. @param thickness: A value subtracted from the lowest height value which in effect adds an additional cuboid to the base of the heightfield. This is used to prevent geoms from looping under the desired terrain and not registering as a collision. Note that the thickness is not affected by the scale or offset parameters. @param bWrap: If non-zero the heightfield will infinitely tile in both directions along the local x and z axes. If zero the heightfield is bounded from zero to width in the local x axis, and zero to depth in the local z axis. """ cdef float[::1] memview = heightData dGeomHeightfieldDataBuildSingle(self.hfdid, &memview[0], copy, width, depth, widthSamples, depthSamples, scale, offset, thickness, bWrap) def buildDouble(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap): """buildDouble(self, heightData, copy, width, depth, int widthSamples, int depthSamples, scale, offset, thickness, bWrap) Configures a dHeightfieldDataID to use height data in byte format. Before a dHeightfieldDataID can be used by a geom it must be configured to specify the format of the height data. This call specifies that the heightfield data is stored as a rectangular array of double precision floats representing the height at each sample point. @param heightData: A list of len( widthSamples * depthSamples ) containing the height values. NOTE: This NEEDS to be a contigious array (easy to create one with numpy, see tutorial_heightmap.py) otherwise ODE won't be able to access it correctly, and it will likely lead to memory corruption. There isn't an automatic conversion built in here as that would bring another - often unnecessary - dependency into Py3ODE. @param copy: True / False, should ODE copy the heightData into it's internal memory or will it remain accessible (not garbage collected) for the lifetime of the heightfield? @param width: Specifies the total 'width' of the heightfield along the geom's local x axis. @param depth: Specifies the total 'depth' of the heightfield along the geom's local z axis. @param widthSamples: Specifies the number of vertices to sample along the width of the heightfield. Each vertex has a corresponding height value which forms the overall shape. Naturally this value must be at least two or more. @param depthSamples: Specifies the number of vertices to sample along the depth of the heightfield. @param scale: A uniform scale applied to all raw height data. @param offset: An offset applied to the scaled height data. @param thickness: A value subtracted from the lowest height value which in effect adds an additional cuboid to the base of the heightfield. This is used to prevent geoms from looping under the desired terrain and not registering as a collision. Note that the thickness is not affected by the scale or offset parameters. @param bWrap: If non-zero the heightfield will infinitely tile in both directions along the local x and z axes. If zero the heightfield is bounded from zero to width in the local x axis, and zero to depth in the local z axis. """ cdef double[::1] memview = heightData dGeomHeightfieldDataBuildDouble(self.hfdid, &memview[0], copy, width, depth, widthSamples, depthSamples, scale, offset, thickness, bWrap) def setBounds(self, float min_height, float max_height): """setBounds(min_height, max_height) Manually set the minimum and maximum height bounds. This call allows you to set explicit min / max values after initial creation typically for callback heightfields which default to +/- infinity, or those whose data has changed. This must be set prior to binding with a geom, as the the AABB is not recomputed after it's first generation. NOTE: The minimum and maximum values are used to compute the AABB for the heightfield which is used for early rejection of collisions. A close fit will yield a more efficient collision check. @param min_height: The new minimum height value. Scale, offset and thickness is then applied. @param max_height: The new maximum height value. Scale and offset is then applied. """ dGeomHeightfieldDataSetBounds(self.hfdid, min_height, max_height) def build_callback(self, userdata, callback, width, depth, widthSamples, depthSamples, scale, offset, thickness, bwrap): """build_callback(self, userdata, callback, width, depth, widthSamples, depthSamples, scale, offset, thickness, bwrap) Configures a dHeightfieldDataID to use a callback to retrieve height data. Before a dHeightfieldDataID can be used by a geom it must be configured to specify the format of the height data. This call specifies that the heightfield data is computed by the user and it should use the given callback when determining the height of a given element of it's shape. @param userdata: A python object that gets passed through to the callback function @param callback: A python function that does the actual computing it takes 3 arguments and returns a number epresenting the vertices height: def callback(arg, x, z): return 0 @param width: Specifies the total 'width' of the heightfield along the geom's local x axis. @param depth: Specifies the total 'depth' of the heightfield along the geom's local z axis. @param widthSamples: Specifies the number of vertices to sample along the width of the heightfield. Each vertex has a corresponding height value which forms the overall shape. Naturally this value must be at least two or more. @param depthSamples: Specifies the number of vertices to sample along the depth of the heightfield. @param scale: A uniform scale applied to all raw height data. @param offset: An offset applied to the scaled height data. @param thickness: A value subtracted from the lowest height value which in effect adds an additional cuboid to the base of the heightfield. This is used to prevent geoms from looping under the desired terrain and not registering as a collision. Note that the thickness is not affected by the scale or offset parameters. @param bWrap: If non-zero the heightfield will infinitely tile in both directions along the local x and z axes. If zero the heightfield is bounded from zero to width in the local x axis, and zero to depth in the local z axis. """ cdef object tup cdef void* data tup = (callback, userdata) self.calltup = tup data = tup dGeomHeightfieldDataBuildCallback(self.hfdid, data, get_height, width, depth, widthSamples, depthSamples, scale, offset, thickness, bwrap) # Callback function for the dGeomHeightfieldDataBuildCallback() call in the HeightfieldData.build_callback() method # The data parameter is a tuple (Python-Callback, Arguments). # The function calls a Python callback function with 3 arguments: # def callback(UserArg, x, z) # x and z are the world coordinates of the heightmap's current vertex. cdef dReal get_height(void *data, int x, int z): cdef object tup tup = data callback, arg = tup return callback(arg, x, z) Py3ODE-1.2.0.dev15/src/joints.pyx000077500000000000000000001011151364423331700163070ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # For every joint type there is a separate class that wraps that joint. # These classes are derived from the base class "Joint" that contains # all the common stuff (including destruction). # The ODE joint is created in the constructor and destroyed in the destructor. # So it's the respective Python wrapper class that has ownership of the # ODE joint. If joint groups are used it can happen that an ODE joint gets # destroyed outside of its Python wrapper (whenever you empty the group). # In such cases the Python wrapper has to be notified so that it dismisses # its pointer. This is done by calling _destroyed() on the respective # Python wrapper (which is done by the JointGroup wrapper). ###################################################################### from cpython.mem cimport PyMem_RawMalloc, PyMem_RawFree # JointGroup cdef class JointGroup: """Joint group. Constructor:: JointGroup() """ # JointGroup ID cdef dJointGroupID gid # A list of Python joints that were added to the group cdef object jointlist def __cinit__(self): self.gid = dJointGroupCreate(0) def __init__(self): self.jointlist = [] def __dealloc__(self): if self.gid!=NULL: for j in self.jointlist: j._destroyed() dJointGroupDestroy(self.gid) # empty def empty(self): """empty() Destroy all joints in the group. """ dJointGroupEmpty(self.gid) for j in self.jointlist: j._destroyed() self.jointlist = [] def _addjoint(self, j): """_addjoint(j) Add a joint to the group. This is an internal method that is called by the joints. The group has to know the Python wrappers because it has to notify them when the group is emptied (so that the ODE joints won't get destroyed twice). The notification is done by calling _destroyed() on the Python joints. @param j: The joint to add @type j: Joint """ self.jointlist.append(j) ###################################################################### # Joint cdef class Joint: """Base class for all joint classes.""" # Joint id as returned by dJointCreateXxx() cdef dJointID jid # A reference to the world so that the world won't be destroyed while # there are still joints using it. cdef object world # The feedback buffer cdef dJointFeedback* feedback cdef object body1 cdef object body2 # A dictionary with user attributes # (set via __getattr__ and __setattr__) cdef object userattribs def __cinit__(self, *a, **kw): self.jid = NULL self.world = None self.feedback = NULL self.body1 = None self.body2 = None self.userattribs = {} def __init__(self, *a, **kw): raise NotImplementedError, "The Joint base class can't be used directly." def __dealloc__(self): self.setFeedback(False) if self.jid!=NULL: dJointDestroy(self.jid) def __getattr__(self, name): try: return self.userattribs[name] except: raise AttributeError, "Joint object has no attribute '%s'"%name def __setattr__(self, name, value): self.userattribs[name] = value def __delattr__(self, name): try: del self.userattribs[name] except: raise AttributeError, "Joint object has no attribute '%s'"%name # _destroyed def _destroyed(self): """Notify the joint object about an external destruction of the ODE joint. This method has to be called when the underlying ODE object was destroyed by someone else (e.g. by a joint group). The Python wrapper will then refrain from destroying it again. """ self.jid = NULL # attach def attach(self, Body body1, Body body2): """attach(body1, body2) Attach the joint to some new bodies. A body can be attached to the environment by passing None as second body. @param body1: First body @param body2: Second body @type body1: Body @type body2: Body """ cdef dBodyID id1, id2 if body1==None: id1 = NULL else: id1 = body1.bid if body2==None: id2 = NULL else: id2 = body2.bid self.body1 = body1 self.body2 = body2 dJointAttach(self.jid, id1, id2) # getBody def getBody(self, index): """getBody(index) -> Body Return the bodies that this joint connects. If index is 0 the "first" body will be returned, corresponding to the body1 argument of the attach() method. If index is 1 the "second" body will be returned, corresponding to the body2 argument of the attach() method. @param index: Bodx index (0 or 1). @type index: int """ if (index == 0): return self.body1 elif (index == 1): return self.body2 else: raise IndexError() # setFeedback def setFeedback(self, release = False): """setFeedback(release = True) Sets the datastructure that is to receive the feedback. The feedback can be used by the user, so that it is known how much force an individual joint exerts. If release is True then a buffer is allocated and the forces/torques applied by the joint can be read using the getFeedback() method. If release is False the buffer is released. @param release: Specifies whether a buffer should be created or released @type release: bool """ if release: if self.feedback != NULL: return self.feedback = PyMem_RawMalloc(sizeof(dJointFeedback)) if self.feedback == NULL: raise MemoryError("Couldn't allocate a new feedback buffer.") dJointSetFeedback(self.jid, self.feedback) else: if self.feedback != NULL: dJointSetFeedback(self.jid, NULL) PyMem_RawFree(self.feedback) self.feedback = NULL # getFeedback def getFeedback(self): """getFeedback() -> (force1, torque1, force2, torque2) Get the forces/torques applied by the joint. If feedback is activated (i.e. setFeedback(True) was called) then this method returns a tuple (force1, torque1, force2, torque2) with the forces and torques applied to body 1 and body 2. The forces/torques are given as 3-tuples. If feedback is deactivated then the method always returns None. """ cdef dJointFeedback* fb fb = dJointGetFeedback(self.jid) if (fb == NULL): return None f1 = (fb.f1[0], fb.f1[1], fb.f1[2]) t1 = (fb.t1[0], fb.t1[1], fb.t1[2]) f2 = (fb.f2[0], fb.f2[1], fb.f2[2]) t2 = (fb.t2[0], fb.t2[1], fb.t2[2]) return (f1,t1,f2,t2) ###################################################################### # BallJoint cdef class BallJoint(Joint): """Ball joint. Constructor:: BallJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateBall(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setAnchor def setAnchor(self, pos): """setAnchor(pos) Set the joint anchor point which must be specified in world coordinates. @param pos: Anchor position @type pos: 3-sequence of floats """ dJointSetBallAnchor(self.jid, pos[0], pos[1], pos[2]) # getAnchor def getAnchor(self): """getAnchor() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 1. If the joint is perfectly satisfied, this will be the same as the point on body 2. """ cdef dVector3 p dJointGetBallAnchor(self.jid, p) return (p[0],p[1],p[2]) # getAnchor2 def getAnchor2(self): """getAnchor2() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 2. If the joint is perfectly satisfied, this will be the same as the point on body 1. """ cdef dVector3 p dJointGetBallAnchor2(self.jid, p) return (p[0],p[1],p[2]) # setParam def setParam(self, param, value): pass # getParam def getParam(self, param): return 0.0 # HingeJoint cdef class HingeJoint(Joint): """Hinge joint. Constructor:: HingeJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateHinge(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setAnchor def setAnchor(self, pos): """setAnchor(pos) Set the hinge anchor which must be given in world coordinates. @param pos: Anchor position @type pos: 3-sequence of floats """ dJointSetHingeAnchor(self.jid, pos[0], pos[1], pos[2]) # getAnchor def getAnchor(self): """getAnchor() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 1. If the joint is perfectly satisfied, this will be the same as the point on body 2. """ cdef dVector3 p dJointGetHingeAnchor(self.jid, p) return (p[0],p[1],p[2]) # getAnchor2 def getAnchor2(self): """getAnchor2() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 2. If the joint is perfectly satisfied, this will be the same as the point on body 1. """ cdef dVector3 p dJointGetHingeAnchor2(self.jid, p) return (p[0],p[1],p[2]) # setAxis def setAxis(self, axis): """setAxis(axis) Set the hinge axis. @param axis: Hinge axis @type axis: 3-sequence of floats """ dJointSetHingeAxis(self.jid, axis[0], axis[1], axis[2]) # getAxis def getAxis(self): """getAxis() -> 3-tuple of floats Get the hinge axis. """ cdef dVector3 a dJointGetHingeAxis(self.jid, a) return (a[0],a[1],a[2]) # getAngle def getAngle(self): """getAngle() -> float Get the hinge angle. The angle is measured between the two bodies, or between the body and the static environment. The angle will be between -pi..pi. When the hinge anchor or axis is set, the current position of the attached bodies is examined and that position will be the zero angle. """ return dJointGetHingeAngle(self.jid) # getAngleRate def getAngleRate(self): """getAngleRate() -> float Get the time derivative of the angle. """ return dJointGetHingeAngleRate(self.jid) # addTorque def addTorque(self, torque): """addTorque(torque) Applies the torque about the hinge axis. @param torque: Torque magnitude @type torque: float """ dJointAddHingeTorque(self.jid, torque) # setParam def setParam(self, param, value): """setParam(param, value) Set limit/motor parameters for the joint. param is one of ParamLoStop, ParamHiStop, ParamVel, ParamFMax, ParamFudgeFactor, ParamBounce, ParamCFM, ParamStopERP, ParamStopCFM, ParamSuspensionERP, ParamSuspensionCFM. These parameter names can be optionally followed by a digit (2 or 3) to indicate the second or third set of parameters. @param param: Selects the parameter to set @param value: Parameter value @type param: int @type value: float """ dJointSetHingeParam(self.jid, param, value) # getParam def getParam(self, param): """getParam(param) -> float Get limit/motor parameters for the joint. param is one of ParamLoStop, ParamHiStop, ParamVel, ParamFMax, ParamFudgeFactor, ParamBounce, ParamCFM, ParamStopERP, ParamStopCFM, ParamSuspensionERP, ParamSuspensionCFM. These parameter names can be optionally followed by a digit (2 or 3) to indicate the second or third set of parameters. @param param: Selects the parameter to read @type param: int """ return dJointGetHingeParam(self.jid, param) # SliderJoint cdef class SliderJoint(Joint): """Slider joint. Constructor:: SlideJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateSlider(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setAxis def setAxis(self, axis): """setAxis(axis) Set the slider axis parameter. @param axis: Slider axis @type axis: 3-sequence of floats """ dJointSetSliderAxis(self.jid, axis[0], axis[1], axis[2]) # getAxis def getAxis(self): """getAxis() -> 3-tuple of floats Get the slider axis parameter. """ cdef dVector3 a dJointGetSliderAxis(self.jid, a) return (a[0],a[1],a[2]) # getPosition def getPosition(self): """getPosition() -> float Get the slider linear position (i.e. the slider's "extension"). When the axis is set, the current position of the attached bodies is examined and that position will be the zero position. """ return dJointGetSliderPosition(self.jid) # getPositionRate def getPositionRate(self): """getPositionRate() -> float Get the time derivative of the position. """ return dJointGetSliderPositionRate(self.jid) # addForce def addForce(self, force): """addForce(force) Applies the given force in the slider's direction. @param force: Force magnitude @type force: float """ dJointAddSliderForce(self.jid, force) # setParam def setParam(self, param, value): dJointSetSliderParam(self.jid, param, value) # getParam def getParam(self, param): return dJointGetSliderParam(self.jid, param) # UniversalJoint cdef class UniversalJoint(Joint): """Universal joint. Constructor:: UniversalJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateUniversal(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setAnchor def setAnchor(self, pos): """setAnchor(pos) Set the universal anchor. @param pos: Anchor position @type pos: 3-sequence of floats """ dJointSetUniversalAnchor(self.jid, pos[0], pos[1], pos[2]) # getAnchor def getAnchor(self): """getAnchor() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 1. If the joint is perfectly satisfied, this will be the same as the point on body 2. """ cdef dVector3 p dJointGetUniversalAnchor(self.jid, p) return (p[0],p[1],p[2]) # getAnchor2 def getAnchor2(self): """getAnchor2() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 2. If the joint is perfectly satisfied, this will be the same as the point on body 1. """ cdef dVector3 p dJointGetUniversalAnchor2(self.jid, p) return (p[0],p[1],p[2]) # setAxis1 def setAxis1(self, axis): """setAxis1(axis) Set the first universal axis. Axis 1 and axis 2 should be perpendicular to each other. @param axis: Joint axis @type axis: 3-sequence of floats """ dJointSetUniversalAxis1(self.jid, axis[0], axis[1], axis[2]) # getAxis1 def getAxis1(self): """getAxis1() -> 3-tuple of floats Get the first univeral axis. """ cdef dVector3 a dJointGetUniversalAxis1(self.jid, a) return (a[0],a[1],a[2]) # setAxis2 def setAxis2(self, axis): """setAxis2(axis) Set the second universal axis. Axis 1 and axis 2 should be perpendicular to each other. @param axis: Joint axis @type axis: 3-sequence of floats """ dJointSetUniversalAxis2(self.jid, axis[0], axis[1], axis[2]) # getAxis2 def getAxis2(self): """getAxis2() -> 3-tuple of floats Get the second univeral axis. """ cdef dVector3 a dJointGetUniversalAxis2(self.jid, a) return (a[0],a[1],a[2]) # addTorques def addTorques(self, torque1, torque2): """addTorques(torque1, torque2) Applies torque1 about axis 1, and torque2 about axis 2. @param torque1: Torque 1 magnitude @param torque2: Torque 2 magnitude @type torque1: float @type torque2: float """ dJointAddUniversalTorques(self.jid, torque1, torque2) def getAngle1(self): return dJointGetUniversalAngle1(self.jid) def getAngle2(self): return dJointGetUniversalAngle2(self.jid) def getAngle1Rate(self): return dJointGetUniversalAngle1Rate(self.jid) def getAngle2Rate(self): return dJointGetUniversalAngle2Rate(self.jid) # setParam def setParam(self, param, value): dJointSetUniversalParam(self.jid, param, value) # getParam def getParam(self, param): return dJointGetUniversalParam(self.jid, param) # Hinge2Joint cdef class Hinge2Joint(Joint): """Hinge2 joint. Constructor:: Hinge2Joint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateHinge2(world.wid, jgid) def __init__(self, World world, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setAnchor def setAnchor(self, pos): """setAnchor(pos) Set the hinge-2 anchor. @param pos: Anchor position @type pos: 3-sequence of floats """ dJointSetHinge2Anchor(self.jid, pos[0], pos[1], pos[2]) # getAnchor def getAnchor(self): """getAnchor() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 1. If the joint is perfectly satisfied, this will be the same as the point on body 2. """ cdef dVector3 p dJointGetHinge2Anchor(self.jid, p) return (p[0],p[1],p[2]) # getAnchor2 def getAnchor2(self): """getAnchor2() -> 3-tuple of floats Get the joint anchor point, in world coordinates. This returns the point on body 2. If the joint is perfectly satisfied, this will be the same as the point on body 1. """ cdef dVector3 p dJointGetHinge2Anchor2(self.jid, p) return (p[0],p[1],p[2]) # setAxis1 def setAxis1(self, axis): """setAxis1(axis) Set the first hinge-2 axis. Axis 1 and axis 2 must not lie along the same line. @param axis: Joint axis @type axis: 3-sequence of floats """ dJointSetHinge2Axis1(self.jid, axis[0], axis[1], axis[2]) # getAxis1 def getAxis1(self): """getAxis1() -> 3-tuple of floats Get the first hinge-2 axis. """ cdef dVector3 a dJointGetHinge2Axis1(self.jid, a) return (a[0],a[1],a[2]) # setAxis2 def setAxis2(self, axis): """setAxis2(axis) Set the second hinge-2 axis. Axis 1 and axis 2 must not lie along the same line. @param axis: Joint axis @type axis: 3-sequence of floats """ dJointSetHinge2Axis2(self.jid, axis[0], axis[1], axis[2]) # getAxis2 def getAxis2(self): """getAxis2() -> 3-tuple of floats Get the second hinge-2 axis. """ cdef dVector3 a dJointGetHinge2Axis2(self.jid, a) return (a[0],a[1],a[2]) # getAngle def getAngle1(self): """getAngle1() -> float Get the first hinge-2 angle (around axis 1). When the anchor or axis is set, the current position of the attached bodies is examined and that position will be the zero angle. """ return dJointGetHinge2Angle1(self.jid) # getAngle1Rate def getAngle1Rate(self): """getAngle1Rate() -> float Get the time derivative of the first hinge-2 angle. """ return dJointGetHinge2Angle1Rate(self.jid) # getAngle2Rate def getAngle2Rate(self): """getAngle2Rate() -> float Get the time derivative of the second hinge-2 angle. """ return dJointGetHinge2Angle2Rate(self.jid) # addTorques def addTorques(self, torque1, torque2): """addTorques(torque1, torque2) Applies torque1 about axis 1, and torque2 about axis 2. @param torque1: Torque 1 magnitude @param torque2: Torque 2 magnitude @type torque1: float @type torque2: float """ dJointAddHinge2Torques(self.jid, torque1, torque2) # setParam def setParam(self, param, value): dJointSetHinge2Param(self.jid, param, value) # getParam def getParam(self, param): return dJointGetHinge2Param(self.jid, param) # FixedJoint cdef class FixedJoint(Joint): """Fixed joint. Constructor:: FixedJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateFixed(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setFixed def setFixed(self): """setFixed() Call this on the fixed joint after it has been attached to remember the current desired relative offset and desired relative rotation between the bodies. """ dJointSetFixed(self.jid) # ContactJoint cdef class ContactJoint(Joint): """Contact joint. Constructor:: ContactJoint(world, jointgroup, contact) """ def __cinit__(self, World world not None, jointgroup, Contact contact): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreateContact(world.wid, jgid, &contact._contact) def __init__(self, World world not None, jointgroup, Contact contact): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # AMotor cdef class AMotor(Joint): """AMotor joint. Constructor:: AMotor(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid = NULL if jointgroup!=None: jg = jointgroup jgid = jg.gid self.jid = dJointCreateAMotor(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setMode def setMode(self, mode): """setMode(mode) Set the angular motor mode. mode must be either AMotorUser or AMotorEuler. @param mode: Angular motor mode @type mode: int """ dJointSetAMotorMode(self.jid, mode) # getMode def getMode(self): """getMode() Return the angular motor mode (AMotorUser or AMotorEuler). """ return dJointGetAMotorMode(self.jid) # setNumAxes def setNumAxes(self, int num): """setNumAxes(num) Set the number of angular axes that will be controlled by the AMotor. num may be in the range from 0 to 3. @param num: Number of axes (0-3) @type num: int """ dJointSetAMotorNumAxes(self.jid, num) # getNumAxes def getNumAxes(self): """getNumAxes() -> int Get the number of angular axes that are controlled by the AMotor. """ return dJointGetAMotorNumAxes(self.jid) # setAxis def setAxis(self, int anum, int rel, axis): """setAxis(anum, rel, axis) Set an AMotor axis. The anum argument selects the axis to change (0,1 or 2). Each axis can have one of three "relative orientation" modes, selected by rel: 0: The axis is anchored to the global frame. 1: The axis is anchored to the first body. 2: The axis is anchored to the second body. The axis vector is always specified in global coordinates regardless of the setting of rel. @param anum: Axis number @param rel: Relative orientation mode @param axis: Axis @type anum: int @type rel: int @type axis: 3-sequence of floats """ dJointSetAMotorAxis(self.jid, anum, rel, axis[0], axis[1], axis[2]) # getAxis def getAxis(self, int anum): """getAxis(anum) Get an AMotor axis. @param anum: Axis index (0-2) @type anum: int """ cdef dVector3 a dJointGetAMotorAxis(self.jid, anum, a) return (a[0],a[1],a[2]) # getAxisRel def getAxisRel(self, int anum): """getAxisRel(anum) -> int Get the relative mode of an axis. @param anum: Axis index (0-2) @type anum: int """ return dJointGetAMotorAxisRel(self.jid, anum) # setAngle def setAngle(self, int anum, angle): """setAngle(anum, angle) Tell the AMotor what the current angle is along axis anum. @param anum: Axis index @param angle: Angle @type anum: int @type angle: float """ dJointSetAMotorAngle(self.jid, anum, angle) # getAngle def getAngle(self, int anum): """getAngle(anum) -> float Return the current angle for axis anum. @param anum: Axis index @type anum: int """ return dJointGetAMotorAngle(self.jid, anum) # getAngleRate def getAngleRate(self, int anum): """getAngleRate(anum) -> float Return the current angle rate for axis anum. @param anum: Axis index @type anum: int """ return dJointGetAMotorAngleRate(self.jid, anum) # addTorques def addTorques(self, torque0, torque1, torque2): """addTorques(torque0, torque1, torque2) Applies torques about the AMotor's axes. @param torque0: Torque 0 magnitude @param torque1: Torque 1 magnitude @param torque2: Torque 2 magnitude @type torque0: float @type torque1: float @type torque2: float """ dJointAddAMotorTorques(self.jid, torque0, torque1, torque2) # setParam def setParam(self, param, value): dJointSetAMotorParam(self.jid, param, value) # getParam def getParam(self, param): return dJointGetAMotorParam(self.jid, param) # LMotor cdef class LMotor(Joint): """LMotor joint. Constructor:: LMotor(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid = NULL if jointgroup!=None: jg = jointgroup jgid = jg.gid self.jid = dJointCreateLMotor(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) # setNumAxes def setNumAxes(self, int num): """setNumAxes(num) Set the number of angular axes that will be controlled by the LMotor. num may be in the range from 0 to 3. @param num: Number of axes (0-3) @type num: int """ dJointSetLMotorNumAxes(self.jid, num) # getNumAxes def getNumAxes(self): """getNumAxes() -> int Get the number of angular axes that are controlled by the LMotor. """ return dJointGetLMotorNumAxes(self.jid) # setAxis def setAxis(self, int anum, int rel, axis): """setAxis(anum, rel, axis) Set an LMotor axis. The anum argument selects the axis to change (0,1 or 2). Each axis can have one of three "relative orientation" modes, selected by rel: 0: The axis is anchored to the global frame. 1: The axis is anchored to the first body. 2: The axis is anchored to the second body. @param anum: Axis number @param rel: Relative orientation mode @param axis: Axis @type anum: int @type rel: int @type axis: 3-sequence of floats """ dJointSetLMotorAxis(self.jid, anum, rel, axis[0], axis[1], axis[2]) # getAxis def getAxis(self, int anum): """getAxis(anum) Get an LMotor axis. @param anum: Axis index (0-2) @type anum: int """ cdef dVector3 a dJointGetLMotorAxis(self.jid, anum, a) return (a[0],a[1],a[2]) # setParam def setParam(self, param, value): dJointSetLMotorParam(self.jid, param, value) # getParam def getParam(self, param): return dJointGetLMotorParam(self.jid, param) # Plane2DJoint cdef class Plane2DJoint(Joint): """Plane-2D Joint. Constructor:: Plane2DJoint(world, jointgroup=None) """ def __cinit__(self, World world not None, jointgroup=None): cdef JointGroup jg cdef dJointGroupID jgid jgid=NULL if jointgroup!=None: jg=jointgroup jgid=jg.gid self.jid = dJointCreatePlane2D(world.wid, jgid) def __init__(self, World world not None, jointgroup=None): self.world = world if jointgroup!=None: jointgroup._addjoint(self) def setXParam(self, param, value): dJointSetPlane2DXParam(self.jid, param, value) def setYParam(self, param, value): dJointSetPlane2DYParam(self.jid, param, value) def setAngleParam(self, param, value): dJointSetPlane2DAngleParam(self.jid, param, value) Py3ODE-1.2.0.dev15/src/mass.pyx000077500000000000000000000276551364423331700157640ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef class Mass: """Mass parameters of a rigid body. This class stores mass parameters of a rigid body which can be accessed through the following attributes: - mass: The total mass of the body (float) - c: The center of gravity position in body frame (3-tuple of floats) - I: The 3x3 inertia tensor in body frame (3-tuple of 3-tuples) This class wraps the dMass structure from the C API. @ivar mass: The total mass of the body @ivar c: The center of gravity position in body frame (cx, cy, cz) @ivar I: The 3x3 inertia tensor in body frame ((I11, I12, I13), (I12, I22, I23), (I13, I23, I33)) @type mass: float @type c: 3-tuple of floats @type I: 3-tuple of 3-tuples of floats """ cdef dMass _mass def __cinit__(self): dMassSetZero(&self._mass) def setZero(self): """setZero() Set all the mass parameters to zero.""" dMassSetZero(&self._mass) def setParameters(self, mass, cgx, cgy, cgz, I11, I22, I33, I12, I13, I23): """setParameters(mass, cgx, cgy, cgz, I11, I22, I33, I12, I13, I23) Set the mass parameters to the given values. @param mass: Total mass of the body. @param cgx: Center of gravity position in the body frame (x component). @param cgy: Center of gravity position in the body frame (y component). @param cgz: Center of gravity position in the body frame (z component). @param I11: Inertia tensor @param I22: Inertia tensor @param I33: Inertia tensor @param I12: Inertia tensor @param I13: Inertia tensor @param I23: Inertia tensor @type mass: float @type cgx: float @type cgy: float @type cgz: float @type I11: float @type I22: float @type I33: float @type I12: float @type I13: float @type I23: float """ dMassSetParameters(&self._mass, mass, cgx, cgy, cgz, I11, I22, I33, I12, I13, I23) def setSphere(self, density, radius): """setSphere(density, radius) Set the mass parameters to represent a sphere of the given radius and density, with the center of mass at (0,0,0) relative to the body. @param density: The density of the sphere @param radius: The radius of the sphere @type density: float @type radius: float """ dMassSetSphere(&self._mass, density, radius) def setSphereTotal(self, total_mass, radius): """setSphereTotal(total_mass, radius) Set the mass parameters to represent a sphere of the given radius and mass, with the center of mass at (0,0,0) relative to the body. @param total_mass: The total mass of the sphere @param radius: The radius of the sphere @type total_mass: float @type radius: float """ dMassSetSphere(&self._mass, total_mass, radius) def setCappedCylinder(self, density, direction, r, h): """setCappedCylinder(density, direction, r, h) Set the mass parameters to represent a capped cylinder of the given parameters and density, with the center of mass at (0,0,0) relative to the body. The radius of the cylinder (and the spherical cap) is r. The length of the cylinder (not counting the spherical cap) is h. The cylinder's long axis is oriented along the body's x, y or z axis according to the value of direction (1=x, 2=y, 3=z). @param density: The density of the cylinder @param direction: The direction of the cylinder (1=x axis, 2=y axis, 3=z axis) @param r: The radius of the cylinder @param h: The length of the cylinder (without the caps) @type density: float @type direction: int @type r: float @type h: float """ dMassSetCappedCylinder(&self._mass, density, direction, r, h) def setCappedCylinderTotal(self, total_mass, direction, r, h): """setCappedCylinderTotal(total_mass, direction, r, h) Set the mass parameters to represent a capped cylinder of the given parameters and mass, with the center of mass at (0,0,0) relative to the body. The radius of the cylinder (and the spherical cap) is r. The length of the cylinder (not counting the spherical cap) is h. The cylinder's long axis is oriented along the body's x, y or z axis according to the value of direction (1=x, 2=y, 3=z). @param total_mass: The total mass of the cylinder @param direction: The direction of the cylinder (1=x axis, 2=y axis, 3=z axis) @param r: The radius of the cylinder @param h: The length of the cylinder (without the caps) @type total_mass: float @type direction: int @type r: float @type h: float """ dMassSetCappedCylinderTotal(&self._mass, total_mass, direction, r, h) def setCylinder(self, density, direction, r, h): """setCylinder(density, direction, r, h) Set the mass parameters to represent a flat-ended cylinder of the given parameters and density, with the center of mass at (0,0,0) relative to the body. The radius of the cylinder is r. The length of the cylinder is h. The cylinder's long axis is oriented along the body's x, y or z axis according to the value of direction (1=x, 2=y, 3=z). @param density: The density of the cylinder @param direction: The direction of the cylinder (1=x axis, 2=y axis, 3=z axis) @param r: The radius of the cylinder @param h: The length of the cylinder @type density: float @type direction: int @type r: float @type h: float """ dMassSetCylinder(&self._mass, density, direction, r, h) def setCylinderTotal(self, total_mass, direction, r, h): """setCylinderTotal(total_mass, direction, r, h) Set the mass parameters to represent a flat-ended cylinder of the given parameters and mass, with the center of mass at (0,0,0) relative to the body. The radius of the cylinder is r. The length of the cylinder is h. The cylinder's long axis is oriented along the body's x, y or z axis according to the value of direction (1=x, 2=y, 3=z). @param total_mass: The total mass of the cylinder @param direction: The direction of the cylinder (1=x axis, 2=y axis, 3=z axis) @param r: The radius of the cylinder @param h: The length of the cylinder @type total_mass: float @type direction: int @type r: float @type h: float """ dMassSetCylinderTotal(&self._mass, total_mass, direction, r, h) def setBox(self, density, lx, ly, lz): """setBox(density, lx, ly, lz) Set the mass parameters to represent a box of the given dimensions and density, with the center of mass at (0,0,0) relative to the body. The side lengths of the box along the x, y and z axes are lx, ly and lz. @param density: The density of the box @param lx: The length along the x axis @param ly: The length along the y axis @param lz: The length along the z axis @type density: float @type lx: float @type ly: float @type lz: float """ dMassSetBox(&self._mass, density, lx, ly, lz) def setBoxTotal(self, total_mass, lx, ly, lz): """setBoxTotal(total_mass, lx, ly, lz) Set the mass parameters to represent a box of the given dimensions and mass, with the center of mass at (0,0,0) relative to the body. The side lengths of the box along the x, y and z axes are lx, ly and lz. @param total_mass: The total mass of the box @param lx: The length along the x axis @param ly: The length along the y axis @param lz: The length along the z axis @type total_mass: float @type lx: float @type ly: float @type lz: float """ dMassSetBoxTotal(&self._mass, total_mass, lx, ly, lz) def adjust(self, newmass): """adjust(newmass) Adjust the total mass. Given mass parameters for some object, adjust them so the total mass is now newmass. This is useful when using the setXyz() methods to set the mass parameters for certain objects - they take the object density, not the total mass. @param newmass: The new total mass @type newmass: float """ dMassAdjust(&self._mass, newmass) def translate(self, t): """translate(t) Adjust mass parameters. Given mass parameters for some object, adjust them to represent the object displaced by (x,y,z) relative to the body frame. @param t: Translation vector (x, y, z) @type t: 3-tuple of floats """ dMassTranslate(&self._mass, t[0], t[1], t[2]) # def rotate(self, R): # """ # Given mass parameters for some object, adjust them to # represent the object rotated by R relative to the body frame. # """ # pass def add(self, Mass b): """add(b) Add the mass b to the mass object. Masses can also be added using the + operator. @param b: The mass to add to this mass @type b: Mass """ dMassAdd(&self._mass, &b._mass) def __getattr__(self, name): if name=="mass": return self._mass.mass elif name=="c": return (self._mass.c[0], self._mass.c[1], self._mass.c[2]) elif name=="I": return ((self._mass.I[0],self._mass.I[1],self._mass.I[2]), (self._mass.I[4],self._mass.I[5],self._mass.I[6]), (self._mass.I[8],self._mass.I[9],self._mass.I[10])) else: raise AttributeError,"Mass object has no attribute '"+name+"'" def __setattr__(self, name, value): if name=="mass": self.adjust(value) elif name=="c": raise AttributeError,"Use the setParameter() method to change c" elif name=="I": raise AttributeError,"Use the setParameter() method to change I" else: raise AttributeError,"Mass object has no attribute '"+name+"'" def __add__(self, Mass b): self.add(b) return self def __str__(self): m = str(self._mass.mass) sc0 = str(self._mass.c[0]) sc1 = str(self._mass.c[1]) sc2 = str(self._mass.c[2]) I11 = str(self._mass.I[0]) I22 = str(self._mass.I[5]) I33 = str(self._mass.I[10]) I12 = str(self._mass.I[1]) I13 = str(self._mass.I[2]) I23 = str(self._mass.I[6]) return "Mass=%s\nCg=(%s, %s, %s)\nI11=%s I22=%s I33=%s\nI12=%s I13=%s I23=%s"%(m,sc0,sc1,sc2,I11,I22,I33,I12,I13,I23) # return "Mass=%s / Cg=(%s, %s, %s) / I11=%s I22=%s I33=%s I12=%s I13=%s I23=%s"%(m,sc0,sc1,sc2,I11,I22,I33,I12,I13,I23) Py3ODE-1.2.0.dev15/src/ode.pyx000077500000000000000000000170041364423331700155530ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # Open Dynamics Engine # Copyright (c) 2001-2003, Russell L. Smith. # All rights reserved. #################################################################### include "declarations.pyx" # The World should keep a reference to joints/bodies, so that they won't # be deleted. # Excplicitly assign the module doc string to __doc__ # (otherwise it won't show up which is probably a "bug" in Pyrex (v0.9.2.1)) __doc__ = """Python Open Dynamics Engine (ODE) wrapper. This module contains classes and functions that wrap the functionality of the Open Dynamics Engine (ODE) which can be found at http://opende.sourceforge.net. There are the following classes and functions: - World - Body - JointGroup - Contact - Space - Mass Joint classes: - BallJoint - HingeJoint - Hinge2Joint - SliderJoint - UniversalJoint - FixedJoint - ContactJoint - AMotor - LMotor - Plane2DJoint Geom classes: - GeomSphere - GeomBox - GeomPlane - GeomCapsule - GeomCylinder - GeomRay - GeomTransform - GeomTriMesh / TriMeshData Functions: - CloseODE() - collide() """ ############################# Constants ############################### paramLoStop = 0 paramHiStop = 1 paramVel = 2 paramFMax = 3 paramFudgeFactor = 4 paramBounce = 5 paramCFM = 6 paramStopERP = 7 paramStopCFM = 8 paramSuspensionERP = 9 paramSuspensionCFM = 10 ParamLoStop = 0 ParamHiStop = 1 ParamVel = 2 ParamFMax = 3 ParamFudgeFactor = 4 ParamBounce = 5 ParamCFM = 6 ParamStopERP = 7 ParamStopCFM = 8 ParamSuspensionERP = 9 ParamSuspensionCFM = 10 ParamLoStop2 = 256+0 ParamHiStop2 = 256+1 ParamVel2 = 256+2 ParamFMax2 = 256+3 ParamFudgeFactor2 = 256+4 ParamBounce2 = 256+5 ParamCFM2 = 256+6 ParamStopERP2 = 256+7 ParamStopCFM2 = 256+8 ParamSuspensionERP2 = 256+9 ParamSuspensionCFM2 = 256+10 ParamLoStop3 = 512+0 ParamHiStop3 = 512+1 ParamVel3 = 512+2 ParamFMax3 = 512+3 ParamFudgeFactor3 = 512+4 ParamBounce3 = 512+5 ParamCFM3 = 512+6 ParamStopERP3 = 512+7 ParamStopCFM3 = 512+8 ParamSuspensionERP3 = 512+9 ParamSuspensionCFM3 = 512+10 ParamGroup = 256 ContactMu2 = 0x001 ContactFDir1 = 0x002 ContactBounce = 0x004 ContactSoftERP = 0x008 ContactSoftCFM = 0x010 ContactMotion1 = 0x020 ContactMotion2 = 0x040 ContactSlip1 = 0x080 ContactSlip2 = 0x100 ContactApprox0 = 0x0000 ContactApprox1_1 = 0x1000 ContactApprox1_2 = 0x2000 ContactApprox1 = 0x3000 AMotorUser = dAMotorUser AMotorEuler = dAMotorEuler Infinity = dInfinity ###################################################################### # Lookup table for geom objects: C ptr -> Python object ## This causes some kind of weird bug! Need to fix this. import weakref _geom_c2py_lut = weakref.WeakValueDictionary() # Mass include "mass.pyx" # Contact include "contact.pyx" # World include "world.pyx" # Body include "body.pyx" # Joint classes include "joints.pyx" # Geom base include "geomobject.pyx" # Space include "space.pyx" # Geom and support classes include "heightfielddata.pyx" include "geoms.pyx" # Include the generated trimesh switch file that either includes the real # trimesh wrapper (trimesh.pyx/trimeshdata.pyx) or a dummy wrapper # (trimesh_dummy.pyx) if trimesh support is not available/desired. include "_trimesh_switch.pyx" def collide(geom1, geom2): """collide(geom1, geom2) -> contacts Generate contact information for two objects. Given two geometry objects that potentially touch (geom1 and geom2), generate contact information for them. Internally, this just calls the correct class-specific collision functions for geom1 and geom2. [flags specifies how contacts should be generated if the objects touch. Currently the lower 16 bits of flags specifies the maximum number of contact points to generate. If this number is zero, this function just pretends that it is one - in other words you can not ask for zero contacts. All other bits in flags must be zero. In the future the other bits may be used to select other contact generation strategies.] If the objects touch, this returns a list of Contact objects, otherwise it returns an empty list. @param geom1: First Geom @type geom1: GeomObject @param geom2: Second Geom @type geom2: GeomObject @returns: Returns a list of Contact objects. """ cdef dContactGeom c[150] cdef long id1 cdef long id2 cdef int i, n cdef Contact cont id1 = geom1._id() id2 = geom2._id() n = dCollide(id1, id2, 150, c, sizeof(dContactGeom)) res = [] i=0 while itup # collide_callback is defined in space.pyx dSpaceCollide2(id1, id2, data, collide_callback) def areConnected(Body body1, Body body2): """areConnected(body1, body2) -> bool Return True if the two bodies are connected together by a joint, otherwise return False. @param body1: First body @type body1: Body @param body2: Second body @type body2: Body @returns: True if the bodies are connected """ if (body1 is environment): return False if (body2 is environment): return False return bool(dAreConnected( body1.bid, body2.bid)) def CloseODE(): """CloseODE() Deallocate some extra memory used by ODE that can not be deallocated using the normal destroy functions. """ dCloseODE() def InitODE(): '''InitODE() Initialize some ODE internals. This will be called for you when you "import ode", but you should call this again if you CloseODE().''' dInitODE() ###################################################################### #environment = Body(None) environment = None InitODE() Py3ODE-1.2.0.dev15/src/space.pyx000077500000000000000000000363071364423331700161060ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### class _SpaceIterator: """ Iterates over the geoms inside a Space (as reported by ODE). """ def __init__(self, space): self.space = space self.idx = 0 def __iter__(self): return self def __next__(self): if self.idx >= self.space.getNumGeoms(): raise StopIteration else: res = self.space.getGeom(self.idx) self.idx += 1 return res cdef class SpaceBase(GeomObject): """SpaceBase class - not initializable by itself A space is a non-placeable geom that can contain other geoms. It is similar to the rigid body concept of the "world", except that it applies to collision instead of dynamics. Space objects exist to make collision detection go faster. Without spaces, you might generate contacts in your simulation by calling dCollide to get contact points for every single pair of geoms. For N geoms this is O(N2) tests, which is too computationally expensive if your environment has many objects. A better approach is to insert the geoms into a space and call dSpaceCollide. The space will then perform collision culling, which means that it will quickly identify which pairs of geoms are potentially intersecting. Those pairs will be passed to a callback function, which can in turn call dCollide on them. This saves a lot of time that would have been spent in useless dCollide tests, because the number of pairs passed to the callback function will be a small fraction of every possible object-object pair. Spaces can contain other spaces. This is useful for dividing a collision environment into several hierarchies to further optimize collision detection speed. """ cdef dSpaceID sid def __cinit__(self, *a, **kw): self.sid = NULL def __init__(self, *a, **kw): raise NotImplementedError, "The SpaceBase class can't be used directly." def __dealloc__(self): if self.sid != NULL: dSpaceDestroy(self.sid) self.sid = NULL self.gid = NULL def _id(self): cdef long id id = self.sid return id def __len__(self): return self.getNumGeoms() def __iter__(self): return _SpaceIterator(self) def add(self, GeomObject geom): """add(geom) Add a geom to a space. The geom must not have been added to a space before. NOTE: This function only creates a weakref to the geom object. What this means is that geoms can get garbage collected if no other (strong) references remain to them. Proper management of references is the duty of the client code. @param geom: Geom object to add @type geom: GeomObject """ dSpaceAdd(self.sid, geom.gid) def remove(self, GeomObject geom): """remove(geom) Remove a geom from a space. @param geom: Geom object to remove @type geom: GeomObject """ dSpaceRemove(self.sid, geom.gid) def query(self, GeomObject geom): """query(geom) -> bool Return True if the given geom is in the space. @param geom: Geom object to check @type geom: GeomObject """ return dSpaceQuery(self.sid, geom.gid) def getNumGeoms(self): """getNumGeoms() -> int Return the number of geoms contained within the space. """ return dSpaceGetNumGeoms(self.sid) def getGeom(self, int idx): """getGeom(idx) -> GeomObject Return the geom with the given index contained within the space. @param idx: Geom index (0,1,...,getNumGeoms()-1) @type idx: int """ # Check the index if idx < 0 or idx >= dSpaceGetNumGeoms(self.sid): raise IndexError, "geom index out of range" cdef dGeomID gid gid = dSpaceGetGeom(self.sid, idx) if gid not in _geom_c2py_lut: raise RuntimeError, "geom id cannot be translated to a Python object" return _geom_c2py_lut[gid] def setManualCleanup(self, int mode): """setCleanup(int mode) Sets manual cleanup flag for a space. Manual cleanup flag marks a space as eligible for manual thread data cleanup. This function should be called for every space object right after creation in case if ODE has been initialized with the dInitFlagManualThreadCleanup flag. Failure to set manual cleanup flag for a space may lead to some resources remaining leaked until the program exit. @param mode: The cleanup mode, 0 or 1 @type mode: int """ # Check mode if not (mode == 0 or mode == 1): raise RuntimeError, "Cleanup mode needs to be either 0 or 1." dSpaceSetManualCleanup(self.sid, mode) def getManualCleanup(self): """getManualCleanup() -> int Get manual cleanup flag of a space. """ return dSpaceGetManualCleanup(self.sid) def setCleanup(self, int mode): """setCleanup(int mode) Set the clean-up mode of the space. If the clean-up mode is 1, then the contained geoms will be destroyed when the space is destroyed. If the clean-up mode is 0 this does not happen. The default clean-up mode for new spaces is 1. @param mode: The cleanup mode, 0 or 1 @type mode: int """ # Check mode if not (mode == 0 or mode == 1): raise RuntimeError, "Cleanup mode needs to be either 0 or 1." dSpaceSetCleanup(self.sid, mode) def getCleanup(self): """getCleanup() -> int Get the clean-up mode of the space. """ return dSpaceGetCleanup(self.sid) def setSublevel(self, int sublevel): """setSublevel(int sublevel) Set the sublevel value for the space. Sublevel affects how the space is handled in dSpaceCollide2 when it is collided with another space. If sublevels of both spaces match, the function iterates geometries of both spaces and collides them with each other. If sublevel of one space is greater than the sublevel of another one, only the geometries of the space with greater sublevel are iterated, another space is passed into collision callback as a geometry itself. By default all the spaces are assigned zero sublevel. NOTE: The space sublevel IS NOT automatically updated when one space is inserted into another or removed from one. It is a client's responsibility to update sublevel value if necessary. @param sublevel: The desired sublevel. @type sublevel: int """ dSpaceSetSublevel(self.sid, sublevel) def getSublevel(self): """getSublevel() -> int Get the sublevel value for the space. """ return dSpaceGetSublevel(self.sid) def clean(self): """clean() Clean the space. """ dSpaceClean(self.sid) def collide(self, arg, callback): """collide(arg, callback) Call a callback function one or more times, for all potentially intersecting objects in the space. The callback function takes 3 arguments: def NearCallback(arg, geom1, geom2): The arg parameter is just passed on to the callback function. Its meaning is user defined. The geom1 and geom2 arguments are the geometry objects that may be near each other. The callback function can call the function collide() (not the Space method) on geom1 and geom2, perhaps first determining whether to collide them at all based on other information. @param arg: A user argument that is passed to the callback function @param callback: Callback function @type callback: callable """ cdef void* data cdef object tup tup = (callback, arg) data = tup dSpaceCollide(self.sid, data, collide_callback) # Callback function for the dSpaceCollide() call in the Space.collide() method # The data parameter is a tuple (Python-Callback, Arguments). # The function calls a Python callback function with 3 arguments: # def callback(UserArg, Geom1, Geom2) # Geom1 and Geom2 are instances of GeomXyz classes. cdef void collide_callback(void* data, dGeomID o1, dGeomID o2): cdef object tup # cdef Space space cdef long id1, id2 # if (dGeomGetBody(o1)==dGeomGetBody(o2)): # return tup = data callback, arg = tup id1 = o1 id2 = o2 g1=_geom_c2py_lut[id1] g2=_geom_c2py_lut[id2] callback(arg,g1,g2) cdef class SimpleSpace(SpaceBase): """Simple space. This does not do any collision culling - it simply checks every possible pair of geoms for intersection, and reports the pairs whose AABBs overlap. The time required to do intersection testing for n objects is O(n**2). This should not be used for large numbers of objects, but it can be the preferred algorithm for a small number of objects. This is also useful for debugging potential problems with the collision system. """ def __cinit__(self, space = None): cdef SpaceBase sp cdef dSpaceID parentid parentid = NULL if space != None: sp = space parentid = sp.sid self.sid = dSimpleSpaceCreate(parentid) # Copy the ID self.gid = self.sid dSpaceSetCleanup(self.sid, 0) _geom_c2py_lut[self.sid]=self def __init__(self, space = None): pass cdef class HashSpace(SpaceBase): """Multi-resolution hash table space. This uses an internal data structure that records how each geom overlaps cells in one of several three dimensional grids. Each grid has cubical cells of side lengths 2**i, where i is an integer that ranges from a minimum to a maximum value. The time required to do intersection testing for n objects is O(n) (as long as those objects are not clustered together too closely), as each object can be quickly paired with the objects around it. """ def __cinit__(self, space = None): cdef SpaceBase sp cdef dSpaceID parentid parentid = NULL if space != None: sp = space parentid = sp.sid self.sid = dHashSpaceCreate(parentid) # Copy the ID self.gid = self.sid dSpaceSetCleanup(self.sid, 0) _geom_c2py_lut[self.sid]=self def __init__(self, space = None): pass def setLevels(self, int minlevel, int maxlevel): """setLevels(minlevel, maxlevel) Sets the size of the smallest and largest cell used in the hash table. The actual size will be 2 ** minlevel and 2 ** maxlevel respectively. """ if minlevel > maxlevel: raise ValueError, "minlevel ({0}) must be less than or equal to maxlevel ({1})".format(minlevel, maxlevel) dHashSpaceSetLevels(self.sid, minlevel, maxlevel) def getLevels(self): """getLevels() -> (minlevel, maxlevel) Gets the size of the smallest and largest cell used in the hash table. The actual size is 2 ** minlevel and 2 ** maxlevel respectively. """ cdef int minlevel cdef int maxlevel dHashSpaceGetLevels(self.sid, &minlevel, &maxlevel) return (minlevel, maxlevel) cdef class QuadTreeSpace(SpaceBase): """Quadtree space. This uses a pre-allocated hierarchical grid-based AABB tree to quickly cull collision checks. It's exceptionally quick for large amounts of objects in landscape-shaped worlds. The amount of memory used is 4 ** depth * 32 bytes. Currently getGeom() is not implemented for the quadtree space. """ def __cinit__(self, center, extents, depth, space = None): cdef SpaceBase sp cdef dSpaceID parentid cdef dVector3 c cdef dVector3 e parentid = NULL if space != None: sp = space parentid = sp.sid c[0] = center[0] c[1] = center[1] c[2] = center[2] e[0] = extents[0] e[1] = extents[1] e[2] = extents[2] self.sid = dQuadTreeSpaceCreate(parentid, c, e, depth) # Copy the ID self.gid = self.sid dSpaceSetCleanup(self.sid, 0) _geom_c2py_lut[self.sid]=self def __init__(self, center, extents, depth, space = None): pass cdef class SAPSpace(SpaceBase): """Sweep and prune space. Culls collisions based on ODE's implementation of the sweep and prune algorithm. sweep_order needs to be one of ["XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"] othervise defaults to "XYZ". """ def __cinit__(self, space = None, sweep_order = "XYZ"): cdef SpaceBase sp cdef dSpaceID parentid parentid = NULL if space != None: sp = space parentid = sp.sid order_value = 52 if sweep_order == "XYZ": order_value = 52 elif sweep_order == "XZY": order_value = 24 elif sweep_order == "YXZ": order_value = 33 elif sweep_order == "YZX": order_value = 9 elif sweep_order == "ZXY": order_value = 18 elif sweep_order == "ZYX": order_value = 6 self.sid = dSweepAndPruneSpaceCreate(parentid, order_value) # Copy the ID self.gid = self.sid dSpaceSetCleanup(self.sid, 0) _geom_c2py_lut[self.sid]=self def __init__(self, space = None, sweep_order = "XYZ"): pass def Space(space_type = 0): """Space factory function. Depending on the type argument this function either returns a SimpleSpace (space_type = 0) or a HashSpace (space_type = 1). This function is provided to remain compatible with previous versions of PyODE where there was only one Space class. >>> space = Space(space_type=0) # Create a SimpleSpace >>> space = Space(space_type=1) # Create a HashSpace """ if space_type == 0: return SimpleSpace() elif space_type == 1: return HashSpace() else: raise ValueError, "Unknown space type ({0})".format(space_type) Py3ODE-1.2.0.dev15/src/trimesh.pyx000077500000000000000000000056141364423331700164630ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # This file is included by _trimesh_switch.pyx if the variable # TRIMESH_SUPPORT was set to True in the setup script. # GeomTriMesh cdef class GeomTriMesh(GeomObject): """TriMesh object. To construct the trimesh geom you need a TriMeshData object that stores the actual mesh. This object has to be passed as first argument to the constructor. Constructor:: GeomTriMesh(data, space=None) """ # Keep a reference to the data cdef TriMeshData data def __cinit__(self, TriMeshData data not None, space=None): cdef SpaceBase sp cdef dSpaceID sid self.data = data sid=NULL if space!=None: sp = space sid = sp.sid self.gid = dCreateTriMesh(sid, data.tmdid, NULL, NULL, NULL) _geom_c2py_lut[self.gid] = self def __init__(self, TriMeshData data not None, space=None): self.space = space self.body = None def placeable(self): return True def _id(self): cdef long id id = self.gid return id def clearTCCache(self): """clearTCCache() Clears the internal temporal coherence caches. """ dGeomTriMeshClearTCCache(self.gid) def getTriangle(self, int idx): """getTriangle(idx) -> (v0, v1, v2) @param idx: Triangle index @type idx: int """ cdef dVector3 v0, v1, v2 cdef dVector3* vp0 cdef dVector3* vp1 cdef dVector3* vp2 vp0 = v0 vp1 = v1 vp2 = v2 dGeomTriMeshGetTriangle(self.gid, idx, vp0, vp1, vp2) return ((v0[0],v0[1],v0[2]), (v1[0],v1[1],v1[2]), (v2[0],v2[1],v2[2])) def getTriangleCount(self): """getTriangleCount() -> n Returns the number of triangles in the TriMesh.""" return dGeomTriMeshGetTriangleCount(self.gid) Py3ODE-1.2.0.dev15/src/trimesh_dummy.pyx000077500000000000000000000032031364423331700176660ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # These classes are included by the file _trimesh_switch.pyx if the # variable TRIMESH_SUPPORT was set to False in the setup script. cdef class TriMeshData: """This class stores the mesh data. This is only a dummy class that's used when trimesh support was disabled. """ def __init__(self): raise NotImplementedError, "Trimesh support is disabled" cdef class GeomTriMesh(GeomObject): """Trimesh object. This is only a dummy class that's used when trimesh support was disabled. """ def __init__(self, TriMeshData data not None, space=None): raise NotImplementedError, "Trimesh support is disabled" Py3ODE-1.2.0.dev15/src/trimeshdata.pyx000077500000000000000000000055711364423331700173170ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### cdef class TriMeshData: """This class stores the mesh data. """ cdef dTriMeshDataID tmdid cdef dReal* vertex_buffer cdef int* face_buffer def __cinit__(self): self.tmdid = dGeomTriMeshDataCreate() self.vertex_buffer = NULL self.face_buffer = NULL def __dealloc__(self): if self.tmdid!=NULL: dGeomTriMeshDataDestroy(self.tmdid) if self.vertex_buffer!=NULL: free(self.vertex_buffer) if self.face_buffer!=NULL: free(self.face_buffer) def build(self, verts, faces): """build(verts, faces) @param verts: Vertices @type verts: Sequence of 3-sequences of floats @param faces: Face definitions (three indices per face) @type faces: Sequence of 3-sequences of ints """ cdef int numverts cdef int numfaces cdef dReal* vp cdef int* fp cdef int a,b,c numverts = len(verts) numfaces = len(faces) # Allocate the vertex and face buffer self.vertex_buffer = malloc(numverts*4*sizeof(dReal)) self.face_buffer = malloc(numfaces*3*sizeof(int)) # Fill the vertex buffer vp = self.vertex_buffer for v in verts: vp[0] = v[0] vp[1] = v[1] vp[2] = v[2] vp[3] = 0 vp = vp+4 # Fill the face buffer fp = self.face_buffer for f in faces: a = f[0] b = f[1] c = f[2] if a<0 or b<0 or c<0 or a>=numverts or b>=numverts or c>=numverts: raise ValueError, "Vertex index out of range" fp[0] = a fp[1] = b fp[2] = c fp = fp+3 # Pass the data to ODE dGeomTriMeshDataBuildSimple(self.tmdid, self.vertex_buffer, numverts, self.face_buffer, numfaces*3)Py3ODE-1.2.0.dev15/src/world.pyx000077500000000000000000000315551364423331700161420ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # World cdef class World: """Dynamics world. The world object is a container for rigid bodies and joints. Constructor:: World() """ cdef dWorldID wid def __cinit__(self): self.wid = dWorldCreate() def __dealloc__(self): if self.wid!=NULL: dWorldDestroy(self.wid) # setGravity def setGravity(self, gravity): """setGravity(gravity) Set the world's global gravity vector. @param gravity: Gravity vector @type gravity: 3-sequence of floats """ dWorldSetGravity(self.wid, gravity[0], gravity[1], gravity[2]) # getGravity def getGravity(self): """getGravity() -> 3-tuple Return the world's global gravity vector as a 3-tuple of floats. """ cdef dVector3 g dWorldGetGravity(self.wid, g) return (g[0],g[1],g[2]) # setERP def setERP(self, erp): """setERP(erp) Set the global ERP value, that controls how much error correction is performed in each time step. Typical values are in the range 0.1-0.8. The default is 0.2. @param erp: Global ERP value @type erp: float """ dWorldSetERP(self.wid, erp) # getERP def getERP(self): """getERP() -> float Get the global ERP value, that controls how much error correction is performed in each time step. Typical values are in the range 0.1-0.8. The default is 0.2. """ return dWorldGetERP(self.wid) # setCFM def setCFM(self, cfm): """setCFM(cfm) Set the global CFM (constraint force mixing) value. Typical values are in the range 10E-9 - 1. The default is 10E-5 if single precision is being used, or 10E-10 if double precision is being used. @param cfm: Constraint force mixing value @type cfm: float """ dWorldSetCFM(self.wid, cfm) # getCFM def getCFM(self): """getCFM() -> float Get the global CFM (constraint force mixing) value. Typical values are in the range 10E-9 - 1. The default is 10E-5 if single precision is being used, or 10E-10 if double precision is being used. """ return dWorldGetCFM(self.wid) # step def step(self, stepsize): """step(stepsize) Step the world. This uses a "big matrix" method that takes time on the order of O(m3) and memory on the order of O(m2), where m is the total number of constraint rows. For large systems this will use a lot of memory and can be very slow, but this is currently the most accurate method. @param stepsize: Time step @type stepsize: float """ dWorldStep(self.wid, stepsize) # quickStep def quickStep(self, stepsize): """quickStep(stepsize) Step the world. This uses an iterative method that takes time on the order of O(m*N) and memory on the order of O(m), where m is the total number of constraint rows and N is the number of iterations. For large systems this is a lot faster than dWorldStep, but it is less accurate. @param stepsize: Time step @type stepsize: float """ dWorldQuickStep(self.wid, stepsize) # setQuickStepNumIterations def setQuickStepNumIterations(self, num): """setQuickStepNumIterations(num) Set the number of iterations that the QuickStep method performs per step. More iterations will give a more accurate solution, but will take longer to compute. The default is 20 iterations. @param num: Number of iterations @type num: int """ dWorldSetQuickStepNumIterations(self.wid, num) # getQuickStepNumIterations def getQuickStepNumIterations(self): """getQuickStepNumIterations() -> int Get the number of iterations that the QuickStep method performs per step. More iterations will give a more accurate solution, but will take longer to compute. The default is 20 iterations. """ return dWorldGetQuickStepNumIterations(self.wid) # setQuickStepNumIterations def setContactMaxCorrectingVel(self, vel): """setContactMaxCorrectingVel(vel) Set the maximum correcting velocity that contacts are allowed to generate. The default value is infinity (i.e. no limit). Reducing this value can help prevent "popping" of deeply embedded objects. @param vel: Maximum correcting velocity @type vel: float """ dWorldSetContactMaxCorrectingVel(self.wid, vel) # getQuickStepNumIterations def getContactMaxCorrectingVel(self): """getContactMaxCorrectingVel() -> float Get the maximum correcting velocity that contacts are allowed to generate. The default value is infinity (i.e. no limit). Reducing this value can help prevent "popping" of deeply embedded objects. """ return dWorldGetContactMaxCorrectingVel(self.wid) # setContactSurfaceLayer def setContactSurfaceLayer(self, depth): """setContactSurfaceLayer(depth) Set the depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. @param depth: Surface layer depth @type depth: float """ dWorldSetContactSurfaceLayer(self.wid, depth) # getContactSurfaceLayer def getContactSurfaceLayer(self): """getContactSurfaceLayer() Get the depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. """ return dWorldGetContactSurfaceLayer(self.wid) # setAutoDisableFlag def setAutoDisableFlag(self, flag): """setAutoDisableFlag(flag) Set the default auto-disable flag for newly created bodies. @param flag: True = Do auto disable @type flag: bool """ dWorldSetAutoDisableFlag(self.wid, flag) # getAutoDisableFlag def getAutoDisableFlag(self): """getAutoDisableFlag() -> bool Get the default auto-disable flag for newly created bodies. """ return dWorldGetAutoDisableFlag(self.wid) # setAutoDisableLinearThreshold def setAutoDisableLinearThreshold(self, threshold): """setAutoDisableLinearThreshold(threshold) Set the default auto-disable linear threshold for newly created bodies. @param threshold: Linear threshold @type threshold: float """ dWorldSetAutoDisableLinearThreshold(self.wid, threshold) # getAutoDisableLinearThreshold def getAutoDisableLinearThreshold(self): """getAutoDisableLinearThreshold() -> float Get the default auto-disable linear threshold for newly created bodies. """ return dWorldGetAutoDisableLinearThreshold(self.wid) # setAutoDisableAngularThreshold def setAutoDisableAngularThreshold(self, threshold): """setAutoDisableAngularThreshold(threshold) Set the default auto-disable angular threshold for newly created bodies. @param threshold: Angular threshold @type threshold: float """ dWorldSetAutoDisableAngularThreshold(self.wid, threshold) # getAutoDisableAngularThreshold def getAutoDisableAngularThreshold(self): """getAutoDisableAngularThreshold() -> float Get the default auto-disable angular threshold for newly created bodies. """ return dWorldGetAutoDisableAngularThreshold(self.wid) # setAutoDisableSteps def setAutoDisableSteps(self, steps): """setAutoDisableSteps(steps) Set the default auto-disable steps for newly created bodies. @param steps: Auto disable steps @type steps: int """ dWorldSetAutoDisableSteps(self.wid, steps) # getAutoDisableSteps def getAutoDisableSteps(self): """getAutoDisableSteps() -> int Get the default auto-disable steps for newly created bodies. """ return dWorldGetAutoDisableSteps(self.wid) # setAutoDisableTime def setAutoDisableTime(self, time): """setAutoDisableTime(time) Set the default auto-disable time for newly created bodies. @param time: Auto disable time @type time: float """ dWorldSetAutoDisableTime(self.wid, time) # getAutoDisableTime def getAutoDisableTime(self): """getAutoDisableTime() -> float Get the default auto-disable time for newly created bodies. """ return dWorldGetAutoDisableTime(self.wid) # setLinearDamping def setLinearDamping(self, scale): """setLinearDamping(scale) Set the world's linear damping scale. @param scale The linear damping scale that is to be applied to bodies. Default is 0 (no damping). Should be in the interval [0, 1]. @type scale: float """ dWorldSetLinearDamping(self.wid, scale) # getLinearDamping def getLinearDamping(self): """getLinearDamping() -> float Get the world's linear damping scale. """ return dWorldGetLinearDamping(self.wid) # setAngularDamping def setAngularDamping(self, scale): """setAngularDamping(scale) Set the world's angular damping scale. @param scale The angular damping scale that is to be applied to bodies. Default is 0 (no damping). Should be in the interval [0, 1]. @type scale: float """ dWorldSetAngularDamping(self.wid, scale) # getAngularDamping def getAngularDamping(self): """getAngularDamping() -> float Get the world's angular damping scale. """ return dWorldGetAngularDamping(self.wid) # impulseToForce def impulseToForce(self, stepsize, impulse): """impulseToForce(stepsize, impulse) -> 3-tuple If you want to apply a linear or angular impulse to a rigid body, instead of a force or a torque, then you can use this function to convert the desired impulse into a force/torque vector before calling the dBodyAdd... function. @param stepsize: Time step @param impulse: Impulse vector @type stepsize: float @type impulse: 3-tuple of floats """ cdef dVector3 force dWorldImpulseToForce(self.wid, stepsize, impulse[0], impulse[1], impulse[2], force) return (force[0], force[1], force[2]) # createBody # def createBody(self): # return Body(self) # createBallJoint # def createBallJoint(self, jointgroup=None): # return BallJoint(self, jointgroup) # createHingeJoint # def createHingeJoint(self, jointgroup=None): # return HingeJoint(self, jointgroup) # createHinge2Joint # def createHinge2Joint(self, jointgroup=None): # return Hinge2Joint(self, jointgroup) # createSliderJoint # def createSliderJoint(self, jointgroup=None): # return SliderJoint(self, jointgroup) # createFixedJoint # def createFixedJoint(self, jointgroup=None): # return FixedJoint(self, jointgroup) # createContactJoint # def createContactJoint(self, jointgroup, contact): # return ContactJoint(self, jointgroup, contact) Py3ODE-1.2.0.dev15/tests/000077500000000000000000000000001364423331700146105ustar00rootroot00000000000000Py3ODE-1.2.0.dev15/tests/test_installation.py000077500000000000000000000024731364423331700207330ustar00rootroot00000000000000#!/usr/bin/env python ###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### import unittest import math import subprocess from xode import node, transform, parser, errors class TestOdeInstall(unittest.TestCase): def setUp(self): pass def testOdeInstall(self): subprocess.check_call('./install_ode.sh') if (__name__ == '__main__'): unittest.main() Py3ODE-1.2.0.dev15/tests/test_xode.py000077500000000000000000000770471364423331700172020ustar00rootroot00000000000000#!/usr/bin/env python ###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### import unittest import ode import math from xode import node, transform, parser, errors test_doc = ''' ''' trimesh_doc=''' ''' # def feq(n1, n2, error=0.1): # """ # Compare two floating point numbers. If the differ by less than C{error}, # return True; otherwise, return False. # """ # # n = math.fabs(n1 - n2) # if (n <= error): # return True # else: # return False # # class Class1: # pass # # class Class2: # pass class TestFake(unittest.TestCase): # Unit tests not working for now even on main PyODE # TODO Debug tests def setUp(self): pass def testFake(self): pass # class TestTreeNode(unittest.TestCase): # # def setUp(self): # self.node1 = node.TreeNode('node1', None) # self.node2 = node.TreeNode('node2', self.node1) # self.node3 = node.TreeNode('node3', self.node2) # self.node4 = node.TreeNode('node4', self.node3) # # self.t2 = transform.Transform() # self.t2.scale(2.0, 3.0, 4.0) # self.node2.setNodeTransform(self.t2) # # self.t3 = transform.Transform() # self.t3.rotate(1.0, 2.0, 3.0) # self.node3.setNodeTransform(self.t3) # # self.t4 = transform.Transform() # self.t4.translate(2.0, 3.0, 1.0) # self.node4.setNodeTransform(self.t4) # # self.node1.setODEObject(Class2()) # self.node2.setODEObject(Class2()) # self.node3.setODEObject(Class1()) # # def testGetName(self): # self.assertEqual(self.node1.getName(), 'node1') # # def testGetParent(self): # self.assertEqual(self.node2.getParent(), self.node1) # # def testGetChildren(self): # self.assertEqual(self.node1.getChildren(), [self.node2]) # self.assertEqual(self.node2.getChildren(), [self.node3]) # self.assertEqual(self.node3.getChildren(), [self.node4]) # self.assertEqual(self.node4.getChildren(), []) # # def testNamedChildLocal(self): # self.assertEqual(self.node1.namedChild('node2'), self.node2) # # def testNamedChildRemote(self): # self.assertEqual(self.node1.namedChild('node3'), self.node3) # # def testNamedChildNotFound(self): # self.assertRaises(KeyError, self.node1.namedChild, 'undefined') # # def testGetFirstAncestor(self): # self.assertEqual(self.node3.getFirstAncestor(Class2), self.node2) # # def testGetFirstAncestorNotFound(self): # self.assertRaises(node.AncestorNotFoundError, # self.node3.getFirstAncestor, Class1) # # def testInitialTransform(self): # t = transform.Transform() # t.setIdentity() # self.assertEqual(self.node1.getNodeTransform().m, t.m) # # def testGetTransform(self): # ref = self.node1.getNodeTransform() * self.t2 * self.t3 # self.assertEqual(self.node3.getTransform().m, ref.m) # # def testGetTransformUntil(self): # ref = self.t3 * self.t4 # self.assertEqual(self.node4.getTransform(self.node2).m, ref.m) # class TestParser(unittest.TestCase): # def setUp(self): # self.p = parser.Parser() # self.root = self.p.parseString(test_doc) # # def assertEqualf(a, b): # self.assertEqual(feq(a, b), True) # self.assertEqualf = assertEqualf # # class TestWorldParser(TestParser): # def testInstance(self): # world = self.root.namedChild('world1').getODEObject() # self.assert_(isinstance(world, ode.World)) # # class TestSpaceParser(TestParser): # def setUp(self): # TestParser.setUp(self) # self.simpleSpace = self.root.namedChild('space1').getODEObject() # # doc = ''' # # # # ''' # # self.p2 = parser.Parser() # self.p2.setParams(spaceFactory=ode.HashSpace) # self.root2 = self.p2.parseString(doc) # self.hashSpace = self.root2.namedChild('space1').getODEObject() # # def makeSpace(): # return ode.QuadTreeSpace((0, 0, 0), (2, 2, 2), 3) # # self.p3 = parser.Parser() # self.p3.setParams(spaceFactory=makeSpace) # self.root3 = self.p3.parseString(doc) # self.quadSpace = self.root3.namedChild('space1').getODEObject() # # def testSimpleInstance(self): # self.assert_(isinstance(self.simpleSpace, ode.SimpleSpace)) # # def testHashInstance(self): # self.assert_(isinstance(self.hashSpace, ode.HashSpace)) # # def testQuadInstance(self): # self.assert_(isinstance(self.quadSpace, ode.QuadTreeSpace)) # # def testSpaceBase(self): # self.assert_(isinstance(self.simpleSpace, ode.SpaceBase)) # self.assert_(isinstance(self.hashSpace, ode.SpaceBase)) # self.assert_(isinstance(self.quadSpace, ode.SpaceBase)) # # class TestBodyParser(TestParser): # def setUp(self): # TestParser.setUp(self) # self.body1 = self.root.namedChild('body1').getODEObject() # self.body3 = self.root.namedChild('body3').getODEObject() # self.body6 = self.root.namedChild('body6').getODEObject() # # def testInstance(self): # self.assert_(isinstance(self.body1, ode.Body)) # # def testRotation(self): # ref = transform.Transform() # ref.rotate(0.0, 0.0, 0.78) # # rot = self.body6.getRotation() # for n1, n2 in zip(ref.getRotation(), rot): # self.assert_(feq(n1, n2)) # # def testPosition(self): # self.assertEqual(self.body3.getPosition(), (10.0, 20.0, 30.0)) # # def testEnable(self): # self.assertEqual(self.body1.isEnabled(), 0) # # def testGravityMode(self): # self.assertEqual(self.body1.getGravityMode(), 0) # # def testTorque(self): # self.assertEqual(self.body1.getTorque(), (1.0, 2.0, 3.0)) # # def testForce(self): # self.assertEqual(self.body1.getForce(), (2.0, 3.0, 4.0)) # # def testFiniteRotation(self): # self.assertEqual(self.body1.getFiniteRotationMode(), 1) # x, y, z = self.body1.getFiniteRotationAxis() # self.assertEqual(x, y, z) # # def testLinearVel(self): # self.assertEqual(self.body1.getLinearVel(), (1.0, 2.0, 3.0)) # # def testAngularVel(self): # self.assertEqual(self.body1.getAngularVel(), (3.0, 2.0, 1.0)) # # class TestMassParser(TestParser): # def setUp(self): # TestParser.setUp(self) # self.mass0 = self.root.namedChild('mass0').getODEObject() # self.mass1 = self.root.namedChild('mass1').getODEObject() # self.mass2 = self.root.namedChild('mass2').getODEObject() # # self.ref1 = ode.Mass() # self.ref1.setSphere(1.0, 1.0) # # self.ref2 = ode.Mass() # self.ref2.setSphere(2.0, 10.0) # self.ref2.adjust(4.0) # # def testInstance(self): # self.assert_(isinstance(self.mass1, ode.Mass)) # # def testDefault(self): # self.assertEqual(self.mass0.c, self.ref1.c) # self.assertEqual(self.mass0.I, self.ref1.I) # self.assertEqual(self.mass0.mass, self.ref1.mass) # # def testTotal(self): # self.assertEqual(self.mass2.mass, 4.0) # # def testSphere(self): # self.assertEqual(self.ref2.c, self.mass2.c) # self.assertEqual(self.ref2.I, self.mass2.I) # # def testAdd(self): # ref = ode.Mass() # ref.setSphere(1.0, 1.0) # ref.add(self.ref2) # # self.assertEqual(ref.c, self.mass1.c) # self.assertEqual(ref.I, self.mass1.I) # # class TestJointParser(TestParser): # def setUp(self): # TestParser.setUp(self) # self.body1 = self.root.namedChild('body1').getODEObject() # self.body2 = self.root.namedChild('body2').getODEObject() # self.joint1 = self.root.namedChild('joint1').getODEObject() # self.joint2 = self.root.namedChild('joint2').getODEObject() # self.joint3 = self.root.namedChild('joint3').getODEObject() # self.joint4 = self.root.namedChild('joint4').getODEObject() # self.joint5 = self.root.namedChild('joint5').getODEObject() # self.joint6 = self.root.namedChild('joint6').getODEObject() # self.joint7 = self.root.namedChild('joint7').getODEObject() # self.joint8 = self.root.namedChild('joint8').getODEObject() # self.joint9 = self.root.namedChild('joint9').getODEObject() # self.joint10 = self.root.namedChild('joint10').getODEObject() # # def testBallInstance(self): # self.assert_(isinstance(self.joint1, ode.BallJoint)) # # def testBodyAncestor(self): # self.assertEqual(self.joint1.getBody(0), self.body1) # # def testEnvironment(self): # self.assertEqual(self.joint1.getBody(1), ode.environment) # # def testBodyReference(self): # self.assertEqual(self.joint2.getBody(0), self.body1) # # def testSpaceParent(self): # self.assertEqual(self.joint3.getBody(0), self.body1) # self.assertEqual(self.joint3.getBody(1), self.body2) # # def testBallAnchor(self): # for n1, n2 in zip(self.joint1.getAnchor(), (1.0, 2.0, 3.0)): # self.assert_(feq(n1, n2)) # # def testFixedInstance(self): # self.assert_(isinstance(self.joint4, ode.FixedJoint)) # # def testHingeInstance(self): # self.assert_(isinstance(self.joint5, ode.HingeJoint)) # # def testHingeAxis(self): # self.assertEqual(self.joint5.getAxis(), (1.0, 0.0, 0.0)) # # def testSliderInstance(self): # self.assert_(isinstance(self.joint6, ode.SliderJoint)) # # def testSliderAxis(self): # self.assertEqual(self.joint6.getAxis(), (0.0, 1.0, 0.0)) # # def testUniversalInstance(self): # self.assert_(isinstance(self.joint7, ode.UniversalJoint)) # # def testUniversalAxis1(self): # ref = (1.0, 0.0, 0.0) # axis1 = self.joint7.getAxis1() # # for r, a in zip(ref, axis1): # self.assert_(feq(r, a)) # # def testUniversalAxis2(self): # ref = (0.0, 1.0, 0.0) # axis2 = self.joint7.getAxis2() # # for r, a in zip(ref, axis2): # self.assert_(feq(r, a)) # # def testHinge2Instance(self): # self.assert_(isinstance(self.joint8, ode.Hinge2Joint)) # # def testHinge2Axis1(self): # ref = (0.0, 0.0, 1.0) # axis1 = self.joint8.getAxis1() # # for r, a in zip(ref, axis1): # self.assert_(feq(r, a)) # # def testHinge2Axis2(self): # ref = (0.0, 1.0, 0.0) # axis2 = self.joint8.getAxis2() # # for r, a in zip(ref, axis2): # self.assert_(feq(r, a)) # # def testAMotorInstance(self): # self.assert_(isinstance(self.joint9, ode.AMotor)) # # def testAMotorNumAxes1(self): # self.assertEqual(self.joint9.getNumAxes(), 1) # # def testAMotorNumAxes3(self): # self.assertEqual(self.joint10.getNumAxes(), 3) # # def testAMotorAxes1(self): # ref = (0.0, 1.0, 0.0) # axis1 = self.joint9.getAxis(0) # self.assertEqual(ref, axis1) # # def testAMotorAxes3(self): # ref = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] # axes = [self.joint10.getAxis(0), self.joint10.getAxis(1), # self.joint10.getAxis(2)] # self.assertEqual(ref, axes) # # def testAxisParamLoStop(self): # self.assertEqualf(self.joint6.getParam(ode.paramLoStop), 1.0) # # def testAxisParamHiStop(self): # self.assertEqualf(self.joint6.getParam(ode.paramHiStop), 2.0) # # def testAxisParamVel(self): # self.assertEqualf(self.joint6.getParam(ode.paramVel), 3.0) # # def testAxisParamFMax(self): # self.assertEqualf(self.joint6.getParam(ode.paramFMax), 4.0) # # def testAxisParamFudgeFactor(self): # self.assertEqualf(self.joint6.getParam(ode.paramFudgeFactor), 0.5) # # def testAxisParamBounce(self): # self.assertEqualf(self.joint6.getParam(ode.paramBounce), 6.0) # # def testAxisParamCFM(self): # self.assertEqualf(self.joint6.getParam(ode.paramCFM), 7.0) # # def testAxisParamStopERP(self): # self.assertEqualf(self.joint6.getParam(ode.paramStopERP), 8.0) # # def testAxisParamStopCFM(self): # self.assertEqualf(self.joint6.getParam(ode.paramStopCFM), 9.0) # # def testAxisParamSuspensionERP(self): # self.assertEqualf(self.joint8.getParam(ode.paramSuspensionERP), 2.0) # # def testAxisParamSuspensionCFM(self): # self.assertEqualf(self.joint8.getParam(ode.paramSuspensionCFM), 3.0) # # def testAxis2FudgeFactor(self): # self.assertEqualf(self.joint8.getParam(ode.ParamFudgeFactor2), 0.2) # # class TestGeomParser(TestParser): # def setUp(self): # TestParser.setUp(self) # # self.geom1 = self.root.namedChild('geom1').getODEObject() # self.geom2 = self.root.namedChild('geom2').getODEObject() # self.geom3 = self.root.namedChild('geom3').getODEObject() # self.geom4 = self.root.namedChild('geom4').getODEObject() # self.geom5 = self.root.namedChild('geom5').getODEObject() # self.geom6 = self.root.namedChild('geom6').getODEObject() # # self.body1 = self.root.namedChild('body1').getODEObject() # self.space1 = self.root.namedChild('space1').getODEObject() # # def testSpaceAncestor(self): # self.assertEqual(self.geom1.getSpace(), self.space1) # # def testBodyAttach(self): # self.assertEqual(self.geom1.getBody(), self.body1) # # def testBoxInstance(self): # self.assert_(isinstance(self.geom1, ode.GeomBox)) # # def testBoxSize(self): # self.assertEqual(self.geom1.getLengths(), (10.0, 20.0, 30.0)) # # def testCCylinderInstance(self): # self.assert_(isinstance(self.geom2, ode.GeomCCylinder)) # # def testCCylinderParams(self): # self.assertEqual(self.geom2.getParams(), (15.0, 3.0)) # # def testSphereInstance(self): # self.assert_(isinstance(self.geom5, ode.GeomSphere)) # # def testSphereRadius(self): # self.assertEqual(self.geom5.getRadius(), 23.0) # # def testPlaneInstance(self): # self.assert_(isinstance(self.geom4, ode.GeomPlane)) # # def testPlaneParams(self): # self.assertEqual(self.geom4.getParams(), ((0.0, 1.0, 0.0), 17.0)) # # def testRayInstance(self): # self.assert_(isinstance(self.geom3, ode.GeomRay)) # # def testRayLength(self): # self.assertEqual(self.geom3.getLength(), 11.0) # # def testIndependantRotation(self): # ref = transform.Transform() # ref.rotate(0.0, 0.0, 0.78) # # for n1, n2 in zip(self.geom5.getRotation(), ref.getRotation()): # self.assert_(feq(n1, n2)) # # def testIndependantPosition(self): # self.assertEqual(self.geom5.getPosition(), (1.0, 2.0, 3.0)) # # def testTransformInstance(self): # self.assert_(isinstance(self.geom6, ode.GeomTransform)) # # def testTransformGeomInstance(self): # self.assert_(isinstance(self.geom6.getGeom(), ode.GeomSphere)) # # def testTransformPosition(self): # pos = self.geom6.getGeom().getPosition() # self.assertEqual(pos, (1.0, 2.0, 3.0)) # # def testTransformRotation(self): # ref = transform.Transform() # ref.rotate(0.78, 0.0, 0.0) # rot = self.geom6.getGeom().getRotation() # # for n1, n2 in zip(rot, ref.getRotation()): # self.assert_(feq(n1, n2)) # # class TestTransformParser(TestParser): # def setUp(self): # TestParser.setUp(self) # self.world1 = self.root.namedChild('world1') # self.body1 = self.root.namedChild('body1') # self.body5 = self.root.namedChild('body5') # self.body7 = self.root.namedChild('body7') # # def testMatrixStyle(self): # t = self.world1.getNodeTransform() # self.assertEqual(t.m, [[1.0, 2.0, 3.0, 4.0], # [1.2, 2.2, 3.2, 4.2], # [1.4, 2.4, 3.4, 4.4], # [1.8, 2.8, 3.8, 4.8]]) # # def testVector(self): # ref = transform.Transform() # ref.rotate(45.0, 45.0, 45.0) # ref.translate(10.0, 11.0, 12.0) # ref.scale(2.0, 2.0, 2.0) # self.assertEqual(self.body1.getNodeTransform().m, ref.m) # # def testAbsolute(self): # t = self.body7.getTransform() # self.assertEqual(t.m, [[1.0, 2.0, 3.0, 4.0], # [1.2, 2.2, 3.2, 4.2], # [1.4, 2.4, 3.4, 4.4], # [1.8, 2.8, 3.8, 4.8]]) # # def testRelative(self): # t1 = transform.Transform() # t1.translate(1.0, 1.0, 1.0) # t2 = transform.Transform() # t2.translate(2.0, 2.0, 2.0) # # t3 = t1 * t2 # # self.assertEqual(self.body5.getTransform().m, t3.m) # # def testMultiply(self): # t1 = transform.Transform() # t2 = transform.Transform() # for r in range(4): # for c in range(4): # t1.m[r][c] = 1 # t2.m[r][c] = 2 # # result = t1 * t2 # for r in range(4): # for c in range(4): # self.assertEqual(result.m[r][c], 8) # # def testInitialIdentity(self): # t = transform.Transform() # for r in range(4): # for c in range(4): # if (r == c): # self.assertEqual(t.m[r][c], 1) # else: # self.assertEqual(t.m[r][c], 0) # # class TestTriMeshParser(unittest.TestCase): # def setUp(self): # self.p = parser.Parser() # self.root = self.p.parseString(trimesh_doc) # self.trimesh1 = self.root.namedChild('trimesh1').getODEObject() # # def testInstance(self): # self.assert_(isinstance(self.trimesh1, ode.GeomTriMesh)) # # def testTriangles(self): # triangles = [(1, 2, 3), # (2, 1, 4), # (3, 2, 1)] # # vertices = [(0.0, 1.0, 1.0), # (1.0, 2.0, 2.0), # (2.0, 0.0, 1.0), # (0.0, 1.0, 2.0), # (2.0, 2.0, 1.0)] # # for i in range(len(triangles)): # tri = self.trimesh1.getTriangle(i) # # ref = [] # for v in triangles[i]: # ref.append(vertices[v-1]) # # self.assertEqual(tri, tuple(ref)) # #class TestInvalid(unittest.TestCase): # def setUp(self): # self.p = parser.Parser() # # class TestInvalidTags(TestInvalid): # def testRoot(self): # doc = ''' # ''' # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testRootChild(self): # doc = ''' # ''' # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testWorldChild(self): # doc = ''' # # # ''' # # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testSpaceChild(self): # doc = ''' # # # ''' # # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testMassChild(self): # doc = ''' # # # # # # # ''' # # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testJointChild(self): # doc = ''' # ''' # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testGeomChild(self): # doc = ''' # ''' # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # def testTriMeshChild(self): # doc = ''' # # # ''' # self.assertRaises(errors.ChildError, self.p.parseString, doc) # # class TestInvalidBody(TestInvalid): # def testBadVector(self): # doc = ''' # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testBodyEnable(self): # doc = ''' # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testFiniteRotationMode(self): # doc = ''' # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testFiniteRotationAxes(self): # doc = ''' # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # class TestInvalidJoint(TestInvalid): # def testEqualLinks(self): # doc = ''' # # # # # ''' # # # both links are ode.environment # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testNoType(self): # doc = ''' # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testWrongType(self): # doc = ''' # # # # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testMisplacedReference(self): # doc = ''' # # # # # # # # # ''' # # bodies must be defined before the joint # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testSliderAxes(self): # doc = ''' # # # # # # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # def testInvalidParam(self): # doc = ''' # # # # # # # # # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) # # class TestInvalidGeom(TestInvalid): # def testNoType(self): # doc = ''' # # # ''' # # self.assertRaises(errors.InvalidError, self.p.parseString, doc) if (__name__ == '__main__'): unittest.main() Py3ODE-1.2.0.dev15/xode/000077500000000000000000000000001364423331700144055ustar00rootroot00000000000000Py3ODE-1.2.0.dev15/xode/.cvsignore000077500000000000000000000000061364423331700164040ustar00rootroot00000000000000*.pyc Py3ODE-1.2.0.dev15/xode/__init__.py000077500000000000000000000021151364423331700165200ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ @author: U{Timothy Stranex} """ Py3ODE-1.2.0.dev15/xode/body.py000077500000000000000000000164761364423331700157350ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Body and Mass Parser @author: U{Timothy Stranex} """ import ode from . import errors, node, joint, transform, geom class Body(node.TreeNode): """ Represents an ode.Body object and corresponds to the tag. """ def __init__(self, name, parent, attrs): node.TreeNode.__init__(self, name, parent) world = parent.getFirstAncestor(ode.World) self.setODEObject(ode.Body(world.getODEObject())) enabled = attrs.get('enabled', 'true') if (enabled not in ['true', 'false']): raise errors.InvalidError("Enabled attribute must be either 'true'"\ " or 'false'.") else: if (enabled == 'false'): self.getODEObject().disable() gravitymode = int(attrs.get('gravitymode', 1)) if (gravitymode == 0): self.getODEObject().setGravityMode(0) self._mass = None self._transformed = False def takeParser(self, parser): """ Handle further parsing. It should be called immediately after the tag has been encountered. """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _applyTransform(self): if (self._transformed): return t = self.getTransform() body = self.getODEObject() body.setPosition(t.getPosition()) body.setRotation(t.getRotation()) self._transformed = True def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) else: self._applyTransform() if (name == 'torque'): self.getODEObject().setTorque(self._parser.parseVector(attrs)) elif (name == 'force'): self.getODEObject().setForce(self._parser.parseVector(attrs)) elif (name == 'finiteRotation'): mode = int(attrs['mode']) try: axis = (float(attrs['xaxis']), float(attrs['yaxis']), float(attrs['zaxis'])) except KeyError: raise errors.InvalidError('finiteRotation element must have' \ ' xaxis, yaxis and zaxis attributes') if (mode not in [0, 1]): raise errors.InvalidError('finiteRotation mode attribute must' \ ' be either 0 or 1.') self.getODEObject().setFiniteRotationMode(mode) self.getODEObject().setFiniteRotationAxis(axis) elif (name == 'linearVel'): self.getODEObject().setLinearVel(self._parser.parseVector(attrs)) elif (name == 'angularVel'): self.getODEObject().setAngularVel(self._parser.parseVector(attrs)) elif (name == 'mass'): self._mass = Mass(nodeName, self) self._mass.takeParser(self._parser) elif (name == 'joint'): j = joint.Joint(nodeName, self) j.takeParser(self._parser) elif (name == 'body'): b = Body(nodeName, self, attrs) b.takeParser(self._parser) elif (name == 'geom'): g = geom.Geom(nodeName, self) g.takeParser(self._parser) elif (name == 'transform'): # so it doesn't raise ChildError pass else: raise errors.ChildError('body', name) def _endElement(self, name): if (name == 'body'): self._parser.pop() self._applyTransform() if (self._mass is not None): self.getODEObject().setMass(self._mass.getODEObject()) class Mass(node.TreeNode): """ Represents an ode.Mass object and corresponds to the tag. """ def __init__(self, name, parent): node.TreeNode.__init__(self, name, parent) mass = ode.Mass() mass.setSphere(1.0, 1.0) self.setODEObject(mass) body = self.getFirstAncestor(ode.Body) body.getODEObject().setMass(mass) def takeParser(self, parser): """ Handle further parsing. It should be called immediately after the tag is encountered. """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'mass_struct'): pass elif (name == 'mass_shape'): self._parseMassShape(attrs) elif (name == 'transform'): # parse transform pass elif (name == 'adjust'): total = float(attrs['total']) self.getODEObject().adjust(total) elif (name == 'mass'): mass = Mass(nodeName, self) mass.takeParser(self._parser) else: raise errors.ChildError('mass', name) def _endElement(self, name): if (name == 'mass'): try: mass = self.getFirstAncestor(ode.Mass) except node.AncestorNotFoundError: pass else: mass.getODEObject().add(self.getODEObject()) self._parser.pop() def _parseMassShape(self, attrs): density = attrs.get('density', None) mass = self.getODEObject() def start(name, attrs): if (name == 'sphere'): radius = float(attrs.get('radius', 1.0)) if (density is not None): mass.setSphere(float(density), radius) elif (name == 'box'): lx = float(attrs['sizex']) ly = float(attrs['sizey']) lz = float(attrs['sizez']) if (density is not None): mass.setBox(float(density), lx, ly, lz) else: # FIXME: Implement remaining mass shapes. raise NotImplementedError() def end(name): if (name == 'mass_shape'): self._parser.pop() self._parser.push(startElement=start, endElement=end) Py3ODE-1.2.0.dev15/xode/errors.py000077500000000000000000000040131364423331700162740ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Exceptions @author: U{Timothy Stranex} """ class InvalidError(Exception): """ Raised when an XODE document is invalid. """ class ChildError(InvalidError): """ Raised when an invalid child element is found. @ivar parent: The parent element. @type parent: str @ivar child: The invalid child element. @type child: str """ def __init__(self, parent, child): self.parent = parent self.child = child def __str__(self): return '<%s> is not a valid child of <%s>.' % (self.child, self.parent) class MissingElementError(InvalidError): """ Raised when a child element is missing. @ivar parent: The parent element. @type parent: str @ivar child: The missing child element. @type child: str """ def __init__(self, parent, child): self.parent = parent self.child = child def __str__(self): return 'Missing child <%s> of <%s>.' % (self.child, self.parent) Py3ODE-1.2.0.dev15/xode/geom.py000077500000000000000000000201141364423331700157070ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Geom Parser @author: U{Timothy Stranex} """ import ode from . import errors, node, joint, body, transform class Geom(node.TreeNode): """ Represents an C{ode.Geom} object and corresponds to the tag. """ def __init__(self, name, parent): node.TreeNode.__init__(self, name, parent) self._space = self.getFirstAncestor(ode.SpaceBase).getODEObject() self._transformed = False try: self._body = self.getFirstAncestor(ode.Body) except node.AncestorNotFoundError: self._body = None def takeParser(self, parser): """ Handle further parsing. It should be called immediately after the tag has been encountered. """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) self._transformed = True elif (name == 'box'): self._parseGeomBox(attrs) elif (name == 'cappedCylinder'): self._parseGeomCCylinder(attrs) elif (name == 'cone'): raise NotImplementedError() elif (name == 'cylinder'): raise NotImplementedError() elif (name == 'plane'): self._parseGeomPlane(attrs) elif (name == 'ray'): self._parseGeomRay(attrs) elif (name == 'sphere'): self._parseGeomSphere(attrs) elif (name == 'trimesh'): self._parseTriMesh(attrs) elif (name == 'geom'): g = Geom(nodeName, self) g.takeParser(self._parser) elif (name == 'body'): b = body.Body(nodeName, self, attrs) b.takeParser(self._parser) elif (name == 'joint'): j = joint.Joint(nodename, self) j.takeParser(self._parser) elif (name == 'jointgroup'): pass elif (name == 'ext'): pass else: raise errors.ChildError('geom', name) def _endElement(self, name): if (name == 'geom'): obj = self.getODEObject() if (obj is None): raise errors.InvalidError('No geom type element found.') self._parser.pop() def _setObject(self, kclass, **kwargs): """ Create the Geom object and apply transforms. Only call for placeable Geoms. """ if (self._body is None): # The Geom is independant so it can have its own transform kwargs['space'] = self._space obj = kclass(**kwargs) t = self.getTransform() obj.setPosition(t.getPosition()) obj.setRotation(t.getRotation()) self.setODEObject(obj) elif (self._transformed): # The Geom is attached to a body so to transform it, it must # by placed in a GeomTransform and its transform is relative # to the body. kwargs['space'] = None obj = kclass(**kwargs) t = self.getTransform(self._body) obj.setPosition(t.getPosition()) obj.setRotation(t.getRotation()) trans = ode.GeomTransform(self._space) trans.setGeom(obj) trans.setBody(self._body.getODEObject()) self.setODEObject(trans) else: kwargs['space'] = self._space obj = kclass(**kwargs) obj.setBody(self._body.getODEObject()) self.setODEObject(obj) def _parseGeomBox(self, attrs): def start(name, attrs): if (name == 'ext'): pass else: raise errors.ChildError('box', name) def end(name): if (name == 'box'): self._parser.pop() lx = float(attrs['sizex']) ly = float(attrs['sizey']) lz = float(attrs['sizez']) self._setObject(ode.GeomBox, lengths=(lx, ly, lz)) self._parser.push(startElement=start, endElement=end) def _parseGeomCCylinder(self, attrs): def start(name, attrs): if (name == 'ext'): pass else: raise errors.ChildError('cappedCylinder', name) def end(name): if (name == 'cappedCylinder'): self._parser.pop() radius = float(attrs['radius']) length = float(attrs['length']) self._setObject(ode.GeomCCylinder, radius=radius, length=length) self._parser.push(startElement=start, endElement=end) def _parseGeomSphere(self, attrs): def start(name, attrs): if (name == 'ext'): pass else: raise errors.ChildError('sphere', name) def end(name): if (name == 'sphere'): self._parser.pop() radius = float(attrs['radius']) self._setObject(ode.GeomSphere, radius=radius) self._parser.push(startElement=start, endElement=end) def _parseGeomPlane(self, attrs): def start(name, attrs): if (name == 'ext'): pass else: raise errors.ChildError('plane', name) def end(name): if (name == 'plane'): self._parser.pop() a = float(attrs['a']) b = float(attrs['b']) c = float(attrs['c']) d = float(attrs['d']) self.setODEObject(ode.GeomPlane(self._space, (a, b, c), d)) self._parser.push(startElement=start, endElement=end) def _parseGeomRay(self, attrs): def start(name, attrs): if (name == 'ext'): pass else: raise errors.ChildError('ray', name) def end(name): if (name == 'ray'): self._parser.pop() length = float(attrs['length']) self.setODEObject(ode.GeomRay(self._space, length)) self._parser.push(startElement=start, endElement=end) def _parseTriMesh(self, attrs): vertices = [] triangles = [] def start(name, attrs): if (name == 'vertices'): pass elif (name == 'triangles'): pass elif (name == 'v'): vertices.append(self._parser.parseVector(attrs)) elif (name == 't'): tri = int(attrs['ia'])-1, int(attrs['ib'])-1, int(attrs['ic'])-1 triangles.append(tri) else: raise errors.ChildError('trimesh', name) def end(name): if (name == 'trimesh'): data = ode.TriMeshData() data.build(vertices, triangles) self._setObject(ode.GeomTriMesh, data=data) self._parser.pop() self._parser.push(startElement=start, endElement=end) Py3ODE-1.2.0.dev15/xode/joint.py000077500000000000000000000302351364423331700161100ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Joint Parser @author: U{Timothy Stranex} """ import ode from . import node, errors class Joint(node.TreeNode): """ Represents an ode.Joint-based object and corresponds to the tag. """ def __init__(self, name, parent): node.TreeNode.__init__(self, name, parent) self._world = self.getFirstAncestor(ode.World).getODEObject() try: self._jg = self.getFirstAncestor(ode.JointGroup).getODEObject() except node.AncestorNotFoundError: self._jg = None try: self._body = self.getFirstAncestor(ode.Body).getODEObject() except node.AncestorNotFoundError: self._body = None self._link1 = None self._link2 = None self.setODEObject(None) def _getName(self, name): root = self.getRoot() try: link = root.namedChild(name).getODEObject() except KeyError: raise errors.InvalidError('Joint link must reference an already '\ 'parsed body.') if (not isinstance(link, ode.Body)): raise errors.InvalidError('Joint link must reference a body.') return link def _getLinks(self): body = self._body or ode.environment if (self._link1 is not None): link1 = self._getName(self._link1) else: link1 = body body = ode.environment if (self._link2 is not None): link2 = self._getName(self._link2) else: link2 = body if (link1 is link2): raise errors.InvalidError('Joint requires two objects.') return link1, link2 def takeParser(self, parser): """ Handles further parsing. It should be called immediately after the tag is encountered. """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): if (name == 'link1'): self._link1 = attrs['body'] elif (name == 'link2'): self._link2 = attrs['body'] elif (name == 'ext'): pass elif (name == 'amotor'): l1, l2 = self._getLinks() self._parseAMotor(self._world, l1, l2) elif (name == 'ball'): l1, l2 = self._getLinks() self._parseBallJoint(self._world, l1, l2) elif (name == 'fixed'): l1, l2 = self._getLinks() self._parseFixedJoint(self._world, l1, l2) elif (name == 'hinge'): l1, l2 = self._getLinks() self._parseHingeJoint(self._world, l1, l2) elif (name == 'hinge2'): l1, l2 = self._getLinks() self._parseHinge2Joint(self._world, l1, l2) elif (name == 'slider'): l1, l2 = self._getLinks() self._parseSliderJoint(self._world, l1, l2) elif (name == 'universal'): l1, l2 = self._getLinks() self._parseUniversalJoint(self._world, l1, l2) else: raise errors.ChildError('joint', name) def _endElement(self, name): if (name == 'joint'): if (self.getODEObject() is None): raise errors.InvalidError('No joint type element found.') self._parser.pop() def _applyAxisParams(self, joint, anum, axis): def setParam(name): attr = 'Param%s' % name if (anum != 0): attr = '%s%i' % (attr, anum+1) joint.setParam(getattr(ode, attr), float(axis[name])) if ('LowStop' in axis): axis['LoStop'] = axis['LowStop'] del axis['LowStop'] for name in list(axis.keys()): if (name not in ['x', 'y', 'z']): if (name in ['LoStop', 'HiStop', 'Vel', 'FMax', 'FudgeFactor', 'Bounce', 'CFM', 'StopERP', 'StopCFM', 'SuspensionERP', 'SuspensionCFM']): setParam(name) else: raise errors.InvalidError('Invalid attribute %s' % repr(name) + ' of element.') def _parseBallJoint(self, world, link1, link2): anchor = [None] def start(name, attrs): if (name == 'anchor'): anchor[0] = self._parser.parseVector(attrs) else: raise errors.ChildError('ball', name) def end(name): if (name == 'ball'): joint = ode.BallJoint(world, self._jg) joint.attach(link1, link2) if (anchor[0] is not None): joint.setAnchor(anchor[0]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) def _parseFixedJoint(self, world, link1, link2): def start(name, attrs): raise errors.ChildError('fixed', name) def end(name): if (name == 'fixed'): self._parser.pop() joint = ode.FixedJoint(world, self._jg) joint.attach(link1, link2) self.setODEObject(joint) self._parser.push(startElement=start, endElement=end) def _parseHingeJoint(self, world, link1, link2): anchor = [None] axes = [] def start(name, attrs): if (name == 'anchor'): anchor[0] = self._parser.parseVector(attrs) elif (name == 'axis'): axes.append(attrs) else: raise errors.ChildError('hinge', name) def end(name): if (name == 'hinge'): joint = ode.HingeJoint(world, self._jg) joint.attach(link1, link2) if (anchor[0] is not None): joint.setAnchor(anchor[0]) if (len(axes) != 1): raise errors.InvalidError('Wrong number of axes for hinge' ' joint.') joint.setAxis(self._parser.parseVector(axes[0])) self._applyAxisParams(joint, 0, axes[0]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) def _parseSliderJoint(self, world, link1, link2): axes = [] def start(name, attrs): if (name == 'axis'): axes.append(attrs) else: raise errors.ChildError('slider', name) def end(name): if (name == 'slider'): joint = ode.SliderJoint(world, self._jg) joint.attach(link1, link2) if (len(axes) != 1): raise errors.InvalidError('Wrong number of axes for slider' ' joint.') joint.setAxis(self._parser.parseVector(axes[0])) self._applyAxisParams(joint, 0, axes[0]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) def _parseUniversalJoint(self, world, link1, link2): anchor = [None] axes = [] def start(name, attrs): if (name == 'anchor'): anchor[0] = self._parser.parseVector(attrs) elif (name == 'axis'): axes.append(attrs) else: raise errors.ChildError('universal', name) def end(name): if (name == 'universal'): joint = ode.UniversalJoint(world, self._jg) joint.attach(link1, link2) if (anchor[0] is not None): joint.setAnchor(anchor[0]) if (len(axes) != 2): raise errors.InvalidError('Wrong number of axes for ' ' universal joint.') joint.setAxis1(self._parser.parseVector(axes[0])) self._applyAxisParams(joint, 0, axes[0]) joint.setAxis2(self._parser.parseVector(axes[1])) self._applyAxisParams(joint, 1, axes[1]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) def _parseHinge2Joint(self, world, link1, link2): anchor = [None] axes = [] def start(name, attrs): if (name == 'anchor'): anchor[0] = self._parser.parseVector(attrs) elif (name == 'axis'): axes.append(attrs) else: raise errors.ChildError('hinge2', name) def end(name): if (name == 'hinge2'): joint = ode.Hinge2Joint(world, self._jg) joint.attach(link1, link2) if (anchor[0] is not None): joint.setAnchor(anchor[0]) if (len(axes) != 2): raise errors.InvalidError('Wrong number of axes for ' ' hinge2 joint.') joint.setAxis1(self._parser.parseVector(axes[0])) self._applyAxisParams(joint, 0, axes[0]) joint.setAxis2(self._parser.parseVector(axes[1])) self._applyAxisParams(joint, 1, axes[1]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) def _parseAMotor(self, world, link1, link2): anchor = [None] axes = [] def start(name, attrs): # The XODE specification allows anchor elements for AMotor but # there is no way to set the anchor of an AMotor. #if (name == 'anchor'): # anchor[0] = self._parser.parseVector(attrs) if (name == 'axis'): axes.append(attrs) else: raise errors.ChildError('amotor', name) def end(name): if (name == 'amotor'): joint = ode.AMotor(world, self._jg) joint.attach(link1, link2) if (anchor[0] is not None): joint.setAnchor(anchor[0]) if (len(axes) > 3): raise errors.InvalidError('Wrong number of axes for ' ' amotor joint.') joint.setNumAxes(len(axes)) for i in range(len(axes)): joint.setAxis(i, 0, self._parser.parseVector(axes[i])) self._applyAxisParams(joint, i, axes[i]) self.setODEObject(joint) self._parser.pop() self._parser.push(startElement=start, endElement=end) Py3ODE-1.2.0.dev15/xode/node.py000077500000000000000000000160131364423331700157100ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Parse Tree @author: U{Timothy Stranex} """ from . import transform class AncestorNotFoundError(Exception): """ Raised when an ancestor represeting an ODE object of some type was not found in the tree. @ivar type: The object type. @type type: class """ def __init__(self, type): self.type = type def __str__(self): return "" % repr(self.type.__name__) class TreeNode: """ A node in an XODE parse tree. """ def __init__(self, name, parent): """ Initialises this node. If the parent is not C{None}, parent.addChild() is called. @param name: The name of this container or C{None} if there is none. @type name: str @param parent: The parent of this node or C{None}. @type parent: instance or C{None} """ self._name = name self._parent = parent self._obj = None self._transform = transform.Transform() self._childs = [] self._namedChild = {} if (self._parent is not None): self._parent.addChild(self, name) def takeParser(self, parser): """ Called to make this node handle further parsing. It will release the parser when it has finished. @param parser: The parser. @type parser: instance of L{parser.Parser} """ def setODEObject(self, obj): """ Sets the ODE object represented by this node. @param obj: The ODE object. @type obj: instance """ self._obj = obj def getODEObject(self): """ @return: The ODE object represented by this node. C{None} is returned if this node does not represent an ODE object. @rtype: instance """ return self._obj def setNodeTransform(self, transform): """ @param transform: This node's transform. @type transform: instance of L{transform.Transform} """ self._transform = transform def getNodeTransform(self): """ @return: The transform of this node. @rtype: instance of L{transform.Transform} """ return self._transform def getTransform(self, untilAncestor=None): """ Calculates the absolute transform at this node. It calculates the transforms recursively from the root node. If C{untilAncestor} is passed, the transform is calculated relative to it. If C{untilAncestor} is passed but is not an ancestor of this node, the transform is calculated from the root node as if C{None} was passed. @param untilAncestor: The ancestor to calculate the transform from. @type untilAncestor: instance of L{TreeNode} @return: The absolute transform at this node. @rtype: instance of L{transform.Transform} """ p = self.getParent() t = self.getNodeTransform() if ((p is None) or (t.isAbsolute()) or (p is untilAncestor)): return t else: return p.getTransform(untilAncestor) * t def getName(self): """ @return: This node's name. If it is not named, C{None} is returned. @rtype: str or C{None} """ return self._name def getChildren(self): """ @return: The list of child nodes. @rtype: list """ return self._childs def namedChild(self, name): """ Retrieves a named child node. If no child by that name is a direct child of this node, all the child nodes are searched recursively until either the named child is found or every node has been searched. @param name: The name of the object. @type name: str @return: The node. @rtype: instance of L{TreeNode} @raise KeyError: If no node with the given name was found. """ if (name in self._namedChild): return self._namedChild[name] else: for child in self._childs: if (isinstance(child, TreeNode)): try: obj = child.namedChild(name) except KeyError: pass else: return obj raise KeyError("Could not find child named '%s'." % name) def addChild(self, child, name): """ Adds a child node. @param child: The child node. @type child: instance of L{TreeNode} @param name: The child's name. If the child is not named, pass C{None}. @type name: str or C{None} """ if (name is not None): self._namedChild[name] = child self._childs.append(child) def getParent(self): """ @return: The parent of this node. C{None} is returned if there is no parent node. @rtype: instance of L{TreeNode} or C{None} """ return self._parent def getFirstAncestor(self, type): """ Find the first ancestor of this node that represents an ODE object of the specified type. @param type: The ODE type. @type type: class @return: The ancestor node. @rtype: instance of L{TreeNode} @raise AncestorNotFoundError: If no ancestor matching the criteria was found. """ parent = self.getParent() if (parent is not None): if (isinstance(parent.getODEObject(), type)): return parent else: return parent.getFirstAncestor(type) else: raise AncestorNotFoundError(type) def getRoot(self): """ Finds the root node of this parse tree. @return: The root node. @rtype: instance of L{TreeNode} """ if (self.getParent() is None): return self else: return self.getParent().getRoot() Py3ODE-1.2.0.dev15/xode/parser.py000077500000000000000000000240741364423331700162650ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Importer for PyODE Introduction ============ This module is part of the implementation of an U{XODE} importer. It is part of the PyODE package. The parser uses the C{xml.parsers.expat} module. The parser creates a tree from an XODE document which the programmer can query or transverse. Many of the tree nodes correspond to ODE objects but some are present merely for organisation (such as the Group node). Currently, the following features of XODE are not supported: - Quaternion and axis-angle rotation modes - Groups - Joints other than BallJoint - Extension support Usage ===== Here's an example showing how to parse a document and transverse the resultant tree:: | from xode import parser | import ode | | f = file('xode-document.xml') | p = parser.Parser(f) | root = p.parseFile(f) | | # Retrieve named objects | body1 = root.childNamed('body1').getODEObject() | joint1 = root.childNamed('joint1').getODEObject() | | # Transverse the tree printing object names | def transverse(node): | print node.getName() | for c in node.getChildren(): | transverse(c) | transverse(root) @see: L{node.TreeNode} @author: U{Timothy Stranex} """ import ode import xml.parsers.expat from . import errors, transform, node, body, joint, geom class Parser: """ An XODE parser. Parameters ========== Certain aspects of the parsing can be controlled by setting parameters with L{setParams()}. C{spaceFactory} --------------- C{spaceFactory} can be set to a callable object that creates instances which inherit from L{ode.SpaceBase}. This factory will be used by the parser to create Space objects for tags unless the class is overridden in the XODE file. The default behavior is to use the L{ode.SimpleSpace} class. Example using L{ode.HashSpace}:: | from xode import parser | import ode | | p = parser.Parser() | p.setParams(spaceFactory=ode.HashSpace) Example using L{ode.QuadTreeSpace}:: | from xode import parser | import ode | | def makeSpace(): | return ode.QuadTreeSpace((0, 0, 0), (2, 2, 2), 3) | | p = parser.Parser() | p.setParams(spaceFactory=makeSpace) """ def __init__(self): """ Initialise the parser. """ self._params = {} self.setParams(spaceFactory=ode.SimpleSpace) def _nullHandler(self, *args, **kwargs): return def push(self, startElement=None, endElement=None): self._handlers.append({'startElement': self._expat.StartElementHandler, 'endElement': self._expat.EndElementHandler}) self._expat.StartElementHandler = startElement or self._nullHandler self._expat.EndElementHandler = endElement or self._nullHandler def pop(self): top = self._handlers.pop() self._expat.StartElementHandler = top['startElement'] self._expat.EndElementHandler = top['endElement'] def _create(self): """ Creates an expat parser. """ self._handlers = [] self._expat = xml.parsers.expat.ParserCreate() self._expat.StartElementHandler = self._nullHandler self._expat.EndElementHandler = self._nullHandler self.push(self._startElement) return self._expat def _startElement(self, name, attrs): if (name == 'xode'): self._root = Root(None, None) self._root.takeParser(self) else: raise errors.InvalidError('Root element must be .') def parseVector(self, attrs): """ Parses an element's attributes as a vector. @return: The vector (x, y, z). @rtype: tuple @raise errors.InvalidError: If the attributes don't correspond to a valid vector. """ try: vec = float(attrs['x']), float(attrs['y']), float(attrs['z']) except ValueError: raise errors.InvalidError('Vector attributes must be numbers.') except KeyError: raise errors.InvalidError('Vector must have x, y and z attributes.') else: return vec def parseString(self, xml): """ Parses the given string. @param xml: The string to parse. @type xml: str @return: The root container. @rtype: instance of L{node.TreeNode} @raise errors.InvalidError: If document is invalid. """ self._create().Parse(xml, 1) return self._root def parseFile(self, fp): """ Parses the given file. @param fp: A file-like object. @type fp: file-like instance @return: The root container. @rtype: instance of L{node.TreeNode} @raise errors.InvalidError: If document is invalid. """ self._create().ParseFile(fp) return self._root def setParams(self, **params): """ Sets some parse parameters. """ self._params.update(params) def getParam(self, name): """ @param name: The parameter name. @type name: str @return: The value of the given parameter. @raise KeyError: If the parameter is not defined. """ return self._params[name] class Root(node.TreeNode): """ The root of the object structure. It corresponds to the tag. """ def takeParser(self, parser): """ Handles further parsing. It should be called immediately after the tag is encountered. @param parser: The parser. @type parser: instance of L{Parser} """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'world'): world = World(nodeName, self) world.takeParser(self._parser) elif (name == 'ext'): pass else: raise errors.ChildError('xode', name) def _endElement(self, name): if (name == 'xode'): self._parser.pop() class World(node.TreeNode): """ Represents an ode.World object. It corresponds to the tag. """ def __init__(self, name, parent): node.TreeNode.__init__(self, name, parent) self.setODEObject(ode.World()) def takeParser(self, parser): """ Handles further parsing. It should be called immediately after the tag is encountered. @param parser: The parser. @type parser: instance of L{Parser} """ self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) elif (name == 'space'): space = Space(nodeName, self) space.takeParser(self._parser) elif (name == 'ext'): pass else: raise errors.ChildError('world', name) def _endElement(self, name): if (name == 'world'): self._parser.pop() class Space(node.TreeNode): """ Represents an ode.Space object and corresponds to the tag. """ def __init__(self, name, parent): node.TreeNode.__init__(self, name, parent) def takeParser(self, parser): """ Handles further parsing. It should be called immediately after the tag is encountered. @param parser: The parser. @type parser: instance of L{Parser} """ self.setODEObject(parser.getParam('spaceFactory')()) self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) elif (name == 'geom'): g = geom.Geom(nodeName, self) g.takeParser(self._parser) elif (name == 'group'): # parse group pass elif (name == 'body'): b = body.Body(nodeName, self, attrs) b.takeParser(self._parser) elif (name == 'jointgroup'): # parse joint group pass elif (name == 'joint'): j = joint.Joint(nodeName, self) j.takeParser(self._parser) elif (name == 'ext'): # parse ext pass else: raise errors.ChildError('space', name) def _endElement(self, name): if (name == 'space'): self._parser.pop() Py3ODE-1.2.0.dev15/xode/transform.py000077500000000000000000000160651364423331700170050ustar00rootroot00000000000000###################################################################### # Python Open Dynamics Engine Wrapper # Copyright (C) 2004 PyODE developers (see file AUTHORS) # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of EITHER: # (1) The GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at # your option) any later version. The text of the GNU Lesser # General Public License is included with this library in the # file LICENSE. # (2) The BSD-style license that is included with this library in # the file LICENSE-BSD. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files # LICENSE and LICENSE-BSD for more details. ###################################################################### # XODE Importer for PyODE """ XODE Transform @author: U{Timothy Stranex} """ import math class Transform: """ A matrix transform. """ def __init__(self): """ Initialise as an identity transform. """ self.m = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.setIdentity() self._absolute = False def takeParser(self, parser, node, attrs): """ Called to make this object handle further parsing. It should be called immediately after the tag has been encountered. @param parser: The parser. @type parser: instance of L{parser.Parser} @param node: The node that is to be transformed. @type node: instance of L{node.TreeNode} @param attrs: The tag attributes. @type attrs: dict """ self._scale = float(attrs.get('scale', 1.0)) self._absolute = (attrs.get('absolute', 'false') == 'true') self._position = None self._euler = None self._node = node self._parser = parser self._parser.push(startElement=self._startElement, endElement=self._endElement) def _startElement(self, name, attrs): if (name == 'matrix4f'): for r in range(4): for c in range(4): self.m[r][c] = float(attrs['m%i%i' % (r, c)]) elif (name == 'position'): self._position = (float(attrs['x']), float(attrs['y']), float(attrs['z'])) elif (name == 'euler'): coeff = 1 if (attrs.get('aformat', 'radians') == 'degrees'): coeff = math.pi/180 x = coeff * float(attrs['x']) y = coeff * float(attrs['y']) z = coeff * float(attrs['z']) self._euler = (x, y, z) elif (name == 'rotation'): pass else: from . import parser raise parser.InvalidError("%s is not a valid child of ."% repr(name)) def _endElement(self, name): if (name == 'transform'): if (self._euler): x, y, z = self._euler self.rotate(x, y, z) if (self._position): x, y, z = self._position self.translate(x, y, z) self.scale(self._scale, self._scale, self._scale) self._node.setNodeTransform(self) self._parser.pop() def isAbsolute(self): """ @return: True if this transform is to be absolute rather than relative to another. @rtype: bool """ return self._absolute def setIdentity(self): """ Set the matrix so that there is no translation, rotation or scaling. """ for r in range(4): for c in range(4): self.m[r][c] = 0 for i in range(4): self.m[i][i] = 1 def translate(self, x, y, z): """ Set the matrix to translate a point. @param x: The offset along the x axis. @type x: float @param y: The offset along the y axis. @type y: float @param z: The offset along the z axis. @type z: float """ t = Transform() t.m[3][0] = x t.m[3][1] = y t.m[3][2] = z r = self * t; self.m = r.m def scale(self, x, y, z): """ Set the matrix to scale a point. @param x: The scaling factor along the x axis. @type x: float @param y: The scaling factor along the y axis. @type y: float @param z: The scaling factor along the z axis. @type z: float """ t = Transform() t.m[0][0] = x t.m[1][1] = y t.m[2][2] = z r = self * t self.m = r.m def rotate(self, x, y, z): """ Set the matrix to rotate a point. @param x: Rotation around the x axis in radians. @type x: float @param y: Rotation around the y axis in radians. @type y: float @param z: Rotation around the z axis in radians. @type z: float """ rx = Transform() rx.m[1][1] = math.cos(x) rx.m[1][2] = math.sin(x) rx.m[2][1] = -math.sin(x) rx.m[2][2] = math.cos(x) ry = Transform() ry.m[0][0] = math.cos(y) ry.m[0][2] = -math.sin(y) ry.m[2][0] = math.sin(y) ry.m[2][2] = math.cos(y) rz = Transform() rz.m[0][0] = math.cos(z) rz.m[0][1] = math.sin(z) rz.m[1][0] = -math.sin(z) rz.m[1][1] = math.cos(z) r = self * rx * ry * rz self.m = r.m def getPosition(self): """ Extracts the position vector. It is returned as a tuple in the form (x, y, z). @return: The position vector. @rtype: tuple """ return self.m[3][0], self.m[3][1], self.m[3][2] def getRotation(self): """ Extracts the rotation matrix. It is returned as a tuple in the form (m00, m01, m02, m10, m11, m12, m20, m21, m22). @return: The rotation matrix. @rtype: tuple """ return self.m[0][0], self.m[0][1], self.m[0][2], \ self.m[1][0], self.m[1][1], self.m[1][2], \ self.m[2][0], self.m[2][1], self.m[2][2] def __mul__(self, t2): """ Concatenate this transform with another. @param t2: The second transform. @type t2: instance of L{Transform} """ ret = Transform() for row in range(4): for col in range(4): part = 0 for i in range(4): part = part + self.m[row][i] * t2.m[i][col] ret.m[row][col] = part return ret