https://wiki.freecad.org/api.php?action=feedcontributions&user=Htsubota&feedformat=atomFreeCAD Documentation - User contributions [en]2024-03-29T05:56:03ZUser contributionsMediaWiki 1.40.1https://wiki.freecad.org/index.php?title=Power_users_hub&diff=17149Power users hub2013-03-25T13:11:55Z<p>Htsubota: </p>
<hr />
<div>[[Image:Crystal_Clear_app_terminal.png|right|150]]<br />
<br />
This is the place to come if you want to have a deeper insight into FreeCAD. Here you can learn about customizing FreeCAD for your needs. <br />
<br />
These pages are in early stage of development. If you can't find the information you are looking for, or have found useful information somewhere we have not linked to, then please leave a comment on [[Talk:Power_users_hub|the talk page]], or, why not? [https://sourceforge.net/apps/mediawiki/free-cad/index.php?title=Help_FreeCAD Add some more content here yourself!]<br />
<br />
One of the nicest features of FreeCAD is that you can script and extend it extremely far without the need to compile anything or touch the source code. All the scripting part is done in [http://en.wikipedia.org/wiki/Python_(programming_language) Python], a very powerful but simple programming language. With simple Python scripts, you have total access to about any part of FreeCAD. For example, you can:<br />
* '''Create and modify geometry''': There is a kind of special object you need but that's not present in the default FreeCAD installation? You can easily create a new object type, either from scratch or by adapting an existing type.<br />
* '''Create custom tools and commands''': At the moment, FreeCAD already has extensive functionality, but there aren't many convenient tools and commands for the final user yet. But it is already easy to create your own sets of tools.<br />
* '''Modify the interface''': The FreeCAD user interface is still very basic at this stage. But everything is there for you to extend it to your needs. You can, for example, create toolbars to put your own tools, create special panels for interacting with your tools, etc.<br />
*'''Modify the scene representation''': FreeCAD has separate processes for building up and computing the geometry and displaying that geometry on your screen. You have full access to the way the scene contents are displayed on screen, therefore you can modify that representation, interact with it, or add all kinds of custom behaviours and screen widgets, like information, draggers, anchors or temporary entities.<br />
<br />
== Customizing FreeCAD ==<br />
<br />
* [[Interface Customization]]: Starting with the beginning: Toolbars and shortcuts<br />
* [[Macros|Working with Macros]]: Easily record often repeated tasks or Python code<br />
<br />
== Scripting in FreeCAD ==<br />
<br />
'''General'''<br />
* [[Introduction to python]] - See also other Python tutorials at the bottom of this page<br />
* [[Python scripting tutorial|FreeCAD scripting tutorial]] - A general look at python scripting in FreeCAD<br />
* [[FreeCAD Scripting Basics]]: Well, the basics...<br />
* [[Gui Command]] : Adding custom commands to the GUI<br />
* Using mixed [[Units]] in FreeCAD<br />
<br />
'''Working with Meshes'''<br />
* [[Mesh Scripting]]: How to interact with the [[Mesh Module]]<br />
<br />
'''Working with Parts'''<br />
* [[Part Module|The Part Module]]: How [http://en.wikipedia.org/wiki/Open_CASCADE Open CASCADE Technology] tools and structure is used in FreeCAD<br />
* [[Topological data scripting]]: How to interact with the Part Module<br />
* [[PythonOCC]]: How to unleash the whole Open CASCADE power<br />
* [[Mesh to Part]]: Converting between object types<br />
<br />
'''Accessing the Coin scenegraph'''<br />
* [[Scenegraph|The Coin/Inventor scenegraph]]: How the FreeCAD scene representation works<br />
* [[Pivy]]: How to access and modify the scenegraph<br />
<br />
'''Controlling the Qt interface'''<br />
* [[PyQt]]: How to access the interface, and modify its contents<br />
* [[Embedding FreeCADGui|Using the FreeCAD GUI]] in another Qt application with PyQt<br />
<br />
'''Working with parametric objects'''<br />
* [[Scripted objects]]: How to make 100% Python-scripted objects in FreeCAD<br />
* [[Drawing Module]]: Automating the 3D-to-2D process<br />
<br />
'''Examples'''<br />
* [[Code snippets]] : A collection of pieces of FreeCAD Python code, to serve as ingredients in your scripts...<br />
* [[Line drawing function]]: How to build a simple tool to draw lines<br />
* [[Dialog creation]]: How to construct dialogs with Qt designer, and use them in FreeCAD<br />
* [[Embedding FreeCAD]]: How to import FreeCAD as a Python module in other applications<br />
* The [[Draft Module]] adds basic 2d drawing functions to freecad. It is written entirely in Python, so it can be a good example if you want to write your own modules.<br />
* [[FreeCAD vector math library]] : A couple of handy functions to manipulate FreeCAD vectors. This library is also included in the Draft module.<br />
<br />
== API Functions ==<br />
<br />
The complete API description can be found [[:Category:API|here]]. Note that it can be incomplete, since we still didn't find a way to include it automatically on this wiki. For more accurate information, browse the modules directly from FreeCAD.<br />
<br />
== Advanced modification ==<br />
<br />
* [[Start up and Configuration]]: Startup and command line options<br />
* [[Install on Windows]]: Using the windows installer<br />
* [[CompileOnWindows|Compiling FreeCAD on Windows]] and [[CompileOnUnix|Compiling FreeCAD on Unix]]<br />
* [[Branding]]: Simple modifications you can do to the source code to change some aspects of FreeCAD<br />
* [[Extra python modules]] : Extend the FreeCAD python interpreter with these powerful modules!<br />
<br />
== Python tutorials ==<br />
<br />
These are good generic tutorials, not specific to FreeCAD, that might interest you if you are totally new to python.<br />
<br />
'''Python'''<br />
* [http://docs.python.org/tut/tut.html Official python tutorial] - A very complete tutorial for discovering python<br />
* [http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python Non-programmer tutorial for python] - an excellent wikibook<br />
* [http://npt.cc.rsu.ru/user/wanderer/ODP/Python_for_Newbies.htm Python for newbies] - one big tutorial covering all the basics<br />
<br />
'''PyQt''' - How to create and manage FreeCAD's Qt UI interface from python<br />
* [http://www.cs.usfca.edu/~afedosov/qttut/ Basic PyQt tutorial] : A simple and short linux-based tutorial that will explain how to work with PyQt and Qt Designer<br />
* [http://zetcode.com/tutorials/pyqt4/firstprograms/ First programs in PyQt4] : A platform-agnostic tutorial showing the interns of python + qt<br />
* [http://vizzzion.org/?id=pyqt programming Qt applications in python] : A more in-depth tutorial covering all the process of working with qt and python.<br />
<br />
'''Pivy''' - How to interact with FreeCAD's 3D scenes<br />
* [http://pivy.coin3d.org/documentation/pycon Basic Pivy tutorial] : A very simple tutorial form the official Pivy site<br />
* [http://www.google.com.br/url?sa=U&start=3&q=http://studierstube.icg.tu-graz.ac.at/doc/pdf/PivyStudierstubeTutorial.pdf&ei=XyC1Sc2wOeCKmQem_eHnBQ&usg=AFQjCNEYhb-0DcUc6OxFVijAe1epBb-4aA Introducing Pivy into studierstube] : A document that is not really a tutorial, but that illustrates well how Pivy works<br />
<br />
== Community projects == <br />
<br />
On the [[free-cad:Community Portal|Community portal]], you can find other FreeCAD-based projects run by the FreeCAD users community. If you are starting a new FreeCAD project, be sure to list it there! We also have a page with things you can do if you would like to [[Help FreeCAD]].<br />
<br />
{{languages | {{es|Power users hub/es}} {{fr|Power users hub/fr}} {{it|Power users hub/it}} {{jp|Power users hub/jp}} {{ru|Power users hub/ru}} {{se|Power users hub/se}} }}<br />
<br />
[[Category:Hubs]]<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Source_documentation&diff=16782Source documentation2013-02-06T11:07:16Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>FreeCAD source is commented to allow automatic html documentation generation with [http://www.doxygen.org Doxygen].<br />
<br />
For those wanting to follow closely the latest svn versions of FreeCAD, and who try to have a look at the c++ part, the first insight in the sources can give the feeling you're looking at an hedgehog: you can't discriminate head from tail and don't really know how to catch it!<br />
<br />
In complement to the Wiki, ''source documentation'' can hopefully alleviate this feeling, providing an entry point, and allowing for easy browsing through the dozens of files and directories.<br />
<br />
==== Build source documentation ====<br />
<br />
If you have Doxygen installed, it's very easy to build the doc. Go to your FreeCAD build directory, configure your sources with CMake, issue<br />
make DevDoc<br />
and consult the resulting html files starting from Doc/SourceDocu/html/index.html<br />
(note: the DevDoc target is not valid for autotools builds)<br />
<br />
By nature, source doc is, and will ever be, work in progress. Don't hesitate to rebuild as often as needed. If you fall upon blatant inadequacies, feel free to post on the forum (note: It is really fully checked with cMake build process only).<br />
<br />
As an alternative, the doc is generated from time to time and accessible on sourceforge [http://free-cad.sf.net/SrcDocu/index.html here]<br />
<br />
==== Integrate Coin3D documentation ====<br />
<br />
On unix systems, it is possible to link Coin3D source documentation with FreeCAD's.<br />
It allows easier navigation and complete inheritance diagrams for Coin derived classes.<br />
<br />
* On Debian and derived systems:<br />
: - Install the package libcoin60-doc<br />
: - Uncompress the file /usr/share/doc/libcoin60-doc/html/coin.tag.gz<br />
: - Regenerate source documentation<br />
: You are up for offline browsing.<br />
<br />
* If you don't want to or can't install Coin doc package, the links will be generated to access coin doc online at doc.coin3D.org, if doxygen tag file can be downloaded at configure time (wget).<br />
<br />
{{docnav|Extra python modules|List of Commands}}<br />
<br />
{{languages | {{es|Source documentation/es}} {{fr|Source documentation/fr}} {{it|Source documentation/it}} {{jp|Source documentation/jp}} {{ru|Source documentation/ru}} {{se|Source documentation/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Extra_python_modules&diff=16781Extra python modules2013-02-06T11:06:03Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>The python interpreter inside FreeCAD can easily be extended by adding new modules to your system's python installation. Those modules will be automatically detected and used by FreeCAD.<br />
<br />
All python modules can be used from within FreeCAD, but several of them, listed below, have a special importance because they allow python programs complete access to core functionality of FreeCAD. Examples of use of those modules can also be found on the [[Code snippets]] page.<br />
<br />
'''Notes''': <br />
<br />
* Of the following modules, Pivy is now fully integrated into any FreeCAD installation package, and PyQt4 is also integrated in the Windows installation package.<br />
* PyQt4 will be progressively obsoleted in FreeCAD after version 0.13, in favour of [http://qt-project.org/wiki/PySide PySide], which does exactly the same job but has a license (LGPL) more compatible with FreeCAD.<br />
<br />
==PyQt4==<br />
<br />
homepage: [http://www.riverbankcomputing.co.uk/pyqt http://www.riverbankcomputing.co.uk/pyqt]<br />
<br />
PyQt (version 4) is a python bindings library which allow programs to access, create or modify [http://en.wikipedia.org/wiki/Qt_(toolkit) Qt] interfaces. Since the FreeCAD interface is built with Qt, installing PyQt4 on your system allow python programs inside FreeCAD to access all the interface, modify its parts, create new widgets or gather info from interface parts.<br />
<br />
PyQt is released under a multiple licensing system, same system as [http://trolltech.com/products/qt used by Qt]. To resume, there is a commercial version and a free GPL version. If you want to use it to make commercial (closed source) programs, you need to purchase the commercial license, otherwise you can simply install and use freely the GPL version.<br />
<br />
===Installation===<br />
<br />
Before installing PyQt4, you obviously need a python environment installed and working.<br />
<br />
'''Linux'''<br />
<br />
The simplest way to install PyQt4 is through your distribution's package manager. On Debian/Ubuntu systems, the package name is generally ''python-qt4'', while on RPM-based systems it is named ''pyqt4''. The necessary dependencies (Qt and SIP) will be taken care of automatically.<br />
<br />
'''Windows'''<br />
<br />
The program can be downloaded from [http://www.riverbankcomputing.co.uk/pyqt/download.php here]. You'll need to install the Qt and SIP libraries before installing pyqt4 (to be documented).<br />
<br />
===Usage===<br />
<br />
Once it is installed, you can check that everything is working by typing in FreeCAD python console:<br />
<br />
import PyQt4<br />
<br />
To access the FreeCAD interface, type:<br />
<br />
from PyQt4 import QtCore,QtGui<br />
app = QtGui.qApp<br />
FreeCADWindow = app.activeWindow()<br />
<br />
Now you can start to explore the interface with the dir() command. You can add new elements, like a custom widget, with commands like:<br />
<br />
FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)<br />
<br />
===Documentation===<br />
<br />
More pyQt4 tutorials (including how to build interfaces with Qt Designer to use with python):<br />
<br />
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html - the official PyQt4 API Reference<br />
<br />
http://www.rkblog.rk.edu.pl/w/p/introduction-pyqt4/ - a simple introduction<br />
<br />
http://www.zetcode.com/tutorials/pyqt4/ - very complete in-depth tutorial<br />
<br />
==Pivy==<br />
<br />
homepage: [http://pivy.coin3d.org/ http://pivy.coin3d.org/]<br />
<br />
Pivy is a [http://www.coin3d.org coin] bindings library for python, officially supported by coin. Coin itself is a toolkit for building 3D applications in OpenGL. It is the toolkit that FreeCAD uses to draw its 3d Scene on the screen. Installing Pivy on your system will allow python programs to access the FreeCAD scenegraph, draw new objects on the scene and use the wide range of available Coin tools for drawing operations. Coin is based on the open Inventor scene description language. Pivy is used by the 2D drafting module of FreeCAD (and also by the complete module), so it is needed if you want to use any tool of those modules.<br />
<br />
It is important to know that FreeCAD only uses coin for representation of objects on the screen, which is separated from the definition of objects. This means that pivy won't be able to modify existing objects, neither to create valid FreeCAD objects. But it can be used to draw all kind of temporary things on screen, such as axis, grids, manipulators, construction geometry, etc...<br />
<br />
Pivy, as well as Coin, is released under a GPL license.<br />
<br />
===Installation===<br />
<br />
====Prerequisites====<br />
<br />
I believe before compiling Pivy you will want to have Coin and SoQt installed.<br />
<br />
I found for building on Mac it was sufficient to install the [http://www.coin3d.org/lib/plonesoftwarecenter_view Coin3 binary package]. Attempting to install coin from MacPorts was problematic: tried to add a lot of X Windows packages and ultimately crashed with a script error.<br />
<br />
For Fedora I found an RPM with Coin3.<br />
<br />
SoQt compiled from [http://www.coin3d.org/lib/soqt/releases/1.5.0 source] fine on Mac and Linux.<br />
<br />
====Debian & Ubuntu====<br />
<br />
Starting with Debian Squeeze and Ubuntu Lucid, pivy will be available directly from the official repositories, saving us a lot of hassle. In the meantime, you can either download one of the packages we made (for debian and ubuntu karmic) availables on the [[Download]] pages, or compile it yourself.<br />
<br />
The best way to compile pivy easily is to grab the debian source package for pivy and make a package with debuild. It is the same source code from the official pivy site, but the debian people made several bug-fixing additions. It also compiles fine on ubuntu karmic: http://packages.debian.org/squeeze/python-pivy (download the .orig.gz and the .diff.gz file, then unzip both, then apply the .diff to the source: go to the unzipped pivy source folder, and apply the .diff patch:<br />
patch -p1 < ../pivy_0.5.0~svn765-2.diff<br />
then<br />
debuild<br />
to have pivy properly built into an official installable package. Then, just install the package with gdebi.<br />
<br />
====Other linux distributions====<br />
<br />
First get the latest sources from the [http://pivy.coin3d.org/mercurial/ project's repository]:<br />
hg clone http://hg.sim.no/Pivy/default Pivy <br />
As of March 2012, the latest version is Pivy-0.5.<br />
<br />
Then you need a tool called SWIG to generate the C++ code for the Python bindings. Pivy-0.5 reports that it has only been tested with SWIG 1.3.31, 1.3.33, 1.3.35, and 1.3.40. So you can download a source tarball for one of these old versions from [http://www.swig.org http://www.swig.org]. Then unpack it and from a command line do (as root):<br />
./configure<br />
make<br />
make install (or checkinstall if you use it)<br />
It takes just a few seconds to build. <br />
<br />
Alternatively, you can try building with a more recent SWIG. As of March 2012, a typical repository version is 2.0.4. Pivy has a minor compile problem with SWIG 2.0.4 on Mac OS (see below) but seems to build fine on Fedora Core 15.<br />
<br />
After that go to the pivy sources and call <br />
python setup.py build <br />
which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.<br />
<br />
This is probably obsolete, but you may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix. <br />
<br />
After that, install by issuing (as root):<br />
python setup.py install (or checkinstall python setup.py install)<br />
That's it, pivy is installed.<br />
<br />
====Mac OS====<br />
These instructions may not be complete. Something close to this worked for OS 10.7 as of March 2012. I use MacPorts for repositories, but other options should also work.<br />
<br />
As for linux, get the latest source:<br />
hg clone http://hg.sim.no/Pivy/default Pivy <br />
If you don't have hg, you can get it from MacPorts:<br />
port install mercurial<br />
<br />
Then, as above you need SWIG. It should be a matter of:<br />
port install swig<br />
<br />
I found I needed also:<br />
port install swig-python<br />
<br />
As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest: https://sourceforge.net/mailarchive/message.php?msg_id=28114815<br />
<br />
This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:<br />
python setup.py build<br />
sudo python setup.py install<br />
<br />
====Windows====<br />
<br />
Assuming you are using Visual Studio 2005 or later you should open a command prompt with 'Visual Studio 2005 Command prompt' from the Tools menu.<br />
If the Python interpreter is not yet in the system path do<br />
set PATH=path_to_python_2.5;%PATH%<br />
<br />
To get pivy working you should get the latest sources from the project's repository:<br />
svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy <br />
Then you need a tool called SWIG to generate the C++ code for the Python bindings. It is recommended to use version 1.3.25 of SWIG, not the latest version, because at the moment pivy will only function correctly with 1.3.25. Download the binaries for 1.3.25 from [http://www.swig.org http://www.swig.org]. Then unpack it and from the command line add it to the system path<br />
set PATH=path_to_swig_1.3.25;%PATH%<br />
and set COINDIR to the appropriate path<br />
set COINDIR=path_to_coin<br />
<br />
On Windows the pivy config file expects SoWin instead of SoQt as default. I didn't find an obvious way to build with SoQt, so I modified the file setup.py directly.<br />
In line 200 just remove the part 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (do not remove the closing parenthesis).<br />
<br />
After that go to the pivy sources and call <br />
python setup.py build <br />
which creates the source files. You may run into a compiler error several header files couldn't be found. In this case adjust the INCLUDE variable<br />
set INCLUDE=%INCLUDE%;path_to_coin_include_dir<br />
and if the SoQt headers are not in the same place as the Coin headers also<br />
set INCLUDE=%INCLUDE%;path_to_soqt_include_dir<br />
and finally the Qt headers<br />
set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt<br />
<br />
If you are using the Express Edition of Visual Studio you may get a python keyerror exception.<br />
In this case you have to modify a few things in msvccompiler.py located in your python installation.<br />
<br />
Go to line 122 and replace the line<br />
vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version<br />
with<br />
vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version<br />
Then retry again.<br />
If you get a second error like <br />
error: Python was built with Visual Studio 2003;...<br />
you must also replace line 128<br />
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")<br />
with<br />
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")<br />
Retry once again. If you get again an error like<br />
error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed.<br />
then you should check the environment variables DISTUTILS_USE_SDK and MSSDK with<br />
echo %DISTUTILS_USE_SDK%<br />
echo %MSSDK%<br />
If not yet set then just set it e.g. to 1<br />
set DISTUTILS_USE_SDK=1<br />
set MSSDK=1<br />
<br />
Now, you may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix. <br />
After that copy the generated pivy directory to a place where the python interpreter in FreeCAD can find it.<br />
<br />
===Usage===<br />
<br />
To have Pivy access the FreeCAD scenegraph do the following: <br />
<br />
from pivy import coin<br />
App.newDocument() # Open a document and a view <br />
view = Gui.ActiveDocument.ActiveView <br />
FCSceneGraph = view.getSceneGraph() # returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraph<br />
FCSceneGraph.addChild(coin.SoCube()) # add a box to scene <br />
<br />
You can now explore the FCSceneGraph with the dir() command.<br />
<br />
===Documentation===<br />
<br />
Unfortunately documentation about pivy is still almost inexistant on the net. But you might find Coin documentation useful, since pivy simply translate Coin functions, nodes and methods in python, everything keeps the same name and properties, keeping in mind the difference of syntax between C and python:<br />
<br />
http://doc.coin3d.org/Coin/classes.html - Coin3D API Reference<br />
<br />
http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html - The Inventor Mentor - The "bible" of Inventor scene description language.<br />
<br />
You can also look at the Draft.py file in the FreeCAD Mod/Draft folder, since it makes big use of pivy.<br />
<br />
==pyCollada==<br />
<br />
[http://pycollada.github.com pyCollada] is a python library that allow programs to read and write [http://en.wikipedia.org/wiki/COLLADA Collada (*.DAE)] files. When pyCollada is installed on your system, FreeCAD ({{version|0.13}}) will detect it and add import and export options to handle opening and saving in the Collada file format.<br />
<br />
===Installation===<br />
<br />
Pycollada is usually not yet available in linux distributions repositories, but since it is made only of python files, it doesn't require compilation, and is easy to install. You have 2 ways, or directly from the official pycollada git repository, or with the easy_install tool.<br />
<br />
====Linux====<br />
<br />
In either case, you'll need the following packages already installed on your system:<br />
<br />
python-lxml <br />
python-numpy<br />
python-dateutil<br />
<br />
=====From the git repository=====<br />
<br />
git clone git://github.com/pycollada/pycollada.git pycollada<br />
cd pycollada<br />
sudo python setup.py install<br />
<br />
=====With easy_install=====<br />
<br />
Assuming you have a complete python installation already, the easy_install utility should be present already:<br />
<br />
easy_install pycollada<br />
<br />
You can check if pycollada was correctly installed by issuing in a python console:<br />
<br />
import collada<br />
<br />
If it returns nothing (no error message), then all is OK<br />
<br />
====Windows====<br />
<br />
To Be Documented<br />
<br />
==IfcOpenShell==<br />
<br />
IFCOpenShell is a library currently in development, that allows to import (and soon export) [http://en.wikipedia.org/wiki/Industry_Foundation_Classes Industry foundation Classes (*.IFC)] files. IFC is an extension to the STEP format, and is becoming the standard in [http://en.wikipedia.org/wiki/Building_information_modeling BIM] workflows. When ifcopenshell is correctly installed on your system, the FreeCAD [[Arch Module]] will detect it and use it to import IFC files. Since ifcopenshell is based on OpenCasCade, like FreeCAD, the quality of the import is very high, producing high-quality solid geometry.<br />
<br />
Homepage: http://www.ifcopenshell.org<br />
<br />
===Installation===<br />
<br />
Since ifcopenshell is pretty new, you'll likely need to compile it yourself.<br />
<br />
====Linux====<br />
<br />
You will need a couple of development packages installed on your system in order to compile ifcopenshell:<br />
<br />
liboce-*-dev<br />
python-dev<br />
swig<br />
<br />
but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.<br />
<br />
Grab the latest source code from here:<br />
<br />
svn co https://ifcopenshell.svn.sourceforge.net/svnroot/ifcopenshell ifcopenshell<br />
<br />
The build process is very easy:<br />
<br />
mkdir ifcopenshell-build<br />
cd ifcopenshell-build<br />
cmake ../ifcopenshell/cmake<br />
<br />
or, if you are using oce instead of opencascade:<br />
<br />
cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake <br />
<br />
Since ifcopenshell is made primarily for Blender, it uses python3 by default. To use it inside FreeCAD, you need to compile it against the same version of python that is used by FreeCAD. So you might need to force the python version with additional cmake parameters (adjust the python version to yours): <br />
<br />
cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake<br />
<br />
Then:<br />
<br />
make<br />
sudo make install<br />
<br />
You can check that ifcopenshell was correctly installed by issuing in a python console:<br />
<br />
import IfcImport<br />
<br />
If it returns nothing (no error message), then all is OK<br />
<br />
====Windows====<br />
<br />
''Copied from the IfcOpenShell README file''<br />
<br />
Users are advised to use the Visual Studio .sln file in the win/ folder. For Windows users a prebuilt Open CASCADE version is available from the http://opencascade.org website. Download and install this version and provide the paths to the Open CASCADE header and library files to MS Visual Studio C++.<br />
<br />
For building the IfcPython wrapper, SWIG needs to be installed. Please download the latest swigwin version from http://www.swig.org/download.html . After extracting the .zip file, please add the extracted folder to the PATH environment variable. Python needs to be installed, please provide the include and library paths to Visual Studio.<br />
<br />
{{docnav|Localisation|Source documentation}}<br />
<br />
{{languages | {{es|Extra python modules/es}} {{fr|Extra python modules/fr}} {{it|Extra python modules/it}} {{jp|Extra python modules/jp}} {{ru|Extra python modules/ru}} {{se|Extra python modules/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Branding&diff=16757Branding2013-02-02T06:46:49Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>This article describes the '''Branding''' of FreeCAD. Branding means to start your own application on base of FreeCAD. That can be only your own executable or splash screen till a complete reworked program. On base of the flexible architecture of FreeCAD it's easy to use it as base for your own special purpose program.<br />
<br />
=== General ===<br />
Most of the branding is done in the '''MainCmd.cpp'' or ''MainGui.cpp'''. These Projects generate the executable files of FreeCAD. To make your own Brand just copy the Main or MainGui projets and give the executable an own name, e.g. FooApp.exe. <br />
The most important settings for a new look can be made in one place in the main() function. Here is the code section that controls the branding:<br />
<br />
<code cpp><br />
int main( int argc, char ** argv )<br />
{<br />
// Name and Version of the Application<br />
App::Application::Config()["ExeName"] = "FooApp.exe";<br />
App::Application::Config()["ExeVersion"] = "0.7";<br />
<br />
// set the banner (for loging and console)<br />
App::Application::Config()["ConsoleBanner"] = sBanner;<br />
App::Application::Config()["AppIcon"] = "FCIcon";<br />
App::Application::Config()["SplashPicture"] = "FooAppSplasher";<br />
App::Application::Config()["StartWorkbench"] = "Part design";<br />
App::Application::Config()["HiddenDockWindow"] = "Property editor";<br />
App::Application::Config()["SplashAlignment" ] = "Bottom|Left";<br />
App::Application::Config()["SplashTextColor" ] = "#000000"; // black<br />
<br />
// Inits the Application <br />
App::Application::Config()["RunMode"] = "Gui";<br />
App::Application::init(argc,argv);<br />
<br />
Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);<br />
<br />
Gui::Application::initApplication();<br />
Gui::Application::runApplication();<br />
App::Application::destruct();<br />
<br />
return 0;<br />
}<br />
</code><br />
The first Config entry defines the program name. This is not the executable name, which can be changed by renaming or by compiler settings, but the name that is displayed in the task bar on windows or in the program list on Unix systems.<br />
<br />
The next lines define the Config entries of your FooApp Application. A description of the Config and its entries you find in [[Start up and Configuration]].<br />
<br />
=== Images ===<br />
All image resources are compiled into FreeCAD. This reduces delayed loading and keeps the installation compact. The images are included in XPM-Format which is basically a text format that uses C-syntax. You can basically draw this images with a text editor, but it is more comfortable to create the images with your favorite graphics program and convert it later to XPM format. <br />
<br />
The GNU image program [http://gimp.org/ Gimp] can save XPM file.<br />
<br />
For conversion you can use the ''[[ImageConv]]'' tool which is included with freecad. You can find it under<br />
<br />
/trunk/src/Tools/ImageTools/ImageConv<br />
<br />
It can not only convert images but also automatically update the ''BmpFactoryIcons.cpp'' file, where the images are registered. The typical usage is as simple like the following example:<br />
<br />
ImageConv -i InputImage.png -o OutputImage.xpm<br />
<br />
This converts the file ''InputImage.png'' in XPM-format and writes the result to file ''OutputImage.xpm''.<br />
<br />
The line:<br />
<br />
Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);<br />
<br />
in the main() then include the image in the BitmapFactory of FreeCAD.<br />
<br />
==== Icons ====<br />
The main application icon ''FCIcon'' that appears in window titles and other places is defined in<br />
<br />
/trunk/src/Gui/Icons/images.cpp<br />
<br />
and starts with the line<br />
<br />
<nowiki>static const char *FCIcon[]={</nowiki><br />
<br />
Replace it with your favourite icon, recompile freecad and the next step to create your own brand is done. There are many other icons in this file that you might change to your gusto.<br />
<br />
If you need to add new icons, you have to register it in <br />
/trunk/src/Gui/Icons/BmpFactoryIcons.cpp<br />
so that you can access from FreeCAD.<br />
<br />
==== Background Image ====<br />
The background image appears, when no document window is open. Like the splash screen it is defined in ''developers.h'' in the section starting with:<br />
static const char* const background[]={<br />
You should choose a low contrast image for the background. Otherwise it might irritate the user.<br />
<br />
{{docnav|Testing|Localisation}}<br />
<br />
{{languages | {{es|Branding/es}} {{fr|Branding/fr}} {{it|Branding/it}} {{jp|Branding/jp}} {{ru|Branding/ru}} {{se|Branding/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Testing&diff=16756Testing2013-02-02T06:45:49Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>== Introduction ==<br />
FreeCAD comes with an extensive testing framework. The testing bases on a set of Python scripts which are located in the test module.<br />
<br />
{{docnav|Debugging|Branding}}<br />
<br />
{{languages | {{es|Testing/es}} {{fr|Testing/fr}} {{it|Testing/it}} {{jp|Testing/jp}} {{ru|Testing/ru}} {{se|Testing/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Debugging&diff=16755Debugging2013-02-02T06:44:50Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>== Test first ==<br />
<br />
Before you go through the pain off debugging use the test framework to check if the standard tests work properly. If not there is maybe a broken installation.<br />
<br />
<br />
== command line ==<br />
<br />
The ''debugging'' of FreeCAD is supported by a few internal mechanisms. The command line version of FreeCAD provides to options for debugging support:<br />
;-v: With the "v" option FreeCAD gives a more verbose output.<br />
;-l: With the "l" option FreeCAD writes additional information to a logfile.<br />
<br />
{{Docnav|Module Creation|Testing}}<br />
<br />
{{languages | {{es|Debugging/es}} {{fr|Debugging/fr}} {{it|Debugging/it}} {{jp|Debugging/jp}} {{ru|Debugging/ru}} {{se|Debugging/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD_Build_Tool&diff=16753FreeCAD Build Tool2013-02-02T06:42:21Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>The '''FreeCAD build tool''' or '''fcbt''' is a python script located at<br />
trunc/src/Tools/fcbt.py<br />
It can be used to simplify some frequent tasks in building, distributing and extending FreeCAD.<br />
<br />
== Usage ==<br />
With [[wikipedia:Python (programming language)|Python]] correctly installed, ''fcbt'' can be invoked by the command<br />
python fbct.py<br />
It displays a menu, where you can select the task you want to use it for:<br />
FreeCAD Build Tool<br />
Usage:<br />
fcbt <command name> [command parameter]<br />
possible commands are:<br />
- DistSrc (DS) Build a source Distr. of the current source tree<br />
- DistBin (DB) Build a binary Distr. of the current source tree<br />
- DistSetup (DI) Build a Setup Distr. of the current source tree<br />
- DistSetup (DUI) Build a User Setup Distr. of the current source tree<br />
- DistAll (DA) Run all three above modules<br />
- NextBuildNumber (NBN) Increase the Build Number of this Version<br />
- CreateModule (CM) Insert a new FreeCAD Module in the module directory<br />
<br />
For help on the modules type:<br />
fcbt <command name> ?<br />
At the input promt enter the abbreviated command you want to call. For example type "CM" for [[Module Creation|creating a module]].<br />
<br />
=== DistSrc ===<br />
The command "DS" [[Create Source Distribution|creates a source distribution]] of the current source tree.<br />
<br />
=== DistBin ===<br />
The command "DB" [[Create Binary Distibution|creates a binary distribution]] of the current source tree.<br />
<br />
=== DistSetup ===<br />
The command "DI" [[Create Setup Distribution|creates a setup distribution]] of the current source tree.<br />
<br />
=== DistSetup ===<br />
The command "DUI" [[Create User Setup Distribution|creates a user setup distribution]] of the current source tree.<br />
<br />
=== DistAll ===<br />
The command "DA" executes "DS", "DB" and "DI" in sequence.<br />
<br />
=== NextBuildNumber ===<br />
The "NBN" command [[Increment Build Number|increments the build number]] to create a new release version of FreeCAD.<br />
<br />
=== CreateModule ===<br />
The "CM" command [[Module Creation|creates a new application module]].<br />
<br />
{{Docnav|Start up and Configuration|Module Creation}}<br />
<br />
{{languages | {{es|FreeCAD Build Tool/es}} {{fr|FreeCAD Build Tool/fr}} {{it|FreeCAD Build Tool/it}} {{jp|FreeCAD Build Tool/jp}} {{ru|FreeCAD Build Tool/ru}} {{se|FreeCAD Build Tool/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Start_up_and_Configuration&diff=16752Start up and Configuration2013-02-02T06:40:05Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>This page shows the different ways to start FreeCAD and the most important configuration features. <br />
<br />
== Starting FreeCAD from the Command line ==<br />
<br />
FreeCAD can be started normally, by double-clicking on its desktop icon or selecting it from the start menu, but it can also be started directly from the command line. This allows you to change soem of the default startup options.<br />
<br />
=== Command line options ===<br />
<br />
The command line options are subject of frequent changes, therefore it is a good idea to check the current options by typing:<br />
FreeCAD --help<br />
<br />
From the response you can read the possible parameters:<br />
<br />
Usage:<br />
FreeCAD [options] File1 File2 .....<br />
Allowed options: <br />
<br />
Generic options:<br />
-v [ --version ] print version string<br />
-h [ --help ] print help message<br />
-c [ --console ] start in console mode<br />
<br />
Configuration:<br />
-l [ --write-log ] arg write a log file<br />
-t [ --run-test ] arg test level<br />
-M [ --module-path ] arg additional module paths<br />
-P [ --python-path ] arg additional python paths<br />
--response-file arg can be specified with '@name', too<br />
<br />
=== Response and config files ===<br />
<br />
FreeCAD can read some of these options from a config file. This file must be in the bin path and must be named FreeCAD.cfg. Be aware that options specified in the command line override the config file!<br />
<br />
Some operating system have very low limit of the command line length. The common way to work around those limitations is using response files. A response file is just a configuration file which uses the same syntax as the command line. If the command line specifies a name of response file to use, it's loaded and parsed in addition to the command line:<br />
<br />
FreeCAD @ResponseFile.txt <br />
<br />
or:<br />
<br />
FreeCAD --response-file=ResponseFile.txt<br />
<br />
=== Hidden options ===<br />
<br />
There are a couple of options not visible to the user. These options are e.g. the X-Window parameters parsed by the Windows system:<br />
* -display display, sets the X display (default is $DISPLAY).<br />
* -geometry geometry, sets the client geometry of the first window that is shown.<br />
* -fn or -font font, defines the application font. The font should be specified using an X logical font description.<br />
* -bg or -background color, sets the default background color and an application palette (light and dark shades are calculated).<br />
* -fg or -foreground color, sets the default foreground color.<br />
* -btn or -button color, sets the default button color.<br />
* -name name, sets the application name.<br />
* -title title, sets the application title.<br />
* -visual TrueColor, forces the application to use a TrueColor visual on an 8-bit display.<br />
* -ncols count, limits the number of colors allocated in the color cube on an 8-bit display, if the application is using the QApplication::ManyColor color specification. If count is 216 then a 6x6x6 color cube is used (i.e. 6 levels of red, 6 of green, and 6 of blue); for other values, a cube approximately proportional to a 2x3x1 cube is used.<br />
* -cmap, causes the application to install a private color map on an 8-bit display.<br />
<br />
<br />
== Running FreeCAD without User Interface ==<br />
<br />
FreeCAD normally starts in GUI mode, but you can also force it to start in console mode by typing:<br />
<br />
FreeCAD -c<br />
<br />
from the command line. In console mode, no user interface will be displayed, and you will be presented with a python interpreter prompt. From that python prompt, you have the same functionality as the python interpreter that runs inside the FreeCAD GUI, and normal access to all modules and plugins of FreeCAD, excepted the FreeCADGui module. Be aware that modules that depend on FreeCADGui might also be unavailable.<br />
<br />
<br />
== Running FreeCAD as a python module ==<br />
<br />
FreeCAD can also be used to run as a python module inside other applications that use python or from an external python shell. For that, the host python application must know where your FreeCAD libs reside. The best way to obtain that is to temporarily append FreeCAD's lib path to the sys.path variable. The following code typed from any python shell will import FreeCAD and let you run it the same way as in console mode:<br />
<br />
<code python><br />
import sys<br />
sys.path.append("path/to/FreeCAD/lib") # change this by your own FreeCAD lib path<br />
import FreeCAD<br />
</code><br />
<br />
Once FreeCAD is loaded, it is up to you to make it interact with your host application in any way you can imagine!<br />
<br />
== The Config set ==<br />
<br />
On every Startup FreeCAD examines its surrounding and the command line parameters. It builds up a '''configuration set''' which holds the essence of the runtime information. This information is later used to determine the place where to save user data or log files. It is also very important for post postmortem analyzes. Therefore it is saved in the log file.<br />
<br />
=== User related information===<br />
<br />
{| border="2" cellpadding="4" cellspacing="0" style="margin-top:1em; margin-bottom:1em; background:#f9f9f9; border:1px #aaa solid; border-collapse:collapse;"<br />
|+ User config entries<br />
|-<br />
! Config var name !! Synopsis !! Example M$ !! Example Posix (Linux) <br />
|- <br />
| UserAppData || Path where FreeCAD stores User Related application data. || C:\Documents and Settings\username\Application Data\FreeCAD ||/home/username/.FreeCAD <br />
|- <br />
| UserParameter || File where FreeCAD stores User Related application data. || C:\Documents and Settings\username\Application Data\FreeCAD\user.cfg ||/home/username/.FreeCAD/user.cfg <br />
|- <br />
| SystemParameter || File where FreeCAD stores Application Related data. || C:\Documents and Settings\username\Application Data\FreeCAD\system.cfg ||/home/username/.FreeCAD/system.cfg <br />
|- <br />
| UserHomePath || Home path of the current user || C:\Documents and Settings\username\My Documents ||/home/username <br />
|}<br />
<br />
=== Command line arguments ===<br />
<br />
{| border="2" cellpadding="4" cellspacing="0" style="margin-top:1em; margin-bottom:1em; background:#f9f9f9; border:1px #aaa solid; border-collapse:collapse;"<br />
|+ User config entries<br />
|-<br />
! Config var name !! Synopsis !! Example <br />
|- <br />
| LoggingFile || 1 if the logging is switched on || 1 <br />
|- <br />
| LoggingFileName || File name where the log is placed || C:\Documents and Settings\username\Application Data\FreeCAD\FreeCAD.log <br />
|- <br />
| RunMode || This indicates how the main loop will work. '''"Script"''' means that the given script is called and then exit. '''"Cmd"''' runs the command line interpreter. '''"Internal"''' runs an internal script. '''"Gui"''' enters the Gui event loop. '''"Module"''' loads a given python module. || "Cmd"<br />
|- <br />
| FileName || Meaning depends on the RunMode || <br />
|- <br />
| ScriptFileName || Meaning depends on the RunMode || <br />
|- <br />
| Verbose || Verbosity level of FreeCAD || "" or "strict" <br />
|- <br />
| OpenFileCount ||Holds the number of files opened through command line arguments || "12" <br />
|- <br />
| AdditionalModulePaths||Holds the additional Module paths given in the cmd line || "extraModules/" <br />
|}<br />
<br />
=== System related ===<br />
<br />
{| border="2" cellpadding="4" cellspacing="0" style="margin-top:1em; margin-bottom:1em; background:#f9f9f9; border:1px #aaa solid; border-collapse:collapse;"<br />
|+ User config entries<br />
|-<br />
! Config var name !! Synopsis !! Example M$ !! Example Posix (Linux) <br />
|- <br />
| AppHomePath || Path where FreeCAD is installed || c:/Progam Files/FreeCAD_0.7|| /user/local/FreeCAD_0.7<br />
|- <br />
| PythonSearchPath || Holds a list of paths which python search modules. This is at startup can change during execution || || <br />
|}<br />
<br />
Some libraries need to call system environment variables. Sometimes when there is a problem with a FreeCAD installation, it is because some environment variable is absent or set wrongly. Therefore, some important variables get duplicated in the Config and saved in the log file.<br />
<br />
'''Python related environment variables:'''<br />
* PYTHONPATH<br />
* PYTHONHOME<br />
* TCL_LIBRARY<br />
* TCLLIBPATH<br />
<br />
'''OpenCascade related environment variables:'''<br />
* CSF_MDTVFontDirectory<br />
* CSF_MDTVTexturesDirectory<br />
* CSF_UnitsDefinition<br />
* CSF_UnitsLexicon<br />
* CSF_StandardDefaults<br />
* CSF_PluginDefaults<br />
* CSF_LANGUAGE<br />
* CSF_SHMessage<br />
* CSF_XCAFDefaults<br />
* CSF_GraphicShr<br />
* CSF_IGESDefaults<br />
* CSF_STEPDefaults<br />
<br />
'''System related environment variables:'''<br />
* PATH<br />
<br />
=== Build related information===<br />
<br />
The table below shows the availible informations about the Build version. Most of it comes from the Subversion repository. This stuff is needed to exactly rebuild a version!<br />
<br />
{| border="2" cellpadding="4" cellspacing="0" style="margin-top:1em; margin-bottom:1em; background:#f9f9f9; border:1px #aaa solid; border-collapse:collapse;"<br />
|+ User config entries<br />
|-<br />
! Config var name !! Synopsis !! Example <br />
|- <br />
| BuildVersionMajor || Major Version number of the Build. Defined in src/Build/Version.h.in || 0<br />
|- <br />
| BuildVersionMinor || Minor Version number of the Build. Defined in src/Build/Version.h.in || 7<br />
|- <br />
| BuildRevision || SVN Repository Revision number of the src in the Build. Generated by SVN || 356 <br />
|- <br />
| BuildRevisionRange || Range of differnt changes || 123-356 <br />
|- <br />
| BuildRepositoryURL || Repository URL || https://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk/src<br />
|- <br />
| BuildRevisionDate || Date of the above Revision || 2007/02/03 22:21:18 <br />
|- <br />
| BuildScrClean || Indicates if the source was changed ager checkout ||Src modified <br />
|- <br />
| BuildScrMixed || || Src not mixed<br />
|}<br />
<br />
=== Branding related ===<br />
<br />
These Config entries are related to the branding mechanism of FreeCAD. See [[Branding]] for more details.<br />
<br />
{| border="2" cellpadding="4" cellspacing="0" style="margin-top:1em; margin-bottom:1em; background:#f9f9f9; border:1px #aaa solid; border-collapse:collapse;"<br />
|+ User config entries<br />
|-<br />
! Config var name !! Synopsis !! Example <br />
|- <br />
| ExeName || Name of the build Executable file. Can diver from FreeCAD if a different main.cpp is used. || FreeCAD.exe <br />
|- <br />
| ExeVersion || Over all Version shows up at start time || V0.7 <br />
|- <br />
| AppIcon || Icon which is used for the Executable, shows in Application MainWindow. || "FCIcon" <br />
|- <br />
| ConsoleBanner || Banner which is prompted in console mode || <br />
|- <br />
| SplashPicture || Name of the Icon used for the Splash Screen || "FreeCADSplasher" <br />
|- <br />
| SplashAlignment || Alignment of the Text in the Splash dialog || "Bottom|Left" <br />
|- <br />
| SplashTextColor || Color of the splasher Text || "#000000" <br />
|- <br />
| StartWorkbench || Name of the Workbech which get started automaticly after Startup || "Part design" <br />
|- <br />
| HiddenDockWindow || List of dockwindows (separated by a semicolon) which will be disabled || "Property editor" <br />
|}<br />
<br />
{{docnav|Third Party Tools|FreeCAD Build Tool}}<br />
<br />
{{languages | {{es|Start up and Configuration/es}} {{fr|Start up and Configuration/fr}} {{it|Start up and Configuration/it}} {{jp|Start up and Configuration/jp}} {{ru|Start up and Configuration/ru}} {{se|Start up and Configuration/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Third_Party_Tools&diff=16749Third Party Tools2013-02-02T06:35:57Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>== Tool Page ==<br />
For every serious software development you need tools. Here is a list of tools we use to develop FreeCAD:<br />
<br />
=== Platform independend tools ===<br />
<br />
==== Qt-Toolkit ====<br />
The Qt-toolkit is a state of the art, plattform independend user interface design tool. It is contained in the [[LibPack]] of FreeCAD, but can also be downloaded at [http://www.trolltech.com www.trolltech.com].<br />
<br />
==== InkScape ====<br />
Great vector drawing programm. Adhers to the SVG standard and is used to draw Icons and Pictures. Get it at [http://www.inkscape.org www.inkscape.org].<br />
<br />
==== Doxygen ====<br />
A very good and stable tool to generate source documentation from the .h and .cpp files.<br />
<br />
==== The Gimp ====<br />
Not much to say about the Gnu Image Manipulation Program. Besides it can handle .xpm files which is a very convenient way to handle Icons in QT Programms. XPM is basicly C-Code which can be compiled into a programme.<br />
<br />
Get the GIMP here: [http://www.gimp.org/ www.gimp.org]<br />
<br />
=== Tools on Windows ===<br />
<br />
==== Visual Studio 8 Express ====<br />
Although VC8 is for C++ development not really a step forward since VisualStudio 6 (IMO a big step back), its a free development system on Windows. For native Win32 applications you need to download the PlatformSDK from M$. <br />
<br />
So the Express edition is hard to find. But you might try [http://msdn.microsoft.com/vstudio/express/visualc/default.aspx this link]<br />
<br />
==== CamStudio ====<br />
Is a Open Source tool to record Screencasts (Webcasts). Its a very good tool to create tutorials by recording them. Its far not so boring as writing documentation. <br />
<br />
See [http://camstudio.org/ camstudio.org] for details.<br />
<br />
<br />
==== Tortoise SVN ====<br />
This is a very great tool. It makes using Subversion (our version control system on sf.net) a real pleasure. You can throught out the explorer integration, easily manage Revisions, check on Diffs, resolve Confilcts, make branches, and so on.... The commit dialog itself is a piece of art. It gives you an overview over your changed files and allows you to put them in the commit or not. That makes it easy to bundle the changes to logical units and give them an clear commit message.<br />
<br />
You find ToroiseSVN on [http://tortoisesvn.tigris.org/ tortoisesvn.tigris.org].<br />
<br />
==== StarUML ====<br />
<br />
A full featured Open Source UML programm. It has a lot of features of the big ones, including reverse engeniering C++ source code....<br />
<br />
Download here: [http://staruml.sourceforge.net/en/ staruml.sourceforge.net]<br />
<br />
<br />
=== Tools on Linux ===<br />
<br />
TODO<br />
<br />
{{docnav|Third Party Libraries|Start up and Configuration}}<br />
<br />
{{languages | {{es|Third Party Tools/es}} {{fr|Third Party Tools/fr}} {{it|Third Party Tools/it}} {{jp|Third Party Tools/jp}} {{ru|Third Party Tools/ru}} {{se|Third Party Tools/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Third_Party_Libraries&diff=16748Third Party Libraries2013-02-02T06:34:46Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>=== Overview === <br />
These are libraries which are not changed in the FreeCAD project. They are basically used unchanged as a dynamic link library (*.so or *.dll). If there is a change necessary or a wrapper class is needed, then the code of the wrapper or the changed library code have to be moved to the FreeCAD base package.<br />
The used libraries are:<br />
<br />
Consider using [[#LibPack|LibPack]] instead of downloading and installing all the stuff on your own.<br />
<br />
=== Links === <br />
<br />
{| class="wikitable" style="text-align:left"<br />
|+ Link table<br />
|-<br />
! Lib name !! Version needed !! Link to get it <br />
|- <br />
| Python || >= 2.5.x || http://www.python.org/ <br />
|- <br />
| OpenCasCade || >= 5.2 || http://www.opencascade.org <br />
|- <br />
| Qt || >= 4.1.x || http://www.qtsoftware.com <br />
|- <br />
| Coin3D || >= 2.x || http://www.coin3d.org <br />
|- <br />
| ODE || >= 0.10.x || http://www.ode.org <br />
|- <br />
| SoQt || >= 1.2 || http://www.coin3d.org <br />
|- <br />
| Xerces-C++ || >= 2.7.x < 3.0 || http://xml.apache.org/xerces-c/ <br />
|- <br />
| GTS || >= 0.7.x || http://gts.sourceforge.net/ <br />
|- <br />
| Zlib || >= 1.x.x || http://www.zlib.net/ <br />
|- <br />
| Boost || >= 1.33.x || http://www.boost.org/ <br />
|- <br />
| Eigen3 || >= 3.0.1 || http://eigen.tuxfamily.org/index.php?title=Main_Page <br />
|}<br />
<br />
=== Details === <br />
<br />
==== Python ====<br />
'''Version:''' 2.5 or higher<br />
<br />
'''License:''' Python 2.5 license<br />
<br />
You can use the source or binary from http://www.python.org/ or use alternetivly ActiveState Python from http://www.activestate.com/ though it is a little bit hard to get the debug libs from ActiveState.<br />
<br />
===== Description ===== <br />
Python is the primary scripting language and is used throughout the application.<br />
For example:<br />
<br />
* Implement test scripts for testing on:<br />
** memory leaks<br />
** ensure presents of functionality after changes<br />
** post build checks<br />
** test coverage tests<br />
* Macros and macro recording<br />
* Implement application logic for standard packages<br />
* Implementation of whole workbenches<br />
* Dynamic loading of packages<br />
* Implementing rules for design (Knowledge engineering)<br />
* Doing some fancy Internet stuff like work groups and PDM<br />
* And so on ...<br />
<br />
Especially the dynamic package loading of Python is used to load at run time additional functionality and workbenches needed for the actual tasks. For a closer look to Python see: www.python.org Why Python you may ask. There are some reasons: So far I used different scripting languages in my professional life:<br />
* Perl<br />
* Tcl/Tk<br />
* VB<br />
* Java<br />
Python is more OO then Perl and Tcl, the code is not a mess like in Perl and VB. Java isn't a script language in the first place and hard (or impossible) to embed. Python is well documented and easy to embed and extend. It is also well tested and has a strong back hold in the open source community.<br />
<br />
===== Credits =====<br />
Goes to Guido van Rossum and a lot of people made Python such a success!<br />
<br />
==== OpenCasCade ==== <br />
<br />
'''Version:''' 5.2 or higher<br />
<br />
'''License:''' OCTPL<br />
<br />
OCC is a full-featured CAD Kernel. Originally, it's developed by Matra Datavision in France for the Strim (Styler) and Euclid Quantum applications and later on made Open Source. It's a really huge library and makes a free CAD application possible in the first place, by providing some packages which would be hard or impossible to implement in an Open Source project:<br />
* A complete STEP compliant geometry kernel<br />
* A topological data model and all needed functions to work on (cut, fuse, extrude, and so on. . . )<br />
* Standard Import- / Export processors like STEP, IGES, VRML<br />
* 3D and 2D viewer with selection support<br />
* A document and project data structure with support for save and restore, external linking of documents, recalculation of design history (parametric modeling) and a facility to load new data types as an extension package dynamically<br />
<br />
To learn more about OpenCasCade take a look at the OpenCasCade page or http://www.opencascade.org.<br />
<br />
==== Qt ==== <br />
<br />
'''Version:''' 4.1.x or higher<br />
<br />
'''License:''' GPL v2.0/v3.0 or Commercial (from version 4.5 on also LPGL v2.1)<br />
<br />
I don't think I need to tell a lot about Qt. It's one of the most often used GUI toolkits in Open Source projects. For me the most important point to use Qt is the Qt Designer and the possibility to load whole dialog boxes as a (XML) resource and incorporate specialized widgets. In a CAX application the user interaction and dialog boxes are by far the biggest part of the code and a good dialog designer is very important to easily extend FreeCAD with new functionality. Further information and a very good online documentation you'll find on http://www.qtsoftware.com.<br />
<br />
==== Coin3D ==== <br />
<br />
'''Version:''' 2.0 or higer<br />
<br />
'''License:''' GPL v2.0 or Commercial<br />
<br />
Coin is a high-level 3D graphics library with a C++ Application Programming Interface. Coin uses scenegraph data structures to render real-time graphics suitable for mostly all kinds of scientific and engineering visualization applications.<br />
<br />
Coin is portable over a wide range of platforms: any UNIX / Linux / *BSD platform, all Microsoft Windows operating system, and Mac OS X.<br />
<br />
Coin is built on the industry-standard OpenGL immediate mode rendering library, and adds abstractions for higher-level primitives, provides 3D interactivity, immensely increases programmer convenience and productivity, and contains many complex optimization features for fast rendering that are transparent for the application programmer.<br />
<br />
Coin is based on the SGI Open Inventor API. Open Inventor, for those who are not familiar with it, has long since become the de facto standard graphics library for 3D visualization and visual simulation software in the scientific and engineering community. It has proved it's worth over a period of more than 10 years, its maturity contributing to its success as a major building block in thousands of large-scale engineering applications around the world.<br />
<br />
We will use OpenInventor as 3D viewer in FreeCAD because the OpenCasCade viewer (AIS and Graphics3D) has serios limitations and performace bottlenecks, especially when it goes in large-scale engineering rendering. Other things like textures or volumetric rendering are not really supported, and so on ....<br />
<br />
Since Version 2.0 Coin uses a different licence model. It's not longer LGPL. They use GPL for open source and a commercial licence for closed source. That means if you want to sell your work based on FreeCAD (extension modules) you need to purchase a Coin licence!<br />
<br />
==== ODE (Open dynamic engine) ====<br />
<br />
'''Version:''' 0.10.0 or higher<br />
<br />
'''License:''' LGPL v2.1 or later or BSD<br />
<br />
ODE is an open source, high performance library for simulating rigid body dynamics. It is fully featured, stable, mature and platform independent with an easy to use C/C++ API. It has advanced joint types and integrated collision detection with friction. ODE is useful for simulating vehicles, objects in virtual reality environments and virtual creatures. It is currently used in many computer games, 3D authoring tools and simulation tools. <br />
<br />
===== Credits =====<br />
Russell Smith is the primary author of ODE.<br />
<br />
<br />
==== SoQt ==== <br />
<br />
'''Version:''' 1.2.0 or higher<br />
<br />
'''License:''' GPL v2.0 or Commercial<br />
<br />
SoQt is the Inventor binding to the Qt Gui Toolkit. Unfortunately, it's not longer LGPL so we have to remove it from the code base of FreeCAD and link it as a library. It has the same licence model like Coin. And you have to compile it with your version of Qt.<br />
<br />
==== Xerces-C++ ==== <br />
<br />
'''Version:''' 2.7.0 or higher<br />
<br />
'''License:''' Apache Software License Version 2.0<br />
<br />
Xerces-C++ is a validating XML parser written in a portable subset of C++. Xerces-C++ makes it easy to give your application the ability to read and write XML data. A shared library is provided for parsing, generating, manipulating, and validating XML documents.<br />
<br />
Xerces-C++ is faithful to the XML 1.0 recommendation and many associated standards (see Features below).<br />
<br />
The parser provides high performance, modularity, and scalability. Source code, samples and API documentation are provided with the parser. For portability, care has been taken to make minimal use of templates, no RTTI, and minimal use of #ifdefs.<br />
<br />
The parser is used for saving and restoring parameters in FreeCAD.<br />
<br />
==== GTS ==== <br />
<br />
'''Version:''' 0.7.x<br />
<br />
'''License:''' LGPL v2.0 or later<br />
<br />
GTS stands for the GNU Triangulated Surface Library. It is an Open Source Free Software Library intended to provide a set of useful functions to deal with 3D surfaces meshed with interconnected triangles. The source code is available free of charge under the Free Software LGPL license.<br />
<br />
Actually not needed to compile FreeCAD. You can switch on the usage with a proprocessor switch in FCConfig.h.<br />
<br />
==== Zlib ==== <br />
<br />
'''Version:''' 1.x.x<br />
<br />
'''License:''' zlib License<br />
<br />
zlib is designed to be a free, general-purpose, legally unencumbered -- that is, not covered by any patents -- lossless data-compression library for use on virtually any computer hardware and operating system. The zlib data format is itself portable across platforms. Unlike the LZW compression method used in Unix compress(1) and in the GIF image format, the compression method currently used in zlib essentially never expands the data. (LZW can double or triple the file size in extreme cases.) zlib's memory footprint is also independent of the input data and can be reduced, if necessary, at some cost in compression. <br />
<br />
<br />
<br />
==== Boost ==== <br />
<br />
'''Version:''' 1.33.x<br />
<br />
'''License:''' Boost Software License - Version 1.0<br />
<br />
The Boost C++ libraries are a collection of peer-reviewed, open source libraries that extend the functionality of C++. The libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects. Many of Boost's founders are on the C++ standard committee and several Boost libraries have been accepted for incorporation into the Technical Report 1 of C++0x.<br />
<br />
The libraries are aimed at a wide range of C++ users and application domains. They range from general-purpose libraries like SmartPtr, to OS Abstractions like FileSystem, to libraries primarily aimed at other library developers and advanced C++ users, like MPL.<br />
<br />
In order to ensure efficiency and flexibility, Boost makes extensive use of templates. Boost has been a source of extensive work and research into generic programming and meta-programming in C++.<br />
<br />
See: http://www.boost.org/ for details.<br />
<br />
=== LibPack ===<br />
<br />
LibPack is a convenient package with all the above libraries packed together. It is currently available for the <br />
Windows platform on the [[Download]] page! If you're working under Linux you don't need a LibPack, instead of you should make use of the package repositories of your Linux distribution. <br />
<br />
==== FreeCADLibs7.x Changelog ====<br />
* Using QT 4.5.x and Coin 3.1.x<br />
* Eigen template lib for Robot added<br />
* SMESH experimental <br />
<br />
<br />
{{docnav|CompileOnMac|Third Party Tools}}<br />
<br />
{{languages | {{es|Third Party Libraries/es}} {{fr|Third Party Libraries/fr}} {{it|Third Party Libraries/it}} {{jp|Third Party Libraries/jp}} {{ru|Third Party Libraries/ru}} {{se|Third Party Libraries/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Compile_on_MacOS&diff=16746Compile on MacOS2013-02-02T06:31:17Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>Since Mac OS X is BSD (UNIX) based, compiling FreeCAD on a Mac isn't much different from [[CompileOnUnix]], however there are a number of Mac-specific details critical to getting everything working properly. These instructions have been tested on Lion (10.7), but ''should work'' on Intel Macs running (Snow) Leopard as well.<br />
<br />
=== Download the FreeCAD sources ===<br />
<br />
Check out the latest revision of the FreeCAD source tree from the Sourceforge subversion repository:<br />
<br />
svn co http://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk free-cad<br />
<br />
=== Install Dependencies ===<br />
<br />
On Mac OS X 10.7, the following dependencies are NOT bundled with the operating and thus must be installed before building FreeCAD:<br />
<br />
*sip<br />
*fortran<br />
*xerces-c<br />
*boost<br />
*eigen<br />
*ftgl<br />
*coin3d<br />
*OpenCASCADE<br />
*Qt<br />
*pyqt<br />
*soqt<br />
<br />
<br />
==== Option 1: Homebrew ====<br />
<br />
'''Note''': this section is still a work in progress! See the help forum post for the latest.<br />
<br />
:https://sourceforge.net/apps/phpbb/free-cad/viewtopic.php?f=4&t=2064&p=15405<br />
<br />
Download and install the package manager Homebrew:<br />
<br />
:http://mxcl.github.com/homebrew/<br />
<br />
Then compile and install most of FreeCAD's dependencies:<br />
<br />
brew install sip gfortran xerces-c boost eigen coin qt pyqt soqt ftgl<br />
<br />
Go on to [[CompileOnMac#Build OpenCASCADE]].<br />
<br />
==== Option 2: MacPorts/Fink ====<br />
<br />
'''Note: this section is in need of updates.'''<br />
<br />
Install MacPorts )if you don't already have it). MacPorts is a system that allows you to download, compile, and install many common open-source applications with a single command. Similar applications from the UNIX/Linux world are PKGSRC and APT. To install, just download the disk image from the MacPorts site and follow the directions:<br />
<br />
:http://www.macports.org/install.php<br />
<br />
Whether or not you just installed MacPorts, you'll probably want to make sure it's up to date. Run:<br />
<br />
sudo port selfupdate<br />
<br />
Now that MacPorts is installed and up to date, you can start installing some of FreeCAD's required packages:<br />
<br />
*xercesc<br />
*boost<br />
*py-sip<br />
*ftlg<br />
*f2c<br />
*eigen3<br />
*py-pyqt4<br />
<br />
The following command will compile/install the above libraries. If MacPorts produces errors, you may want to try installing them one at a time.<br />
<br />
sudo port install xercesc boost ftgl f2c eigen3 py-sip py-pyqt4<br />
<br />
Note that for python packages like py-sip and py-pyqt4, there are multiple packages, one for each MacPorts version of Python.<br />
<br />
Note that boost is a large package, and py-pyqt4 depends on qt4-mac, which is a large package. You may want to run port -v install so that you have more of an idea what's going on during these long builds.<br />
<br />
Qt4 is also available for Mac as a binary installer from the Qt web site. I'm not sure how nicely this approach plays with FreeCAD compiling.<br />
<br />
<br />
'''Install Fortran Compiler'''<br />
<br />
You also need a FORTRAN compiler. Apple's fork of gcc on OSX does not come with FORTRAN.<br />
<br />
An installer for GFortran can be found here, and will do the trick:<br />
<br />
http://gcc.gnu.org/wiki/GFortranBinaries#MacOS<br />
<br />
If you are using fink, another method is to use the following commands (attempted by Shaneyfelt 2100.Nov.14)<br />
<br />
sudo fink selfupdate<br />
sudo fink install gcc46<br />
<br />
''This installs another gcc compiler collection with the name gcc-4 to avoid a name conflict with the apple one.''<br />
<br />
MacPorts gcc4x packages also include FORTRAN compilers, so this should also work:<br />
sudo port install gcc46<br />
<br />
Another possible MacPorts package is g95. This seems to be a valid FORTRAN90 compiler and will pass FreeCAD's cmake configuration tests, but the actual build seems to ask for gcc-specific options, so probably easier to stick to gcc4x.<br />
<br />
<br />
'''Install Eigen3'''<br />
<br />
Download and unzip the latest eigen3 library here:<br />
<br />
http://eigen.tuxfamily.org/index.php?title=Main_Page<br />
<br />
These are needed for solver functionality. Once unzipped, the folder named 'Eigen' can be dropped into<br />
<br />
'''/usr/local/include/eigen3/'''<br />
<br />
=== Build OpenCASCADE ===<br />
<br />
Currently, the easiest way to build OpenCASCADE on OS X is from the community edition (oce). Download the source or check out the Git repository from:<br />
<br />
:https://github.com/tpaviot/oce<br />
<br />
Then, in terminal:<br />
<br />
mkdir build<br />
cd build<br />
cmake ..<br />
cd ..<br />
make<br />
make install/strip<br />
<br />
You may need cmake:<br />
<br />
sudo port install cmake<br />
<br />
=== Download and 'install' the FreeCAD.app template ===<br />
<br />
The following archive contains an application bundle template for FreeCAD. This is not strictly necessary, but it makes working with FreeCAD more convenient than the default installation configuration. The recommended install location for the bundle is the /Applications folder, but you should be able to put it anywhere you want -- just remember that the bundle can't be moved after FreeCAD is complied and installed without further modifications. Running make install using the configuration in the next step will install into this bundle.<br />
<br />
:http://dl.getdropbox.com/u/103808/FreeCAD/FreeCAD_bundle_template_20091128.tar.gz<br />
<br />
=== Compile ===<br />
<br />
Configure, compile, and install FreeCAD using the following commands from within the root FreeCAD folder. If you put your FreeCAD.app bundle somewhere other than /Applications (or aren't using the bundle), change the 'PREFIX' argument accordingly.<br />
<br />
./autogen.sh<br />
<br />
PREFIX=/Applications/FreeCAD.app/Contents<br />
<br />
If you installed dependencies using Option 1 (Homebrew):<br />
<br />
''Note'': this config line has not been verified and may contain errors!<br />
<br />
./configure --with-xercesc-lib=/usr/local/lib --with-xercesc-include=/usr/local/include \<br />
--with-boost-lib=/usr/local/lib --with-boost-include=/usr/local/include \<br />
--with-qt4-dir=/usr/local--with-qt4-lib=/usr/local/lib --with-qt4-include=/usr/local/include \<br />
--with-qt4-framework=/usr/local/lib --with-qt4-bin=/usr/local/bin --with-occ-lib=/usr/local/lib \<br />
--with-occ-include=/usr/local/include/oce --with-coin=/usr/local/lib --with-soqt=/usr/local/lib \<br />
--prefix=/Applications/FreeCAD.app/Contents --bindir=/Applications/FreeCAD.app/Contents/MacOS \<br />
--libdir=/Applications/FreeCAD.app/Contents/Frameworks/FreeCAD \<br />
--includedir=/Applications/FreeCAD.app/Contents/Resources/include \<br />
--datarootdir=/Applications/FreeCAD.app/Contents/Resources/share --enable-debug=no \<br />
--with-python-include=/System/Library/Frameworks/Python.framework/Versions/2.5/Headers<br />
<br />
Or if you installed dependencies using Option 2 (MacPorts/Fink):<br />
<br />
./configure --with-xercesc-lib=/opt/local/lib --with-xercesc-include=/opt/local/include \<br />
--with-boost-lib=/opt/local/lib --with-boost-include=/opt/local/include \<br />
--with-qt4-dir=/usr/local/Trolltech/Qt-4.8.0 --with-qt4-lib=/usr/local/Trolltech/Qt-4.8.0/lib \<br />
--with-qt4-include=/usr/local/Trolltech/Qt-4.8.0/include --with-qt4-framework=/Library/Frameworks \<br />
--with-qt4-bin=/usr/local/Trolltech/Qt-4.8.0/bin --with-occ-lib=/usr/local/lib \<br />
--with-occ-include=/usr/local/include/oce --with-coin=/Library/Frameworks \<br />
--with-soqt=/Library/Frameworks --prefix=/Applications/FreeCAD.app/Contents \<br />
--bindir=/Applications/FreeCAD.app/Contents/MacOS --libdir=/Applications/FreeCAD.app/Contents/Frameworks/FreeCAD \<br />
--includedir=/Applications/FreeCAD.app/Contents/Resources/include \<br />
--datarootdir=/Applications/FreeCAD.app/Contents/Resources/share --enable-debug=no \<br />
--with-python-include=/System/Library/Frameworks/Python.framework/Versions/2.5/Headers<br />
<br />
Then:<br />
<br />
make <br />
make install<br />
<br />
Depending on your machine's processing power, the make step can take quite a while.<br />
<br />
=== Run ===<br />
If everything went OK, double-clicking the .app bundle should start FreeCAD. If you have any issues, post the details on the [http://sourceforge.net/apps/phpbb/free-cad/viewforum.php?f=4 help forum].<br />
<br />
=== PyQt4 ===<br />
<br />
Some users reported facing a "No Module named PyQt4" message on FreeCAD startup. This is a workaround to correct it:<br />
cd /Library/Python/2.6/site-packages<br />
sudo ln -s /contrib/lib/python2.6/site-packages/PyQt4 .<br />
sudo ln -s /contrib/lib/python2.6/site-packages/sip* .<br />
cd /volatile/FreeCAD-r5443-ser/bin/pivy<br />
cp _coin.dylib _coin.so<br />
cd /volatile/FreeCAD-r5443-ser/lib<br />
for i in *.dylib; do j=`basename $i .dylib`; cp $i $j.so; done<br />
<br />
=== Pivy ===<br />
Some FreeCAD components won't work without Pivy. See [[Extra_python_modules#Pivy|here]] for partial build instructions. <br />
<br />
<br />
{{docnav|CompileOnUnix|Third Party Libraries}}<br />
<br />
{{languages | {{es|CompileOnMac/es}} {{fr|CompileOnMac/fr}} {{jp|CompileOnMac/jp}} {{se|CompileOnMac/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Compile_on_Windows&diff=16744Compile on Windows2013-02-02T06:28:02Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>This article explains step by step '''how to compile FreeCAD on Windows'''.<br />
<br />
=== Prerequisites ===<br />
What you need is mainly the compiler. On Windows we use the M$<br />
VisualStudio 8 Compiler (or VC++ Express) with the highest service pack. Although it's<br />
probably possible to use Cygwin or MingW gcc it's not tested or ported so<br />
far. We have also ported to use VC8 Express Edition.<br />
You need to download the Windows Platform SDK to get e.g. the Windows.h.<br />
Also you need all the [[Third Party Libraries]] to successfully compile FreeCAD.<br />
<br />
If you use the M$ compilers you want most likely download the FreeCAD LibPack <br />
which provides you with all needed libs to build FreeCAD on Windows.<br />
<br />
Other prerequisites (and helpful programs) are:<br />
* cMake<br />
* TortoiseGit<br />
* Python 2.6<br />
* WiX (Windows installer XML v3.0) - if you want to make msi installer<br />
<br />
It is also necessary to have, in your system path, paths to:<br />
* Libpack<br />
* git (not tortoiseGit, but git.exe)<br />
* python<br />
<br />
=== Building with cMake ===<br />
<br />
First of all, you have to [http://www.cmake.org/cmake/resources/software.html download cMake]<br />
and install it on your build machine.<br />
<br />
==== The switch to cMake ====<br />
Since version 0.9 we use the cMake build system to generate the build/make files<br />
for various compilers. We do not longer deliver .vcproj files. <br />
If you want build former versions of FreeCAD (0.8 and older) see "Building older versions" <br />
later in this article.<br />
<br />
We switched because it became more and more painful to maintain project files for 30+<br />
build targets and x compilers. cMake gives us the posibility to support alternative <br />
IDEs, like Code::Blocks, Qt Creator and Eclipse CDT the main compiler<br />
we use is still M$ VC9 Express, though. But we plan for the future a build process on <br />
Windows without proprietary compiler software.<br />
==== Configure the build process ====<br />
<br />
The first step to build FreeCAD with cMake is to configure the environment. There<br />
are basically two ways to go:<br />
* Using the LibPack<br />
* Installing all needed libs and let cMake find them<br />
<br />
In the first case you only need to give cMake the path to the LibPack<br />
and all the rest should be done automatically and you see such a screen:<br />
[[File:CMake_Screen.png]]<br />
<br />
You see the LibPack path inserted into the '''FREECAD_LIBPACK_DIR''' variable. Starting<br />
from that all includes and paths are set. You just need to press the '''Generate''' button<br />
and the project files get generated.<br />
<br />
If you switch the '''FREECAD_LIBPACK_USE''' options off, the configuration tries to find<br />
each and every library needed on your system. Depending on the libs that works well more or<br />
less. So you have to do often define some paths by hand. cMake will show you what is<br />
not found and need to be specified.<br />
<br />
==== Options for the Build Process ====<br />
The cMake build system gives us a lot more flexibility over the build process. That means<br />
we can switch on and off some features or modules. It's in a way like the Linux kernel build.<br />
You have a lot switches to determine the build process.<br />
<br />
Here is the description of these switches. They will most likely change a lot in the future<br />
because we want to increase the build flexibility a lot more.<br />
<br />
{| class="wikitable" style="text-align:left"<br />
|+ Link table<br />
|-<br />
! Variable name !! Description !! Default<br />
|- <br />
| FREECAD_LIBPACK_USE || Switch the usage of the FreeCAD LibPack on or off || On Win32 on, otherwishe off <br />
|- <br />
| FREECAD_LIBPACK_DIR || Directory where the LibPack is || FreeCAD SOURCE dir<br />
|- <br />
| FREECAD_BUILD_GUI || Build FreeCAD with all Gui related modules || ON<br />
|- <br />
| FREECAD_BUILD_CAM || Build the CAM module, experimental! || OFF<br />
|- <br />
| FREECAD_BUILD_INSTALLER || Create the project files for the Windows installer. || OFF<br />
|- <br />
| FREECAD_BUILD_DOXYGEN_DOCU || Create the project files for source code documentation. || OFF<br />
|- <br />
| FREECAD_MAINTAINERS_BUILD || Switch on stuff needed only when you do a Release build. || OFF<br />
|}<br />
<br />
<br />
<br />
==== Procedure with cMake and Visual Studio 2008 ====<br />
Once you start cMake GUI, select source folder, add destination folder and click on "Configure". cMake will ask you to select generator - recommended for FreeCAD is "Visual Studio 9 2008". <br />
<br />
After you click "Next", cMake will throw error since it can not find LibPack. You will need to manually select folder where Libpack is in "FREECAD_LIBPACK_DIR" variable. After that you need to click on "Configure" once more.<br />
After configure is done, click on "Generate". Now you are done with cMake, and you can close it.<br />
<br />
Before using Visual Studio, we need to add libpack to system path (you need to do this only once, when building first time). You need to go to "Control Panel >> System >> Advanced System Settings". In the "System properties" dialog, under "Advanced" tab there is button "Environment Variables". Click on it.<br />
After you click on it, add libpack to the Path. Separate it from other path variables with ";".<br />
<br />
Now you need to start Visual Studio 2008. Visual C++ Express 2008 will also work. Before building, it is good procedure to copy bin folder from libpack\bin folder to bin folder of the build files (generated with cMake).<br />
<br />
After this go to "File >> Open >> Project/Solution". You need to open FreeCAD_Trunk.sln, from the build files generated with cMake. <br />
Once it is opened, there will be three popup menus in the toolbar. One of them says "Debug" - Switch it to "Release".<br />
Then execute "Build >> Build Solution" (or just press F7) - this process will last long time.<br />
<br />
Once it is done, choose "Debug >> Start without Debugging". Popup window will ask you to select exe file. Click on a popup menu under "Executable File Name" and choose "Browse". You need to go to \bin folder where source files are, and select "FreeCAD.exe"<br />
<br />
and you are done!<br />
<br />
==== command line build ====<br />
Here an example how to build FreeCAD from the Command line:<br />
<br />
rem @echo off<br />
rem Build script, uses vcbuild to completetly build FreeCAD<br />
<br />
rem update trunc<br />
d:<br />
cd "D:\_Projekte\FreeCAD\FreeCAD_0.9"<br />
"C:\Program Files (x86)\Subversion\bin\svn.exe" update <br />
<br />
rem set the aprobiated Variables here or outside in the system<br />
<br />
set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem<br />
set INCLUDE=<br />
set LIB=<br />
<br />
rem Register VS Build programms<br />
call "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"<br />
<br />
rem Set Standard include paths<br />
set INCLUDE=%INCLUDE%;%FrameworkSDKDir%\include<br />
set INCLUDE=%INCLUDE%;C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include<br />
<br />
rem Set lib Pathes<br />
set LIB=%LIB%;C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib<br />
set LIB=%LIB%;%PROGRAMFILES%\Microsoft Visual Studio\VC98\Lib<br />
<br />
rem Start the Visuall Studio build process<br />
"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcpackages\vcbuild.exe" "D:\_Projekte\FreeCAD FreeCAD_0.9_build\FreeCAD_trunk.sln" /useenv<br />
<br />
=== Building older versions ===<br />
<br />
==== Using LibPack ==== <br />
To make it easier to get [[FreeCAD]] compiled, we provide a collection of all<br />
needed libraries. It's called the [[LibPack]]. You can find it on the [http://sourceforge.net/project/showfiles.php?group_id=49159 download page] on<br />
sourceforge.<br />
<br />
You need to set the following environment variables:<br />
<br />
:'''FREECADLIB''' = "D:\Wherever\LIBPACK"<br />
<br />
:'''QTDIR''' = "%FREECADLIB%"<br />
<br />
Add "%FREECADLIB%\bin" and "%FREECADLIB%\dll" to the system ''PATH'' variable. Keep in mind that you have to replace "%FREECADLIB%" with the path name, since Windows does not recursively replace environment variables.<br />
<br />
===== Directory setup in Visual Studio =====<br />
Some search path of Visual Studio need to be set. <br />
To change them, use the menu ''Tools→Options→Directory<br />
<br />
====== Includes ======<br />
Add the following search path to the include path search list:<br />
* %FREECADLIB%\include<br />
* %FREECADLIB%\include\Python<br />
* %FREECADLIB%\include\boost<br />
* %FREECADLIB%\include\xercesc<br />
* %FREECADLIB%\include\OpenCascade<br />
* %FREECADLIB%\include\OpenCV<br />
* %FREECADLIB%\include\Coin<br />
* %FREECADLIB%\include\SoQt<br />
* %FREECADLIB%\include\QT<br />
* %FREECADLIB%\include\QT\Qt3Support<br />
* %FREECADLIB%\include\QT\QtCore<br />
* %FREECADLIB%\include\QT\QtGui<br />
* %FREECADLIB%\include\QT\QtNetwork<br />
* %FREECADLIB%\include\QT\QtOpenGL<br />
* %FREECADLIB%\include\QT\QtSvg<br />
* %FREECADLIB%\include\QT\QtUiTools<br />
* %FREECADLIB%\include\QT\QtXml<br />
* %FREECADLIB%\include\Gts<br />
* %FREECADLIB%\include\zlib<br />
<br />
====== Libs ======<br />
Add the following search path to the lib path search list:<br />
* %FREECADLIB%\lib<br />
<br />
====== Executables ======<br />
Add the following search path to the executable path search list:<br />
* %FREECADLIB%\bin<br />
* TortoiseSVN binary installation directory, usually "C:\Programm Files\TortoiseSVN\bin", this is needed for a distribution build when ''SubWVRev.exe'' is used to extract the version number from Subversion.<br />
<br />
===== Python needed =====<br />
During the compilation some Python scripts get executed. So the Python<br />
interpreter has to function on the OS. Use a command box to check it. If<br />
the Python library is not properly installed you will get an error message<br />
like ''Cannot find python.exe''. If you use the LibPack you can also use the<br />
python.exe in the bin directory.<br />
<br />
===== Special for VC8 =====<br />
When building the project with VC8, you have to change the link information for the WildMagic library, since you need a different version for VC6 and VC8. Both versions are supplied in ''LIBPACK/dll''. In the project properties for ''AppMesh'' change the library name for the ''wm.dll'' to the VC8 version. Take care to change it in Debug ''and'' Release configuration.<br />
<br />
==== Compile ==== <br />
<br />
After you conform to all prerequisites the compilation is - hopefully - only a mouse click in VC ;-)<br />
<br />
==== After Compiling ==== <br />
To get FreeCAD up and running from the compiler environment you need to copy a few files from the [[LibPack]] to the ''bin'' folder where FreeCAD.exe is installed after a successful build:<br />
<br />
* ''python.exe'' and ''python_d.exe'' from ''LIBPACK/bin''<br />
* ''python25.dll'' and ''python25_d.dll'' from ''LIBPACK/bin''<br />
* ''python25.zip'' from ''LIBPACK/bin''<br />
* make a copy of ''Python25.zip'' and rename it to ''Python25_d.zip''<br />
* ''QtCore4.dll'' from ''LIBPACK/bin''<br />
* ''QtGui4.dll'' from ''LIBPACK/bin''<br />
* ''boost_signals-vc80-mt-1_34_1.dll'' from ''LIBPACK/bin''<br />
* ''boost_program_options-vc80-mt-1_34_1.dll'' from ''LIBPACK/bin''<br />
* ''xerces-c_2_8.dll'' from ''LIBPACK/bin''<br />
* ''zlib1.dll'' from ''LIBPACK/bin''<br />
* ''coin2.dll'' from ''LIBPACK/bin''<br />
* ''soqt1.dll'' from ''LIBPACK/bin''<br />
* ''QtOpenGL4.dll'' from ''LIBPACK/bin''<br />
* ''QtNetwork4.dll'' from ''LIBPACK/bin''<br />
* ''QtSvg4.dll'' from ''LIBPACK/bin''<br />
* ''QtXml4.dll'' from ''LIBPACK/bin''<br />
<br />
When using a [[LibPack]] with a Python version older than 2.5 you have to copy two further files:<br />
* ''zlib.pyd'' and ''zlib_d.pyd'' from ''LIBPACK/bin/lib''. This is needed by python to open the zipped python library.<br />
* ''_sre.pyd'' and ''_sre_d.pyd'' from ''LIBPACK/bin/lib''. This is needed by python for the built in help system.<br />
<br />
If you don't get it running due to a Python error it is very likely that one of the ''zlib*.pyd'' files is missing.<br />
<br />
==== Additional stuff ==== <br />
<br />
If you whant to build the source code documentation you need [http://www.stack.nl/~dimitri/doxygen/ DoxyGen].<br />
<br />
To create an intstaller package you need [http://wix.sourceforge.net/ WIX].<br />
<br />
<br />
During the compilation some Python scripts get executed. So the Python interpreter has to work properly.<br />
<br />
For more details have also a look to ''README.Linux'' in your sources.<br />
<br />
First of all you should build the Qt plugin that provides all custom widgets of FreeCAD we need for the Qt Designer. The sources are located under <br />
//src/Tools/plugins/widget//.<br />
So far we don't provide a makefile -- but calling <br />
qmake plugin.pro<br />
creates it. Once that's done, calling ''make'' will create the library <br />
//libFreeCAD_widgets.so//.<br />
To make this library known to your ''Qt Designer'' you have to copy the file to<br />
//$QTDIR/plugin/designer//.<br />
<br />
{{docnav|Tracker|CompileOnUnix}}<br />
<br />
{{languages | {{es|CompileOnWindows/es}} {{fr|CompileOnWindows/fr}} {{jp|CompileOnWindows/jp}} {{se|CompileOnWindows/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Tracker&diff=16743Tracker2013-02-02T06:26:45Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>== Reporting bugs ==<br />
<br />
Recently the sourceforge platform made the [http://www.mantisbt.org/ mantis bug tracker] application available to projects, and FreeCAD is now using it actively, instead of the old built-in bug tracker. The adress of our bug tracker is:<br />
<br />
http://sourceforge.net/apps/mantisbt/free-cad/main_page.php<br />
<br />
If you think you might have found a bug, you are welcome to report it there. But before reporting a bug, please check the following items:<br />
<br />
* Make sure your bug is really a bug, that is, something that should be working and that is not working. If you are not sure, dont hesitate to explain your problem on the [http://sourceforge.net/apps/phpbb/free-cad/ forum] and ask what to do.<br />
* Before submitting anything, read the [[FAQ|frequently asked questions]], do a search on the [http://sourceforge.net/apps/phpbb/free-cad/ forum], and make sure the same bug hasn't been reported before, by doing a search on the bug tracker.<br />
* Describe as clearly as possible the problem, and how it can be reproduced. If we can not verify the bug, we might not be able to fix it.<br />
* Join the following information: Your operating system, if it is 32 or 64 bits, and the version of FreeCAD you are running.<br />
* Please file one separate report for each bug.<br />
* If you are on a linux system and your bug causes a crash in FreeCAD, you can try running a debug backtrace: From a terminal run ''gdb freecad'' (assuming package gdb is installed), then, inside gdb, type ''run'' . FreeCAD will then run. After the crash happens, type ''bt'' , to get the full backtrace. Include that backtrace in your bug report.<br />
<br />
== Requesting features ==<br />
<br />
If you want something to appear in FreeCAD that is not implemented yet, it is not a bug but a feature request. You can also submit it on the same tracker (file it as feature request instead of bug), but keep in mind there are no guarantees that your wish will be fullfilled.<br />
<br />
== Submitting patches ==<br />
<br />
In case you have programmed a bug fix, an extension or something else that can be of public use in FreeCAD, create a patch using the Subversion diff tool and submit it on the same tracker (file it as patch).<br />
<br />
== The "old" sourceforge tracker (obsolete) ==<br />
<br />
'''Note''': Please use the new mantis bug tracker to submit bugs, this one is now a bit deprecated...<br />
<br />
=== Where to find? ===<br />
The FreeCAD project has its own [https://sourceforge.net/tracker/?group_id=49159 tracker summary page]. There you find the overview on the individual sections of the tracker.<br />
<br />
=== When to use? ===<br />
[[Image:Bugtracker Screenshot annotated.png|right|thumb|The FreeCAD Bug Tracker]]<br />
<br />
=== Bugs ===<br />
If you think you might have found a bug, go to the [http://sourceforge.net/tracker/?atid=455298&group_id=49159&func=browse Bugs Section] of the tracker and choose "any" for ''status'' to see all bug request ever filed. The keyword search allows you to find bug tracker entries for a similiar issue. If you can not find an older entry about your problem, you should file a new entry on the same page.<br />
<br />
=== Feature Requests ===<br />
If you are missing a feature in FreeCAD that you think of as beeing absolutely necessary to become the ''worlds best'' CAD-Software, you might find the [http://sourceforge.net/tracker/?atid=455301&group_id=49159&func=browse Feature Request] section helpfull. <br />
<br />
=== Support Requests ===<br />
If you don't get around compiling FreeCAD and the [[CompileOnWindows|Compile On Windows]] or [[CompileOnUnix|Compile On Unix]] section does not give you a hint, or you try to port it to a new environment or are programming new modules or extensions for FreeCAD and need some assistance then the [http://sourceforge.net/tracker/?atid=455299&group_id=49159&func=browse Support Requests] section is the place you might want to go to.<br />
<br />
=== New Patches ===<br />
In case you have programmed a bug fix, an extension or something else that can be of public use in FreeCAD, create a patch using Subversion and file it in the [https://sourceforge.net/tracker/?group_id=49159&atid=455300 patches section].<br />
<br />
{{docnav|License|CompileOnWindows}}<br />
<br />
{{languages | {{es|Tracker/es}} {{fr|Tracker/fr}} {{it|Tracker/it}} {{jp|Tracker/jp}} {{ru|Tracker/ru}} {{se|Tracker/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Dialog_creation&diff=16741Dialog creation2013-02-02T06:23:41Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>In this page we will show how to build a simple Qt Dialog with [http://doc.trolltech.com/4.3/designer-manual.html Qt Designer], Qt's official tool for designing interfaces, then convert it to python code, then use it inside FreeCAD. I'll assume in the example that you know how to edit and run python scripts already, and that you can do simple things in a terminal window such as navigate, etc. You must also have, of course, pyqt installed.<br />
<br />
== Designing the dialog ==<br />
<br />
In CAD applications, designing a good UI (User Interface) is very important. About everything the user will do will be through some piece of interface: reading dialog boxes, pressing buttons, choosing between icons, etc. So it is very important to think carefully to what you want to do, how you want the user to behave, and how will be the workflow of your action.<br />
<br />
There are a couple of concepts to know when designing interface:<br />
* [http://en.wikipedia.org/wiki/Modal_window Modal/non-modal dialogs]: A modal dialog appears in front of your screen, stopping the action of the main window, forcing the user to respond to the dialog, while a non-modal dialog doesn't stop you from working on the main window. In some case the first is better, in other cases not.<br />
* Identifying what is required and what is optional: Make sure the user knows what he must do. Label everything with proper description, use tooltips, etc.<br />
* Separating commands from parameters: This is usually done with buttons and text input fields. The user knows that clicking a button will produce an action while changing a value inside a text field will change a parameter somewhere. Nowadays, though, users usually know well what is a button, what is an input field, etc. The interface toolkit we are using, Qt, is a state-of-the-art toolkit, and we won't have to worry much about making things clear, since they will already be very clear by themselves.<br />
<br />
So, now that we have well defined what we will do, it's time to open the qt designer. Let's design a very simple dialog, like this:<br />
<br />
[[Image:Qttestdialog.jpg]]<br />
<br />
We will then use this dialog in FreeCAD to produce a nice rectangular plane. You might find it not very useful to produce nice rectangular planes, but it will be easy to change it later to do more complex things. When you open it, Qt Designer looks like this:<br />
<br />
[[Image:Qtdesigner-screenshot.jpg]]<br />
<br />
It is very simple to use. On the left bar you have elements that can be dragged on your widget. On the right side you have properties panels displaying all kinds of editable properties of selected elements. So, begin with creating a new widget. Select "Dialog without buttons", since we don't want the default Ok/Cancel buttons. Then, drag on your widget '''3 labels''', one for the title, one for writing "Height" and one for writing "Width". Labels are simple texts that appear on your widget, just to inform the user. If you select a label, on the right side will appear several properties that you can change if you want, such as font style, height, etc.<br />
<br />
Then, add '''2 LineEdits''', which are text fields that the user can fill in, one for the height and one for the width. Here too, we can edit properties. For example, why not set a default value? For example 1.00 for each. This way, when the user will see the dialog, both values will be filled already and if he is satisfied he can directly press the button, saving precious time. Then, add a '''PushButton''', which is the button the user will need to press after he filled the 2 fields.<br />
<br />
Note that I choosed here very simple controls, but Qt has many more options, for example you could use Spinboxes instead of LineEdits, etc... Have a look at what is available, you will surely have other ideas.<br />
<br />
That's about all we need to do in Qt Designer. One last thing, though, let's rename all our elements with easier names, so it will be easier to identify them in our scripts:<br />
<br />
[[Image:Qtpropeditor.jpg]]<br />
<br />
== Converting our dialog to python ==<br />
<br />
Now, let's save our widget somewhere. It will be saved as an .ui file, that we will easily convert to python script with pyuic. On windows, the pyuic program is bundled with pyqt (to be verified), on linux you probably will need to install it separately from your package manager (on debian-based systems, it is part of the pyqt4-dev-tools package). To do the conversion, you'll need to open a terminal window (or a command prompt window on windows), navigate to where you saved your .ui file, and issue:<br />
<br />
pyuic mywidget.ui > mywidget.py<br />
<br />
On some systems the program is called pyuic4 instead of pyuic. This will simply convert the .ui file into a python script. If we open the mywidget.py file, its contents are very easy to understand:<br />
<br />
from PyQt4 import QtCore, QtGui<br />
<br />
class Ui_Dialog(object):<br />
def setupUi(self, Dialog):<br />
Dialog.setObjectName("Dialog")<br />
Dialog.resize(187, 178)<br />
self.title = QtGui.QLabel(Dialog)<br />
self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))<br />
self.title.setObjectName("title")<br />
self.label_width = QtGui.QLabel(Dialog)<br />
...<br />
<br />
self.retranslateUi(Dialog)<br />
QtCore.QMetaObject.connectSlotsByName(Dialog)<br />
<br />
def retranslateUi(self, Dialog):<br />
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))<br />
self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))<br />
...<br />
<br />
As you see it has a very simple structure: a class named Ui_Dialog is created, that stores the interface elements of our widget. That class has two methods, one for setting up the widget, and one for translating its contents, that is part of the general Qt mechanism for translating interface elements. The setup method simply creates, one by one, the widgets as we defined them in Qt Designer, and sets their options as we decided earlier. Then, the whole interface gets translated, and finally, the slots get connected (we'll talk about that later).<br />
<br />
We can now create a new widget, and use this class to create its interface. We can already see our widget in action, by putting our mywidget.py file in a place where FreeCAD will find it (in the FreeCAD bin directory, or in any of the Mod subdirectories), and, in the FreeCAD python interpreter, issue:<br />
<br />
from PyQt4 import QtGui<br />
import mywidget<br />
d = QtGui.QWidget()<br />
d.ui = mywidget.Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
And our dialog will appear! Note that our python interpreter is still working, we have a non-modal dialog. So, to close it, we can (apart from clicking its close icon, of course) issue:<br />
d.hide()<br />
<br />
== Making our dialog do something ==<br />
<br />
Now that we can show and hide our dialog, we just need to add one last part: To make it do something! If you play a bit with Qt designer, you'll quickly discover a whole section called "signals and slots". Basically, it works like this: elements on your widgets (in Qt terminology, those elements are themselves widgets) can send signals. Those signals differ according to the widget type. For example, a button can send a signal when it is pressed and when it is released. Those signals can be connected to slots, which can be special functionality of other widgets (for example a dialog has a "close" slot to which you can connect the signal from a close button), or can be custom functions. The [http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html PyQt Reference Documentation] lists all the qt widgets, what they can do, what signals they can send, etc...<br />
<br />
What we will do here, is to create a new function that will create a plane based on height and width, and to connect that function to the pressed signal emitted by our "Create!" button. So, let's begin with importing our FreeCAD modules, by putting the following line at the top of the script, where we already import QtCore and QtGui:<br />
<br />
import FreeCAD, Part<br />
<br />
Then, let's add a new function to our Ui_Dialog class:<br />
<br />
def createPlane(self):<br />
try:<br />
# first we check if valid numbers have been entered<br />
w = float(self.width.text())<br />
h = float(self.height.text())<br />
except ValueError:<br />
print "Error! Width and Height values must be valid numbers!"<br />
else:<br />
# create a face from 4 points<br />
p1 = FreeCAD.Vector(0,0,0)<br />
p2 = FreeCAD.Vector(w,0,0)<br />
p3 = FreeCAD.Vector(w,h,0)<br />
p4 = FreeCAD.Vector(0,h,0)<br />
pointslist = [p1,p2,p3,p4,p1]<br />
mywire = Part.makePolygon(pointslist)<br />
myface = Part.Face(mywire)<br />
Part.show(myface)<br />
self.hide()<br />
<br />
Then, we need to inform Qt to connect the button to the function, by placing the following line just before QtCore.QMetaObject.connectSlotsByName(Dialog):<br />
<br />
QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)<br />
<br />
This, as you see, connects the pressed() signal of our create object (the "Create!" button), to a slot named createPlane, which we just defined. That's it! Now, as a final touch, we can add a little function to create the dialog, it will be easier to call. Outside the Ui_Dialog class, let's add this code:<br />
<br />
class plane():<br />
d = QtGui.QWidget()<br />
d.ui = Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
<br />
Then, from FreeCAD, we only need to do:<br />
<br />
import mywidget<br />
mywidget.plane()<br />
<br />
That's all Folks... Now you can try all kinds of things, like for example inserting your widget in the FreeCAD interface (see the [[Code snippets]] page), or making much more advanced custom tools, by using other elements on your widget.<br />
<br />
== The complete script ==<br />
<br />
This is the complete script, for reference:<br />
<br />
# -*- coding: utf-8 -*-<br />
<br />
# Form implementation generated from reading ui file 'mywidget.ui'<br />
#<br />
# Created: Mon Jun 1 19:09:10 2009<br />
# by: PyQt4 UI code generator 4.4.4<br />
#<br />
# WARNING! All changes made in this file will be lost!<br />
<br />
from PyQt4 import QtCore, QtGui<br />
import FreeCAD, Part <br />
<br />
class Ui_Dialog(object):<br />
def setupUi(self, Dialog):<br />
Dialog.setObjectName("Dialog")<br />
Dialog.resize(187, 178)<br />
self.title = QtGui.QLabel(Dialog)<br />
self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))<br />
self.title.setObjectName("title")<br />
self.label_width = QtGui.QLabel(Dialog)<br />
self.label_width.setGeometry(QtCore.QRect(10, 50, 57, 16))<br />
self.label_width.setObjectName("label_width")<br />
self.label_height = QtGui.QLabel(Dialog)<br />
self.label_height.setGeometry(QtCore.QRect(10, 90, 57, 16))<br />
self.label_height.setObjectName("label_height")<br />
self.width = QtGui.QLineEdit(Dialog)<br />
self.width.setGeometry(QtCore.QRect(60, 40, 111, 26))<br />
self.width.setObjectName("width")<br />
self.height = QtGui.QLineEdit(Dialog)<br />
self.height.setGeometry(QtCore.QRect(60, 80, 111, 26))<br />
self.height.setObjectName("height")<br />
self.create = QtGui.QPushButton(Dialog)<br />
self.create.setGeometry(QtCore.QRect(50, 140, 83, 26))<br />
self.create.setObjectName("create")<br />
<br />
self.retranslateUi(Dialog)<br />
QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)<br />
QtCore.QMetaObject.connectSlotsByName(Dialog)<br />
<br />
def retranslateUi(self, Dialog):<br />
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))<br />
self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label_width.setText(QtGui.QApplication.translate("Dialog", "Width", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label_height.setText(QtGui.QApplication.translate("Dialog", "Height", None, QtGui.QApplication.UnicodeUTF8))<br />
self.create.setText(QtGui.QApplication.translate("Dialog", "Create!", None, QtGui.QApplication.UnicodeUTF8))<br />
<br />
def createPlane(self):<br />
try:<br />
# first we check if valid numbers have been entered<br />
w = float(self.width.text())<br />
h = float(self.height.text())<br />
except ValueError:<br />
print "Error! Width and Height values must be valid numbers!"<br />
else:<br />
# create a face from 4 points<br />
p1 = FreeCAD.Vector(0,0,0)<br />
p2 = FreeCAD.Vector(w,0,0)<br />
p3 = FreeCAD.Vector(w,h,0)<br />
p4 = FreeCAD.Vector(0,h,0)<br />
pointslist = [p1,p2,p3,p4,p1]<br />
mywire = Part.makePolygon(pointslist)<br />
myface = Part.Face(mywire)<br />
Part.show(myface)<br />
<br />
class plane():<br />
d = QtGui.QWidget()<br />
d.ui = Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
<br />
<br />
{{docnav|Line drawing function|License}}<br />
<br />
{{languages | {{cn|Dialog creation/cn}} {{de|Dialog creation/de}} {{es|Dialog creation/es}} {{fr|Dialog creation/fr}} {{it|Dialog creation/it}} {{jp|Dialog creation/jp}} {{ru|Dialog creation/ru}} {{se|Dialog creation/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Line_drawing_function&diff=16740Line drawing function2013-02-02T06:22:29Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>This page shows how advanced functionality can easily be built in Python. In this exercise, we will be building a new tool that draws a line. This tool can then be linked to a FreeCAD command, and that command can be called by any element of the interface, like a menu item or a toolbar button.<br />
<br />
==The main script==<br />
<br />
First we will write a script containing all our functionality. Then, we will save this in a file, and import it in FreeCAD, so all classes and functions we write will be availible to FreeCAD. So, launch your favorite text editor, and type the following lines:<br />
<br />
import FreeCADGui, Part<br />
from pivy.coin import *<br />
<br />
class line:<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
def __init__(self):<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
self.stack = []<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint) <br />
<br />
def getpoint(self,event_cb):<br />
event = event_cb.getEvent()<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
pos = event.getPosition()<br />
point = self.view.getPoint(pos[0],pos[1])<br />
self.stack.append(point)<br />
if len(self.stack) == 2:<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
shape = l.toShape()<br />
Part.show(shape)<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
<br />
==Detailed explanation==<br />
<br />
import Part, FreeCADGui<br />
from pivy.coin import *<br />
<br />
In Python, when you want to use functions from another module, you need to import it. In our case, we will need functions from the [[Part Module]], for creating the line, and from the Gui module (FreeCADGui), for accessing the 3D view. We also need the complete contents of the coin library, so we can use directly all coin objects like SoMouseButtonEvent, etc...<br />
<br />
class line:<br />
<br />
Here we define our main class. Why do we use a class and not a function? The reason is that we need our tool to stay "alive" while we are waiting for the user to click on the screen. A function ends when its task has been done, but an object (a class defines an object) stays alive until it is destroyed.<br />
<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
<br />
In Python, every class or function can have a description string. This is particularly useful in FreeCAD, because when you'll call that class in the interpreter, the description string will be displayed as a tooltip.<br />
<br />
def __init__(self):<br />
<br />
Python classes can always contain an __init__ function, which is executed when the class is called to create an object. So, we will put here everything we want to happen when our line tool begins.<br />
<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
<br />
In a class, you usually want to append ''self.'' before a variable name, so it will be easily accessible to all functions inside and outside that class. Here, we will use self.view to access and manipulate the active 3D view.<br />
<br />
self.stack = []<br />
<br />
Here we create an empty list that will contain the 3D points sent by the getpoint function.<br />
<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)<br />
<br />
This is the important part: Since it is actually a [http://www.coin3d.org/ coin3D] scene, the FreeCAD uses coin callback mechanism, that allows a function to be called everytime a certain scene event happens. In our case, we are creating a callback for [http://doc.coin3d.org/Coin/group__events.html SoMouseButtonEvent] events, and we bind it to the getpoint function. Now, everytime a mouse button is pressed or released, the getpoint function will be executed.<br />
<br />
Note that there is also an alternative to addEventCallbackPivy() called addEventCallback() which dispenses the use of pivy. But since pivy is a very efficient and natural way to access any part of the coin scene, it is much better to use it as much as you can!<br />
<br />
def getpoint(self,event_cb):<br />
<br />
Now we define the getpoint function, that will be executed when a mouse button is pressed in a 3D view. This function will receive an argument, that we will call event_cb. From this event callback we can access the event object, which contains several pieces of information (mode info [[Code_snippets#Observing_mouse_events_in_the_3D_viewer_via_Python|here]]).<br />
<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
<br />
The getpoint function will be called when a mouse button is pressed or released. But we want to pick a 3D point only when pressed (otherwise we would get two 3D points very close to each other). So we must check for that here.<br />
<br />
pos = event.getPosition()<br />
<br />
Here we get the screen coordinates of the mouse cursor<br />
<br />
point = self.view.getPoint(pos[0],pos[1])<br />
<br />
This function gives us a FreeCAD vector (x,y,z) containing the 3D point that lies on the focal plane, just under our mouse cursor. If you are in camera view, imagine a ray coming from the camera, passing through the mouse cursor, and hitting the focal plane. There is our 3D point. If we are in orthogonal view, the ray is parallel to the view direction.<br />
<br />
self.stack.append(point)<br />
<br />
We add our new point to the stack<br />
<br />
if len(self.stack) == 2:<br />
<br />
Do we have enough points already? if yes, then let's draw the line!<br />
<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
<br />
Here we use the function Line() from the [[Part Module]] that creates a line from two FreeCAD vectors. Everything we create and modify inside the Part module, stays in the Part module. So, until now, we created a Line Part. It is not bound to any object of our active document, so nothing appears on the screen.<br />
<br />
shape = l.toShape()<br />
<br />
The FreeCAD document can only accept shapes from the Part module. Shapes are the most generic type of the Part module. So, we must convert our line to a shape before adding it to the document.<br />
<br />
Part.show(shape)<br />
<br />
The Part module has a very handy show() function that creates a new object in the document and binds a shape to it. We could also have created a new object in the document first, then bound the shape to it manually.<br />
<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
<br />
Since we are done with our line, let's remove the callback mechanism, that consumes precious CPU cycles.<br />
<br />
==Testing & Using the script==<br />
<br />
Now, let's save our script to some place where the FreeCAD python interpreter will find it. When importing modules, the interpreter will look in the following places: the python installation paths, the FreeCAD bin directory, and all FreeCAD modules directories. So, the best solution is to create a new directory in one of the FreeCAD [[Installing_more_workbenches|Mod directories]], and to save our script in it. For example, let's make a "MyScripts" directory, and save our script as "exercise.py".<br />
<br />
Now, everything is ready, let's start FreeCAD, create a new document, and, in the python interpreter, issue:<br />
<br />
import exercise<br />
<br />
If no error message appear, that means our exercise script has been loaded. We can now check its contents with:<br />
<br />
dir(exercise)<br />
<br />
The command dir() is a built-in python command that lists the contents of a module. We can see that our line() class is there, waiting for us. Now let's test it:<br />
<br />
exercise.line()<br />
<br />
Then, click two times in the 3D view, and bingo, here is our line! To do it again, just type exercise.line() again, and again, and again... Feels great, no?<br />
<br />
==Registering the script in the FreeCAD interface==<br />
<br />
Now, for our new line tool to be really cool, it should have a button on the interface, so we don't need to type all that stuff everytime. The easiest way is to transform our new MyScripts directory into a full FreeCAD workbench. It is easy, all that is needed is to put a file called '''InitGui.py''' inside your MyScripts directory. The InitGui.py will contain the instructions to create a new workbench, and add our new tool to it. Besides that we will also need to transform a bit our exercise code, so the line() tool is recognized as an official FreeCAD command. Let's start by making an InitGui.py file, and write the following code in it:<br />
<br />
class MyWorkbench (Workbench): <br />
MenuText = "MyScripts"<br />
def Initialize(self):<br />
import exercise<br />
commandslist = ["line"]<br />
self.appendToolbar("My Scripts",commandslist)<br />
Gui.addWorkbench(MyWorkbench())<br />
<br />
By now, you should already understand the above script by yourself, I think: We create a new class that we call MyWorkbench, we give it a title (MenuText), and we define an Initialize() function that will be executed when the workbench is loaded into FreeCAD. In that function, we load in the contents of our exercise file, and append the FreeCAD commands found inside to a command list. Then, we make a toolbar called "My Scripts" and we assign our commands list to it. Currently, of course, we have only one tool, so our command list contains only one element. Then, once our workbench is ready, we add it to the main interface.<br />
<br />
But this still won't work, because a FreeCAD command must be formatted in a certain way to work. So we will need to transform a bit our line() tool. Our new exercise.py script will now look like this:<br />
<br />
import FreeCADGui, Part<br />
from pivy.coin import *<br />
class line:<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
def Activated(self):<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
self.stack = []<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint) <br />
def getpoint(self,event_cb):<br />
event = event_cb.getEvent()<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
pos = event.getPosition()<br />
point = self.view.getPoint(pos[0],pos[1])<br />
self.stack.append(point)<br />
if len(self.stack) == 2:<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
shape = l.toShape()<br />
Part.show(shape)<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
def GetResources(self): <br />
return {'Pixmap' : 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'} <br />
FreeCADGui.addCommand('line', line())<br />
<br />
What we did here is transform our __init__() function into an Activated() function, because when FreeCAD commands are run, they automatically execute the Activated() function. We also added a GetResources() function, that informs FreeCAD where it can find an icon for the tool, and what will be the name and tooltip of our tool. Any jpg, png or svg image will work as an icon, it can be any size, but it is best to use a size that is close to the final aspect, like 16x16, 24x24 or 32x32.<br />
Then, we add the line() class as an official FreeCAD command with the addCommand() method.<br />
<br />
That's it, we now just need to restart FreeCAD and we'll have a nice new workbench with our brand new line tool!<br />
<br />
==So you want more?==<br />
<br />
If you liked this exercise, why not try to improve this little tool? There are many things that can be done, like for example:<br />
* Add user feedback: until now we did a very bare tool, the user might be a bit lost when using it. So we could add some feedback, telling him what to do next. For example, you could issue messages to the FreeCAD console. Have a look in the FreeCAD.Console module<br />
* Add a possibility to type the 3D points coordinates manually. Look at the python input() function, for example<br />
* Add the possibility to add more than 2 points<br />
* Add events for other things: Now we just check for Mouse button events, what if we would also do something when the mouse is moved, like displaying current coordinates?<br />
* Give a name to the created object<br />
Don't hesitate to write your questions or ideas on the [[Talk:Line_drawing_function|talk page]]!<br />
<br />
{{docnav|Code snippets|Dialog creation}}<br />
<br />
{{languages | {{cn|Line drawing function/cn}} {{es|Line drawing function/es}} {{fr|Line drawing function/fr}} {{it|Line drawing function/it}} {{jp|Line drawing function/jp}} {{ru|Line drawing function/ru}} {{se|Line drawing function/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Code_snippets&diff=16739Code snippets2013-02-02T06:21:13Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...<br />
<br />
<br />
=== A typical InitGui.py file ===<br />
<br />
Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one. <br />
<br />
class ScriptWorkbench (Workbench): <br />
MenuText = "Scripts"<br />
def Initialize(self):<br />
import Scripts # assuming Scripts.py is your module<br />
list = ["Script_Cmd"] # That list must contain command names, that can be defined in Scripts.py<br />
self.appendToolbar("My Scripts",list) <br />
<br />
Gui.addWorkbench(ScriptWorkbench())<br />
<br />
=== A typical module file ===<br />
<br />
This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.<br />
<br />
import FreeCAD, FreeCADGui <br />
<br />
class ScriptCmd: <br />
def Activated(self): <br />
# Here your write what your ScriptCmd does...<br />
FreeCAD.Console.PrintMessage('Hello, World!')<br />
def GetResources(self): <br />
return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} <br />
<br />
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())<br />
<br />
=== Import a new filetype ===<br />
<br />
Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:<br />
<br />
This line must be added to the InitGui.py file to add the new file extension to the list:<br />
<br />
# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files<br />
FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext") <br />
<br />
Then in the Import_Ext.py file:<br />
<br />
def open(filename): <br />
doc=App.newDocument()<br />
# here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects<br />
doc.recompute()<br />
<br />
To export your document to some new filetype works the same way, except that you use:<br />
FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext") <br />
<br />
=== Adding a line ===<br />
<br />
A line simply has 2 points.<br />
<br />
import Part,PartGui <br />
doc=App.activeDocument() <br />
# add a line element to the document and set its points <br />
l=Part.Line()<br />
l.StartPoint=(0.0,0.0,0.0)<br />
l.EndPoint=(1.0,1.0,1.0)<br />
doc.addObject("Part::Feature","Line").Shape=l.toShape() <br />
doc.recompute()<br />
<br />
=== Adding a polygon ===<br />
<br />
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.<br />
<br />
import Part,PartGui <br />
doc=App.activeDocument()<br />
n=list() <br />
# create a 3D vector, set its coordinates and add it to the list <br />
v=App.Vector(0,0,0) <br />
n.append(v) <br />
v=App.Vector(10,0,0) <br />
n.append(v) <br />
#... repeat for all nodes <br />
# Create a polygon object and set its nodes <br />
p=doc.addObject("Part::Polygon","Polygon") <br />
p.Nodes=n <br />
doc.recompute()<br />
<br />
=== Adding and removing an object to a group ===<br />
<br />
doc=App.activeDocument() <br />
grp=doc.addObject("App::DocumentObjectGroup", "Group") <br />
lin=doc.addObject("Part::Feature", "Line")<br />
grp.addObject(lin) # adds the lin object to the group grp<br />
grp.removeObject(lin) # removes the lin object from the group grp<br />
<br />
Note: You can even add other groups to a group...<br />
<br />
=== Adding a Mesh ===<br />
<br />
import Mesh<br />
doc=App.activeDocument()<br />
# create a new empty mesh<br />
m = Mesh.Mesh()<br />
# build up box out of 12 facets<br />
m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)<br />
m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0)<br />
m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0)<br />
m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0)<br />
m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0)<br />
m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0)<br />
m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0)<br />
m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0)<br />
m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0)<br />
m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0)<br />
m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0)<br />
m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)<br />
# scale to a edge langth of 100<br />
m.scale(100.0)<br />
# add the mesh to the active document<br />
me=doc.addObject("Mesh::Feature","Cube")<br />
me.Mesh=m<br />
<br />
=== Adding an arc or a circle ===<br />
<br />
import Part<br />
doc = App.activeDocument()<br />
c = Part.Circle() <br />
c.Radius=10.0 <br />
f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature <br />
f.Shape = c.toShape() # Assign the circle shape to the shape property <br />
doc.recompute()<br />
<br />
=== Accessing and changing representation of an object ===<br />
<br />
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...<br />
<br />
gad=Gui.activeDocument() # access the active document containing all <br />
# view representations of the features in the<br />
# corresponding App document <br />
<br />
v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube' <br />
v.ShapeColor # prints the color to the console <br />
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white<br />
<br />
=== Observing mouse events in the 3D viewer via Python ===<br />
<br />
The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.<br />
<br />
App.newDocument()<br />
v=Gui.activeDocument().activeView()<br />
<br />
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and<br />
#'up' events we need a boolean flag to handle this.<br />
class ViewObserver:<br />
def logPosition(self, info):<br />
down = (info["State"] == "DOWN")<br />
pos = info["Position"]<br />
if (down):<br />
FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")<br />
<br />
o = ViewObserver()<br />
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)<br />
<br />
Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call<br />
<br />
v.removeEventCallback("SoMouseButtonEvent",c)<br />
<br />
The following event types are supported<br />
* SoEvent -- all kind of events<br />
* SoButtonEvent -- all mouse button and key events<br />
* SoLocation2Event -- 2D movement events (normally mouse movements)<br />
* SoMotion3Event -- 3D movement events (normally spaceball)<br />
* SoKeyboradEvent -- key down and up events<br />
* SoMouseButtonEvent -- mouse button down and up events<br />
* SoSpaceballButtonEvent -- spaceball button down and up events<br />
<br />
The Python function that can be registered with addEventCallback() expects a dictionary. Depending on the watched event the dictionary can contain different keys. <br />
<br />
For all events it has the keys: <br />
* Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ... <br />
* Time -- the current time as string <br />
* Position -- a tuple of two integers, mouse position <br />
* ShiftDown -- a boolean, true if Shift was pressed otherwise false <br />
* CtrlDown -- a boolean, true if Ctrl was pressed otherwise false <br />
* AltDown -- a boolean, true if Alt was pressed otherwise false <br />
<br />
For all button events, i.e. keyboard, mouse or spaceball events <br />
* State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases <br />
<br />
For keyboard events: <br />
* Key -- a character of the pressed key <br />
<br />
For mouse button event <br />
* Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY <br />
<br />
For spaceball events: <br />
* Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY <br />
<br />
And finally motion events: <br />
* Translation -- a tuple of three floats <br />
* Rotation -- a quaternion for the rotation, i.e. a tuple of four floats<br />
<br />
=== Manipulate the scenegraph in Python ===<br />
<br />
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.<br />
<br />
from pivy.coin import * # load the pivy module<br />
view = Gui.ActiveDocument.ActiveView # get the active viewer<br />
root = view.getSceneGraph() # the root is an SoSeparator node<br />
root.addChild(SoCube())<br />
view.fitAll()<br />
<br />
The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python.<br />
However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with<br />
<br />
type = SoType.fromName("SoFCSelection")<br />
node = type.createInstance()<br />
<br />
=== Adding and removing objects to/from the scenegraph ===<br />
<br />
Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):<br />
<br />
from pivy import coin<br />
sg = Gui.ActiveDocument.ActiveView.getSceneGraph()<br />
co = coin.SoCoordinate3()<br />
pts = [[0,0,0],[10,0,0]]<br />
co.point.setValues(0,len(pts),pts)<br />
ma = coin.SoBaseColor()<br />
ma.rgb = (1,0,0)<br />
li = coin.SoLineSet()<br />
li.numVertices.setValue(2)<br />
no = coin.SoSeparator()<br />
no.addChild(co)<br />
no.addChild(ma)<br />
no.addChild(li)<br />
sg.addChild(no)<br />
<br />
To remove it, simply issue:<br />
<br />
sg.removeChild(no)<br />
<br />
===Adding custom widgets to the interface===<br />
<br />
You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PyQt4.<br />
<br />
The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):<br />
<br />
class myWidget_Ui(object):<br />
def setupUi(self, myWidget):<br />
myWidget.setObjectName("my Nice New Widget")<br />
myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget<br />
<br />
self.label = QtGui.QLabel(myWidget) # creates a label<br />
self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size<br />
self.label.setObjectName("label") # sets its name, so it can be found by name<br />
<br />
def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets<br />
myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8)) <br />
<br />
Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:<br />
<br />
app = QtGui.qApp<br />
FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it<br />
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget<br />
myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script<br />
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui<br />
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window<br />
<br />
===Adding a Tab to the Combo View===<br />
<br />
The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.<br />
<br />
from PyQt4 import QtGui,QtCore<br />
from PyQt4 import uic<br />
#from PySide import QtGui,QtCore<br />
<br />
def getMainWindow():<br />
"returns the main window"<br />
# using QtGui.qApp.activeWindow() isn't very reliable because if another<br />
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is<br />
# returned<br />
toplevel = QtGui.qApp.topLevelWidgets()<br />
for i in toplevel:<br />
if i.metaObject().className() == "Gui::MainWindow":<br />
return i<br />
raise Exception("No main window found")<br />
<br />
def getComboView(mw):<br />
dw=mw.findChildren(QtGui.QDockWidget)<br />
for i in dw:<br />
if str(i.objectName()) == "Combo View":<br />
return i.findChild(QtGui.QTabWidget)<br />
raise Exception("No tab widget found")<br />
<br />
mw = getMainWindow()<br />
tab = getComboView(getMainWindow())<br />
tab2=QtGui.QDialog()<br />
tab.addTab(tab2,"A Special Tab")<br />
uic.loadUi("/myTaskPanelforTabs.ui",tab2)<br />
tab2.show()<br />
<br />
#tab.removeTab(2)<br />
<br />
===Opening a custom webpage===<br />
<br />
import WebGui<br />
WebGui.openBrowser("http://www.example.com")<br />
<br />
===Getting the HTML contents of an opened webpage===<br />
<br />
from PyQt4 import QtGui,QtWebKit<br />
a = QtGui.qApp<br />
mw = a.activeWindow()<br />
v = mw.findChild(QtWebKit.QWebFrame)<br />
html = unicode(v.toHtml())<br />
print html<br />
<br />
{{docnav|Embedding FreeCAD|Line drawing function}}<br />
<br />
{{languages | {{cn|Code snippets/cn}} {{es|Code snippets/es}} {{fr|Code snippets/fr}} {{it|Code snippets/it}} {{jp|Code snippets/jp}} {{se|Code snippets/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Embedding_FreeCAD&diff=16738Embedding FreeCAD2013-02-02T06:19:52Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.<br />
<br />
=== Using FreeCAD without GUI ===<br />
<br />
One first, direct, easy and useful application you can make of this is to import FreeCAD documents into your program. In the following example, we'll import the Part geometry of a FreeCAD document into [http://www.blender.org blender]. Here is the complete script. I hope you'll be impressed by its simplicity:<br />
<br />
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file<br />
import Blender, sys<br />
sys.path.append(FREECADPATH)<br />
<br />
def import_fcstd(filename):<br />
try:<br />
import FreeCAD<br />
except ValueError:<br />
Blender.Draw.PupMenu('Error%t|FreeCAD library not found. Please check the FREECADPATH variable in the import script is correct')<br />
else:<br />
scene = Blender.Scene.GetCurrent()<br />
import Part<br />
doc = FreeCAD.open(filename)<br />
objects = doc.Objects<br />
for ob in objects:<br />
if ob.Type[:4] == 'Part':<br />
shape = ob.Shape<br />
if shape.Faces:<br />
mesh = Blender.Mesh.New()<br />
rawdata = shape.tessellate(1)<br />
for v in rawdata[0]:<br />
mesh.verts.append((v.x,v.y,v.z))<br />
for f in rawdata[1]:<br />
mesh.faces.append.append(f)<br />
scene.objects.new(mesh,ob.Name)<br />
Blender.Redraw()<br />
<br />
def main():<br />
Blender.Window.FileSelector(import_fcstd, 'IMPORT FCSTD', <br />
Blender.sys.makename(ext='.fcstd')) <br />
<br />
# This lets you import the script without running it<br />
if __name__=='__main__':<br />
main()<br />
<br />
The first, important part is to make sure python will find our FreeCAD library. Once it finds it, all FreeCAD modules such as Part, that we'll use too, will be available automatically. So we simply take the sys.path variable, which is where python searches for modules, and we append the FreeCAD lib path. This modification is only temporary, and will be lost when we'll close our python interpreter. Another way could be making a link to your FreeCAD library in one of the python search paths. I kept the path in a constant (FREECADPATH) so it'll be easier for another user of the script to configure it to his own system.<br />
<br />
Once we are sure the library is loaded (the try/except sequence), we can now work with FreeCAD, the same way as we would inside FreeCAD's own python interpreter. We open the FreeCAD document that is passed to us by the main() function, and we make a list of its objects. Then, as we choosed only to care about Part geometry, we check if the Type property of each object contains "Part", then we tesselate it.<br />
<br />
The tesselation produce a list of vertices and a list of faces defined by vertices indexes. This is perfect, since it is exactly the same way as blender defines meshes. So, our task is ridiculously simple, we just add both lists contents to the verts and faces of a blender mesh. When everything is done, we just redraw the screen, and that's it!<br />
<br />
Of course this script is very simple (in fact I made a more advanced [http://yorik.orgfree.com/scripts/import_freecad.py here]), you might want to extend it, for example importing mesh objects too, or importing Part geometry that has no faces, or import other file formats that FreeCAD can read. You might also want to export geometry to a FreeCAD document, which can be done the same way. You might also want to build a dialog, so the user can choose what to import, etc... The beauty of all this actually lies in the fact that you let FreeCAD do the ground work while presenting its results in the program of your choice.<br />
<br />
=== Using FreeCAD with GUI ===<br />
<br />
From version 4.2 on Qt has the intriguing ability to embed Qt-GUI-dependent plugins into non-Qt host applications and share the host's event loop.<br />
<br />
Especially, for FreeCAD this means that it can be imported from within another application with its whole user interface where the host application has full control over FreeCAD, then.<br />
<br />
The whole python code to achieve that has only two lines<br />
<br />
import FreeCADGui <br />
FreeCADGui.showMainWindow()<br />
<br />
If the host application is based on Qt then this solution should work on all platforms which Qt supports. However, the host should link the same Qt version as FreeCAD because otherwise you could run into unexpected runtime errors. <br />
<br />
For non-Qt applications, however, there are a few limitations you must be aware of. This solution probably doesn't work together with all other toolkits.<br />
For Windows it works as long as the host application is directly based on Win32 or any other toolkit that internally uses the Win32 API such as wxWidgets, MFC or WinForms. In order to get it working under X11 the host application must link the "glib" library.<br />
<br />
Note, for any console application this solution of course doesn't work because there is no event loop running.<br />
<br />
{{docnav|Scripted objects|Code snippets}}<br />
<br />
{{languages | {{cn|Embedding FreeCAD/cn}} {{es|Embedding FreeCAD/es}} {{fr|Embedding FreeCAD/fr}} {{it|Embedding FreeCAD/it}} {{jp|Embedding FreeCAD/jp}} {{se|Embedding FreeCAD/se}} {{ru|Embedding FreeCAD/ru}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Scripted_objects&diff=16737Scripted objects2013-02-02T06:18:45Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>Besides the standard object types such as annotations, meshes and parts objects, FreeCAD also offers the amazing possibility to build 100% python-scripted objects, called Python Features. Those objects will behave exactly as any other FreeCAD object, and are saved and restored automatically on file save/load.<br />
<br />
One particularity must be understood, those objects are saved in FreeCAD FcStd files with python's [http://docs.python.org/2/library/json.html json] module. That module turns a python object as a string, allowing it to be added to the saved file. On load, the json module uses that string to recreate the original object, provided it has access to the source code that created the object. This means that if you save such a custom object and open it on a machine where the python code that generated the object is not present, the object won't be recreated. If you distribute such objects to others, you will need to distribute the python script that created it together.<br />
<br />
Python Features follow the same rule as all FreeCAD features: they are separated into App and GUI parts. The app part, the Document Object, defines the geometry of our object, while its GUI part, the View Provider Object, defines how the object will be drawn on screen. The View Provider Object, as any other FreeCAD feature, is only available when you run FreeCAD in its own GUI. There are several properties and methods available to build your object. Properties must be of any of the predefined properties types that FreeCAD offers, and will appear in the property view window, so they can be edited by the user. This way, FeaturePython objects are truly and totally parametric. you can define properties for the Object and its ViewObject separately.<br />
<br />
'''Hint:''' In former versions we used Python's [http://docs.python.org/release/2.5/lib/module-cPickle.html cPickle] module. However, this module executes arbitrary code and thus causes a security problem. Thus, we moved to Python's json module. <br />
<br />
== Basic example ==<br />
<br />
The following sample can be found in the [http://free-cad.svn.sourceforge.net/viewvc/free-cad/trunk/src/Mod/TemplatePyMod/FeaturePython.py?view=markup src/Mod/TemplatePyMod/FeaturePython.py] file, together with several other examples:<br />
<br />
"Examples for a feature class and its view provider."<br />
<br />
import FreeCAD, FreeCADGui<br />
from pivy import coin<br />
<br />
class Box:<br />
def __init__(self, obj):<br />
"'''Add some custom properties to our box feature'''"<br />
obj.addProperty("App::PropertyLength","Length","Box","Length of the box").Length=1.0<br />
obj.addProperty("App::PropertyLength","Width","Box","Width of the box").Width=1.0<br />
obj.addProperty("App::PropertyLength","Height","Box", "Height of the box").Height=1.0<br />
obj.Proxy = self<br />
<br />
def onChanged(self, fp, prop):<br />
"'''Do something when a property has changed'''"<br />
FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")<br />
<br />
def execute(self, fp):<br />
"'''Do something when doing a recomputation, this method is mandatory'''"<br />
FreeCAD.Console.PrintMessage("Recompute Python Box feature\n")<br />
<br />
class ViewProviderBox:<br />
def __init__(self, obj):<br />
"'''Set this object to the proxy object of the actual view provider'''"<br />
obj.addProperty("App::PropertyColor","Color","Box","Color of the box").Color=(1.0,0.0,0.0)<br />
obj.Proxy = self<br />
<br />
def attach(self, obj):<br />
"'''Setup the scene sub-graph of the view provider, this method is mandatory'''"<br />
self.shaded = coin.SoGroup()<br />
self.wireframe = coin.SoGroup()<br />
self.scale = coin.SoScale()<br />
self.color = coin.SoBaseColor()<br />
<br />
data=coin.SoCube()<br />
self.shaded.addChild(self.scale)<br />
self.shaded.addChild(self.color)<br />
self.shaded.addChild(data)<br />
obj.addDisplayMode(self.shaded,"Shaded");<br />
style=coin.SoDrawStyle()<br />
style.style = coin.SoDrawStyle.LINES<br />
self.wireframe.addChild(style)<br />
self.wireframe.addChild(self.scale)<br />
self.wireframe.addChild(self.color)<br />
self.wireframe.addChild(data)<br />
obj.addDisplayMode(self.wireframe,"Wireframe");<br />
self.onChanged(obj,"Color")<br />
<br />
def updateData(self, fp, prop):<br />
"'''If a property of the handled feature has changed we have the chance to handle this here'''"<br />
# fp is the handled feature, prop is the name of the property that has changed<br />
l = fp.getPropertyByName("Length")<br />
w = fp.getPropertyByName("Width")<br />
h = fp.getPropertyByName("Height")<br />
self.scale.scaleFactor.setValue(l,w,h)<br />
pass<br />
<br />
def getDisplayModes(self,obj):<br />
"'''Return a list of display modes.'''"<br />
modes=[]<br />
modes.append("Shaded")<br />
modes.append("Wireframe")<br />
return modes<br />
<br />
def getDefaultDisplayMode(self):<br />
"'''Return the name of the default display mode. It must be defined in getDisplayModes.'''"<br />
return "Shaded"<br />
<br />
def setDisplayMode(self,mode):<br />
"'''Map the display mode defined in attach with those defined in getDisplayModes.\'''<br />
'''Since they have the same names nothing needs to be done. This method is optional'''"<br />
return mode<br />
<br />
def onChanged(self, vp, prop):<br />
"'''Here we can do something when a single property got changed'''"<br />
FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")<br />
if prop == "Color":<br />
c = vp.getPropertyByName("Color")<br />
self.color.rgb.setValue(c[0],c[1],c[2])<br />
<br />
def getIcon(self):<br />
"'''Return the icon in XPM format which will appear in the tree view. This method is\'''<br />
'''optional and if not defined a default icon is shown.'''"<br />
return """<br />
/* XPM */<br />
static const char * ViewProviderBox_xpm[] = {<br />
"16 16 6 1",<br />
" c None",<br />
". c #141010",<br />
"+ c #615BD2",<br />
"@ c #C39D55",<br />
"# c #000000",<br />
"$ c #57C355",<br />
" ........",<br />
" ......++..+..",<br />
" .@@@@.++..++.",<br />
" .@@@@.++..++.",<br />
" .@@ .++++++.",<br />
" ..@@ .++..++.",<br />
"###@@@@ .++..++.",<br />
"##$.@@$#.++++++.",<br />
"#$#$.$$$........",<br />
"#$$####### ",<br />
"#$$#$$$$$# ",<br />
"#$$#$$$$$# ",<br />
"#$$#$$$$$# ",<br />
" #$#$$$$$# ",<br />
" ##$$$$$# ",<br />
" ####### "};<br />
"""<br />
<br />
def __getstate__(self):<br />
"'''When saving the document this object gets stored using Python's json module.\'''<br />
'''Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\'''<br />
'''to return a tuple of all serializable objects or None.'''"<br />
return None<br />
<br />
def __setstate__(self,state):<br />
"'''When restoring the serialized object from document we have the chance to set some internals here.\'''<br />
'''Since no data were serialized nothing needs to be done here.'''"<br />
return None<br />
<br />
<br />
def makeBox():<br />
FreeCAD.newDocument()<br />
a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box")<br />
Box(a)<br />
ViewProviderBox(a.ViewObject)<br />
<br />
== Available properties ==<br />
<br />
Properties are the true building stones of FeaturePython objects. Through them, the user will be able to interact and modify your object. After creating a new FeaturePython object in your document ( obj=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), you can get a list of the available properties by issuing:<br />
<br />
obj.supportedProperties()<br />
<br />
You will get a list of available properties:<br />
<br />
App::PropertyBool<br />
App::PropertyFloat<br />
App::PropertyFloatList<br />
App::PropertyFloatConstraint<br />
App::PropertyAngle<br />
App::PropertyDistance<br />
App::PropertyInteger<br />
App::PropertyIntegerConstraint<br />
App::PropertyPercent<br />
App::PropertyEnumeration<br />
App::PropertyIntegerList<br />
App::PropertyString<br />
App::PropertyStringList<br />
App::PropertyLink<br />
App::PropertyLinkList<br />
App::PropertyMatrix<br />
App::PropertyVector<br />
App::PropertyVectorList<br />
App::PropertyPlacement<br />
App::PropertyPlacementLink<br />
App::PropertyColor<br />
App::PropertyColorList<br />
App::PropertyMaterial<br />
App::PropertyPath<br />
App::PropertyFile<br />
App::PropertyFileIncluded<br />
Part::PropertyPartShape<br />
Part::PropertyFilletContour<br />
Part::PropertyCircle<br />
<br />
When adding properties to your custom objects, take care of this:<br />
* Do not use characters "<" or ">" in the properties descriptions (that would break the xml pieces in the .fcstd file)<br />
* Properties are stored alphabetically in a .fcstd file. If you have a shape in your properties, any property whose name comes after "Shape" in alphabetic order, will be loaded AFTER the shape, which can cause strange behaviours.<br />
<br />
<br />
==Property Type==<br />
By default the properties can be updated. It is possible to make the properties read-only, for instance in the case one wants to show the result of a method. It is also possible to hide the property.<br />
The property type can be set using<br />
<br />
obj.setEditorMode("MyPropertyName", mode)<br />
<br />
where mode is a short int that can be set to:<br />
0 -- default mode, read and write<br />
1 -- read-only<br />
2 -- hidden<br />
<br />
== Other more complex example ==<br />
<br />
This example makes use of the [[Part Module]] to create an octahedron, then creates its coin representation with pivy.<br />
<br />
First is the Document object itself:<br />
<br />
import FreeCAD, FreeCADGui, Part<br />
<br />
class Octahedron:<br />
def __init__(self, obj):<br />
"Add some custom properties to our box feature"<br />
obj.addProperty("App::PropertyLength","Length","Octahedron","Length of the octahedron").Length=1.0<br />
obj.addProperty("App::PropertyLength","Width","Octahedron","Width of the octahedron").Width=1.0<br />
obj.addProperty("App::PropertyLength","Height","Octahedron", "Height of the octahedron").Height=1.0<br />
obj.addProperty("Part::PropertyPartShape","Shape","Octahedron", "Shape of the octahedron")<br />
obj.Proxy = self<br />
<br />
def execute(self, fp):<br />
# Define six vetices for the shape<br />
v1 = FreeCAD.Vector(0,0,0)<br />
v2 = FreeCAD.Vector(fp.Length,0,0)<br />
v3 = FreeCAD.Vector(0,fp.Width,0)<br />
v4 = FreeCAD.Vector(fp.Length,fp.Width,0)<br />
v5 = FreeCAD.Vector(fp.Length/2,fp.Width/2,fp.Height/2)<br />
v6 = FreeCAD.Vector(fp.Length/2,fp.Width/2,-fp.Height/2)<br />
<br />
# Make the wires/faces<br />
f1 = self.make_face(v1,v2,v5)<br />
f2 = self.make_face(v2,v4,v5)<br />
f3 = self.make_face(v4,v3,v5)<br />
f4 = self.make_face(v3,v1,v5)<br />
f5 = self.make_face(v2,v1,v6)<br />
f6 = self.make_face(v4,v2,v6)<br />
f7 = self.make_face(v3,v4,v6)<br />
f8 = self.make_face(v1,v3,v6)<br />
shell=Part.makeShell([f1,f2,f3,f4,f5,f6,f7,f8])<br />
solid=Part.makeSolid(shell)<br />
fp.Shape = solid<br />
<br />
# helper mehod to create the faces<br />
def make_face(self,v1,v2,v3):<br />
wire = Part.makePolygon([v1,v2,v3,v1])<br />
face = Part.Face(wire)<br />
return face<br />
<br />
Then, we have the view provider object, responsible for showing the object in the 3D scene:<br />
<br />
class ViewProviderOctahedron:<br />
def __init__(self, obj):<br />
"Set this object to the proxy object of the actual view provider"<br />
obj.addProperty("App::PropertyColor","Color","Octahedron","Color of the octahedron").Color=(1.0,0.0,0.0)<br />
obj.Proxy = self<br />
<br />
def attach(self, obj):<br />
"Setup the scene sub-graph of the view provider, this method is mandatory"<br />
self.shaded = coin.SoGroup()<br />
self.wireframe = coin.SoGroup()<br />
self.scale = coin.SoScale()<br />
self.color = coin.SoBaseColor()<br />
<br />
self.data=coin.SoCoordinate3()<br />
self.face=coin.SoIndexedLineSet()<br />
<br />
self.shaded.addChild(self.scale)<br />
self.shaded.addChild(self.color)<br />
self.shaded.addChild(self.data)<br />
self.shaded.addChild(self.face)<br />
obj.addDisplayMode(self.shaded,"Shaded");<br />
style=coin.SoDrawStyle()<br />
style.style = coin.SoDrawStyle.LINES<br />
self.wireframe.addChild(style)<br />
self.wireframe.addChild(self.scale)<br />
self.wireframe.addChild(self.color)<br />
self.wireframe.addChild(self.data)<br />
self.wireframe.addChild(self.face)<br />
obj.addDisplayMode(self.wireframe,"Wireframe");<br />
self.onChanged(obj,"Color")<br />
<br />
def updateData(self, fp, prop):<br />
"If a property of the handled feature has changed we have the chance to handle this here"<br />
# fp is the handled feature, prop is the name of the property that has changed<br />
if prop == "Shape":<br />
s = fp.getPropertyByName("Shape")<br />
self.data.point.setNum(6)<br />
cnt=0<br />
for i in s.Vertexes:<br />
self.data.point.set1Value(cnt,i.X,i.Y,i.Z)<br />
cnt=cnt+1<br />
<br />
self.face.coordIndex.set1Value(0,0)<br />
self.face.coordIndex.set1Value(1,1)<br />
self.face.coordIndex.set1Value(2,2)<br />
self.face.coordIndex.set1Value(3,-1)<br />
<br />
self.face.coordIndex.set1Value(4,1)<br />
self.face.coordIndex.set1Value(5,3)<br />
self.face.coordIndex.set1Value(6,2)<br />
self.face.coordIndex.set1Value(7,-1)<br />
<br />
self.face.coordIndex.set1Value(8,3)<br />
self.face.coordIndex.set1Value(9,4)<br />
self.face.coordIndex.set1Value(10,2)<br />
self.face.coordIndex.set1Value(11,-1)<br />
<br />
self.face.coordIndex.set1Value(12,4)<br />
self.face.coordIndex.set1Value(13,0)<br />
self.face.coordIndex.set1Value(14,2)<br />
self.face.coordIndex.set1Value(15,-1)<br />
<br />
self.face.coordIndex.set1Value(16,1)<br />
self.face.coordIndex.set1Value(17,0)<br />
self.face.coordIndex.set1Value(18,5)<br />
self.face.coordIndex.set1Value(19,-1)<br />
<br />
self.face.coordIndex.set1Value(20,3)<br />
self.face.coordIndex.set1Value(21,1)<br />
self.face.coordIndex.set1Value(22,5)<br />
self.face.coordIndex.set1Value(23,-1)<br />
<br />
self.face.coordIndex.set1Value(24,4)<br />
self.face.coordIndex.set1Value(25,3)<br />
self.face.coordIndex.set1Value(26,5)<br />
self.face.coordIndex.set1Value(27,-1)<br />
<br />
self.face.coordIndex.set1Value(28,0)<br />
self.face.coordIndex.set1Value(29,4)<br />
self.face.coordIndex.set1Value(30,5)<br />
self.face.coordIndex.set1Value(31,-1)<br />
<br />
def getDisplayModes(self,obj):<br />
"Return a list of display modes."<br />
modes=[]<br />
modes.append("Shaded")<br />
modes.append("Wireframe")<br />
return modes<br />
<br />
def getDefaultDisplayMode(self):<br />
"Return the name of the default display mode. It must be defined in getDisplayModes."<br />
return "Shaded"<br />
<br />
def setDisplayMode(self,mode):<br />
return mode<br />
<br />
def onChanged(self, vp, prop):<br />
"Here we can do something when a single property got changed"<br />
FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")<br />
if prop == "Color":<br />
c = vp.getPropertyByName("Color")<br />
self.color.rgb.setValue(c[0],c[1],c[2])<br />
<br />
def getIcon(self):<br />
return """<br />
/* XPM */<br />
static const char * ViewProviderBox_xpm[] = {<br />
"16 16 6 1",<br />
" c None",<br />
". c #141010",<br />
"+ c #615BD2",<br />
"@ c #C39D55",<br />
"# c #000000",<br />
"$ c #57C355",<br />
" ........",<br />
" ......++..+..",<br />
" .@@@@.++..++.",<br />
" .@@@@.++..++.",<br />
" .@@ .++++++.",<br />
" ..@@ .++..++.",<br />
"###@@@@ .++..++.",<br />
"##$.@@$#.++++++.",<br />
"#$#$.$$$........",<br />
"#$$####### ",<br />
"#$$#$$$$$# ",<br />
"#$$#$$$$$# ",<br />
"#$$#$$$$$# ",<br />
" #$#$$$$$# ",<br />
" ##$$$$$# ",<br />
" ####### "};<br />
"""<br />
<br />
def __getstate__(self):<br />
return None<br />
<br />
def __setstate__(self,state):<br />
return None<br />
<br />
Finally, once our object and its viewobject are defined, we just need to call them:<br />
<br />
FreeCAD.newDocument()<br />
a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron")<br />
Octahedron(a)<br />
ViewProviderOctahedron(a.ViewObject)<br />
<br />
== Making objects selectable ==<br />
<br />
If you want to make your object selectable, or at least part of it, by clicking on it in the viewport, you must include its coin geometry inside a SoFCSelection node. If your object has complex representation, with widgets, annotations, etc, you might want to include only a part of it in a SoFCSelection. Everything that is a SoFCSelection is constantly scanned by FreeCAD to detect selection/preselection, so it makes sense try not to overload it with unneeded scanning. This is what you would do to include a self.face from the example above:<br />
<br />
selectionNode = coin.SoType.fromName("SoFCSelection").createInstance()<br />
selectionNode.documentName.setValue(FreeCAD.ActiveDocument.Name)<br />
selectionNode.objectName.setValue(obj.Object.Name) # here obj is the ViewObject, we need its associated App Object<br />
selectionNode.subElementName.setValue("Face")<br />
selectNode.addChild(self.face)<br />
...<br />
self.shaded.addChild(selectionNode)<br />
self.wireframe.addChild(selectionNode)<br />
<br />
Simply, you create a SoFCSelection node, then you add your geometry nodes to it, then you add it to your main node, instead of adding your geometry nodes directly.<br />
<br />
== Working with simple shapes ==<br />
<br />
If your parametric object simply outputs a shape, you don't need to use a view provider object. The shape will be displayed using FreeCAD's standard shape representation:<br />
<br />
class Line:<br />
def __init__(self, obj):<br />
'''"App two point properties" '''<br />
obj.addProperty("App::PropertyVector","p1","Line","Start point")<br />
obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(1,0,0)<br />
obj.Proxy = self<br />
<br />
def execute(self, fp):<br />
'''"Print a short message when doing a recomputation, this method is mandatory" '''<br />
fp.Shape = Part.makeLine(fp.p1,fp.p2)<br />
<br />
a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")<br />
Line(a)<br />
a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification)<br />
FreeCAD.ActiveDocument.recompute()<br />
<br />
{{docnav|PyQt|Embedding FreeCAD}}<br />
<br />
{{languages | {{cn|Scripted objects/cn}} {{es|Scripted objects/es}} {{fr|Scripted objects/fr}} {{it|Scripted objects/it}} {{jp|Scripted objects/jp}} {{ru|Scripted objects/ru}} {{se|Scripted objects/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=PySide&diff=16736PySide2013-02-02T06:17:40Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>[http://en.wikipedia.org/wiki/PyQt PyQt] is a python module that allows python applications to create, access and modify [http://en.wikipedia.org/wiki/Qt_(toolkit) Qt] applications. You can use it for example to create your own Qt programs in python, or to access and modify the interface of a running qt application, like FreeCAD. <br />
<br />
By using the PyQt module from inside FreeCAD, you have therefore full control over its interface. You can for example:<br />
* Add your own panels, widgets and toolbars<br />
* Add or hide elements to existing panels<br />
* Change, redirect or add connections between all those elements<br />
<br />
PyQt has an extensive [http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html API documentation], and there are many tutorials on the net to teach you how it works.<br />
<br />
If you want to work on the FreeCAD interface, the very first thing to do is create a reference to the FreeCAD main window:<br />
<br />
import sys<br />
from PyQt4 import QtGui<br />
app = QtGui.qApp<br />
mw = app.activeWindow()<br />
<br />
Then, you can for example browse through all the widgets of the interface:<br />
<br />
for child in mw.children():<br />
print 'widget name = ', child.objectName(), ', widget type = ', child<br />
<br />
The widgets in a Qt interface are usually nested into "containers" widgets, so the children of our main window can themselves contain other children. Depending on the widget type, there are a lot of things you can do. Check the API documentation to see what is possible.<br />
<br />
Adding a new widget, for example a dockWidget (which can be placed in one of FreeCAD's side panels) is easy:<br />
<br />
myWidget = QtGui.QDockWidget()<br />
mw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myWidget)<br />
<br />
You could then add stuff directly to your widget:<br />
<br />
myWidget.setObjectName("my Nice New Widget")<br />
myWidget.resize(QtCore.QSize(300,100)) # sets size of the widget<br />
label = QtGui.QLabel("Hello World", myWidget) # creates a label<br />
label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size<br />
label.setObjectName("myLabel") # sets its name, so it can be found by name<br />
<br />
But a preferred method is to create a UI object which will do all of the setup of your widget at once. The big advantage is that such an UI object can be [[Dialog creation|created graphically]] with the Qt Designer program. A typical object generated by Qt Designer is like this:<br />
<br />
class myWidget_Ui(object):<br />
def setupUi(self, myWidget):<br />
myWidget.setObjectName("my Nice New Widget")<br />
myWidget.resize(QtCore.QSize(300,100).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget<br />
<br />
self.label = QtGui.QLabel(myWidget) # creates a label<br />
self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size<br />
self.label.setObjectName("label") # sets its name, so it can be found by name<br />
<br />
def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets<br />
myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))<br />
<br />
To use it, you just need to apply it to your freshly created widget like this:<br />
<br />
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget<br />
myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script<br />
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui<br />
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window<br />
<br />
{{docnav|Pivy|Scripted objects}}<br />
<br />
{{languages | {{cn|PyQt/cn}} {{es|PyQt/es}} {{fr|PyQt/fr}} {{it|PyQt/it}} {{jp|PyQt/jp}} {{ru|PyQt/ru}} {{se|PyQt/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Pivy&diff=16735Pivy2013-02-02T06:16:45Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>[http://pivy.coin3d.org/ Pivy] is a python binding library for [http://www.coin3d.org Coin3d], the 3D-rendering library used FreeCAD. When imported in a running python interpreter, it allows to dialog directly with any running Coin3d [[Scenegraph|scenegraphs]], such as the FreeCAD 3D views, or even to create new ones. Pivy is bundled in standard FreeCAD installation.<br />
<br />
The coin library is divided into several pieces, coin itself, for manipulating scenegraphs and bindings for several GUI systems, such as windows or, like in our case, qt. Those modules are available to pivy too, depending if they are present on the system. The coin module is always present, and it is what we will use anyway, since we won't need to care about anchoring our 3D display in any interface, it is already done by FreeCAD itself. All we need to do is this:<br />
<br />
from pivy import coin<br />
<br />
==Accessing and modifying the scenegraph==<br />
<br />
We saw in the [[Scenegraph]] page how a typical Coin scene is organized. Everything that appears in a FreeCAD 3D view is a coin scenegraph, organized the same way. We have one root node, and all objects on the screen are its children.<br />
<br />
FreeCAD has an easy way to access the root node of a 3D view scenegraph:<br />
<br />
sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()<br />
print sg<br />
<br />
This will return the root node:<br />
<br />
<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> ><br />
<br />
We can inspect the immediate children of our scene:<br />
<br />
for node in sg.getChildren():<br />
print node<br />
<br />
Some of those nodes, such as SoSeparators or SoGroups, can have children themselves. The complete list of the available coin objects can be found in the [http://doc.coin3d.org/Coin/classes.html official coin documentation].<br />
<br />
Let's try to add something to our scenegraph now. We'll add a nice red cube:<br />
<br />
col = coin.SoBaseColor()<br />
col.rgb=(1,0,0)<br />
cub = coin.SoCube()<br />
myCustomNode = coin.SoSeparator()<br />
myCustomNode.addChild(col)<br />
myCustomNode.addChild(cub)<br />
sg.addChild(myCustomNode)<br />
<br />
and here is our (nice) red cube. Now, let's try this:<br />
<br />
col.rgb=(1,1,0)<br />
<br />
See? everything is still accessible and modifiable on-the-fly. No need to recompute or redraw anything, coin takes care of everything. You can add stuff to your scenegraph, change properties, hide stuff, show temporary objects, anything. Of course, this only concerns the display in the 3D view. That display gets recomputed by FreeCAD on file open, and when an object needs recomputing. So, if you change the aspect of an existing FreeCAD object, those changes will be lost if the object gets recomputed or when you reopen the file.<br />
<br />
A key to work with scenegraphs in your scripts is to be able to access certain properties of the nodes you added when needed. For example, if we wanted to move our cube, we would have added a SoTranslation node to our custom node, and it would have looked like this:<br />
<br />
col = coin.SoBaseColor()<br />
col.rgb=(1,0,0)<br />
trans = coin.SoTranslation()<br />
trans.translation.setValue([0,0,0])<br />
cub = coin.SoCube()<br />
myCustomNode = coin.SoSeparator()<br />
myCustomNode.addChild(col)<br />
mtCustomNode.addChild(trans)<br />
myCustomNode.addChild(cub)<br />
sg.addChild(myCustomNode)<br />
<br />
Remember that in an openInventor scenegraph, the order is important. A node affects what comes next, so you can say something like: color red, cube, color yellow, sphere, and you will get a red cube and a yellow sphere. If we added the translation now to our existing custom node, it would come after the cube, and not affect it. If we had inserted it when creating it, like here above, we could now do:<br />
<br />
trans.translation.setValue([2,0,0])<br />
<br />
And our cube would jump 2 units to the right.<br />
Finally, removing something is done with:<br />
<br />
sg.removeChild(myCustomNode)<br />
<br />
==Using callback mechanisms==<br />
<br />
A [http://en.wikipedia.org/wiki/Callback_%28computer_science%29 callback mechanism] is a system that permits a library that you are using, such as our coin library, to call you back, that is, to call a certain function from your currently running python object. This is extremely useful, because that way coin can notify you if some specific event occurs in the scene. Coin can watch very different things, such as mouse position, clicks of a mouse button, keyboard keys being pressed, and many other things.<br />
<br />
FreeCAD features an easy way to use such callbacks:<br />
<br />
class ButtonTest:<br />
def __init__(self):<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getMouseClick) <br />
def getMouseClick(self,event_cb):<br />
event = event_cb.getEvent()<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
print "Alert!!! A mouse button has been improperly clicked!!!"<br />
self.view.removeEventCallbackSWIG(SoMouseButtonEvent.getClassTypeId(),self.callback) <br />
<br />
ButtonTest()<br />
<br />
The callback has to be initiated from an object, because that object must still be running when the callback will occur.<br />
See also a [[Code_snippets#Observing_mouse_events_in_the_3D_viewer_via_Python|complete list]] of possible events and their parameters, or the [http://doc.coin3d.org/Coin/classes.html official coin documentation].<br />
<br />
== Documentation == <br />
<br />
Unfortunately pivy itself still doesn't have a proper documentation, but since it is an accurate translation of coin, you can safely use the coin documentation as reference, and use python style instead of c++ style (for example SoFile::getClassTypeId() would in pivy be SoFile.getClassId())<br />
<br />
{{docnav|Scenegraph|PyQt}}<br />
<br />
{{languages | {{cn|Pivy/cn}} {{es|Pivy/es}} {{fr|Pivy/fr}} {{it|Pivy/it}} {{jp|Pivy/jp}} {{ru|Pivy/ru}} {{se|Pivy/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Scenegraph&diff=16734Scenegraph2013-02-02T06:15:36Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>FreeCAD is basically a collage of different powerful libraries, the most important being [http://en.wikipedia.org/wiki/Open_CASCADE openCascade], for managing and constructing geometry, [http://en.wikipedia.org/wiki/Coin3D Coin3d] to display that geometry, and [http://en.wikipedia.org/wiki/Qt_(toolkit) Qt] to put all this in a nice Graphical User Interface.<br />
<br />
The geometry that appears in the 3D views of FreeCAD are rendered by the Coin3D library. Coin3D is an implementation of the [http://en.wikipedia.org/wiki/Open_Inventor OpenInventor] standard. The openCascade software also provides the same functionality, but it was decided, at the very beginnings of FreeCAD, not to use the built-in openCascade viewer and rather switch to the more performant coin3D software. A good way to learn about that library is the book [http://www-evasion.imag.fr/Membres/Francois.Faure/doc/inventorMentor/sgi_html/ Open Inventor Mentor].<br />
<br />
[http://en.wikipedia.org/wiki/Open_Inventor OpenInventor] is actually a 3D scene description language. The scene described in openInventor is then rendered in OpenGL on your screen. Coin3D takes care of doing this, so the programmer doesn't need to deal with complex openGL calls, he just has to provide it with valid OpenInventor code. The big advantage is that openInventor is a very well-known and well documented standard.<br />
<br />
One of the big jobs FreeCAD does for you is basically to translate openCascade geometry information into openInventor language.<br />
<br />
OpenInventor describes a 3D scene in the form of a [http://en.wikipedia.org/wiki/Scene_graph scenegraph], like the one below:<br />
<br />
[[Image:Scenegraph.gif]]<br />
image from [http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html Inventor mentor]<br />
<br />
An openInventor scenegraph describes everything that makes part of a 3D scene, such as geometry, colors, materials, lights, etc, and organizes all that data in a convenient and clear structure. Everything can be grouped into sub-structures, allowing you to organize your scene contents pretty much the way you like. Here is an example of an openInventor file:<br />
<br />
#Inventor V2.0 ascii<br />
<br />
Separator { <br />
RotationXYZ { <br />
axis Z<br />
angle 0<br />
}<br />
Transform {<br />
translation 0 0 0.5<br />
}<br />
Separator { <br />
Material {<br />
diffuseColor 0.05 0.05 0.05<br />
}<br />
Transform {<br />
rotation 1 0 0 1.5708<br />
scaleFactor 0.2 0.5 0.2<br />
}<br />
Cylinder {<br />
}<br />
}<br />
}<br />
<br />
As you can see, the structure is very simple. You use separators to organize your data into blocks, a bit like you would organize your files into folders. Each statement affects what comes next, for example the first two items of our root separator are a rotation and a translation, both will affect the next item, which is a separator. In that separator, a material is defined, and another transformation. Our cylinder will therefore be affected by both transformations, the one who was applied directly to it and the one that was applied to its parent separator.<br />
<br />
We also have many other types of elements to organize our scene, such as groups, switches or annotations. We can define very complex materials for our objects, with color, textures, shading modes and transparency. We can also define lights, cameras, and even movement. It is even possible to embed pieces of scripting in openInventor files, to define more complex behaviours.<br />
<br />
If you are interested in learning more about openInventor, head directly to its most famous reference, the [http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html Inventor mentor].<br />
<br />
In FreeCAD, normally, we don't need to interact directly with the openInventor scenegraph. Every object in a FreeCAD document, being a mesh, a part shape or anything else, gets automatically converted to openInventor code and inserted in the main scenegraph that you see in a 3D view. That scenegraph gets updated continuously when you do modifications, add or remove objects to the document. In fact, every object (in App space) has a view provider (a corresponding object in Gui space), responsible for issuing openInventor code.<br />
<br />
But there are many advantages to be able to access the scenegraph directly. For example, we can temporarily change the appearence of an object, or we can add objects to the scene that have no real existence in the FreeCAD document, such as construction geometry, helpers, graphical hints or tools such as manipulators or on-screen information.<br />
<br />
FreeCAD itself features several tools to see or modify openInventor code. For example, the following python code will show the openInventor representation of a selected object:<br />
<br />
obj = FreeCAD.ActiveDocument.ActiveObject<br />
viewprovider = obj.ViewObject<br />
print viewprovider.toString()<br />
<br />
But we also have a python module that allows complete access to anything managed by Coin3D, such as our FreeCAD scenegraph. So, read on to [[Pivy]].<br />
<br />
{{docnav|Mesh to Part|Pivy}}<br />
<br />
{{languages | {{cn|Scenegraph/cn}} {{es|Scenegraph/es}} {{fr|Scenegraph/fr}} {{it|Scenegraph/it}} {{jp|Scenegraph/jp}} {{ru|Scenegraph/ru}} {{se|Scenegraph/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Mesh_to_Part&diff=16733Mesh to Part2013-02-02T06:14:19Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>== Converting Part objects to Meshes ==<br />
<br />
Converting higher-level objects such as [[Part Module|Part shapes]] into simpler objects such as [[Mesh Module|meshes]] is a pretty simple operation, where all faces of a Part object get triangulated. The result of that triangulation (tessellation) is then used to construct a mesh:<br />
<br />
#let's assume our document contains one part object<br />
import Mesh<br />
faces = []<br />
shape = FreeCAD.ActiveDocument.ActiveObject.Shape<br />
triangles = shape.tessellate(1) # the number represents the precision of the tessellation)<br />
for tri in triangles[1]:<br />
face = []<br />
for i in range(3):<br />
vindex = tri[i]<br />
face.append(triangles[0][vindex])<br />
faces.append(face)<br />
m = Mesh.Mesh(faces)<br />
Mesh.show(m)<br />
<br />
Sometimes the triangulation of certain faces offered by OpenCascade is quite ugly. If the face has a rectangular parameter space and doesn't contain any holes or other trimming curves you can also create a mesh on your own:<br />
<br />
import Mesh<br />
def makeMeshFromFace(u,v,face):<br />
(a,b,c,d)=face.ParameterRange<br />
pts=[]<br />
for j in range(v):<br />
for i in range(u):<br />
s=1.0/(u-1)*(i*b+(u-1-i)*a)<br />
t=1.0/(v-1)*(j*d+(v-1-j)*c)<br />
pts.append(face.valueAt(s,t))<br />
<br />
mesh=Mesh.Mesh()<br />
for j in range(v-1):<br />
for i in range(u-1):<br />
mesh.addFacet(pts[u*j+i],pts[u*j+i+1],pts[u*(j+1)+i])<br />
mesh.addFacet(pts[u*(j+1)+i],pts[u*j+i+1],pts[u*(j+1)+i+1])<br />
<br />
return mesh<br />
<br />
== Converting Meshes to Part objects ==<br />
<br />
Converting Meshes to Part objects is an extremely important operation in CAD work, because very often you receive 3D data in mesh format from other people or outputted from other applications. Meshes are very practical to represent free-form geometry and big visual scenes, as it is very lightweight, but for CAD we generally prefer higher-level objects that carry much more information, such as the idea of solid, or faces made of curves instead of triangles.<br />
<br />
Converting meshes to those higher-level objects (handled by the [[Part Module]] in FreeCAD) is not an easy operation. Meshes can be made of thousands of triangles (for example when generated by a 3D scanner), and having solids made of the same number of faces would be extremely heavy to manipulate. So you generally want to optimize the object when converting.<br />
<br />
FreeCAD currently offers two methods to convert Meshes to Part objects. The first method is a simple, direct conversion, without any optimization:<br />
<br />
import Mesh,Part<br />
mesh = Mesh.createTorus()<br />
shape = Part.Shape()<br />
shape.makeShapeFromMesh(mesh.Topology,0.05) # the second arg is the tolerance for sewing<br />
solid = Part.makeSolid(shape)<br />
Part.show(solid)<br />
<br />
The second method offers the possibility to consider mesh facets coplanar when the angle between them is under a certain value. This allows to build much simpler shapes:<br />
<br />
# let's assume our document contains one Mesh object<br />
import Mesh,Part,MeshPart<br />
faces = []<br />
mesh = App.ActiveDocument.ActiveObject.Mesh<br />
segments = mesh.getPlanes(0.00001) # use rather strict tolerance here<br />
<br />
for i in segments:<br />
if len(i) > 0:<br />
# a segment can have inner holes<br />
wires = MeshPart.wireFromSegment(mesh, i)<br />
# we assume that the exterior boundary is that one with the biggest bounding box<br />
if len(wires) > 0:<br />
ext=None<br />
max_length=0<br />
for i in wires:<br />
if i.BoundBox.DiagonalLength > max_length:<br />
max_length = i.BoundBox.DiagonalLength<br />
ext = i<br />
<br />
wires.remove(ext)<br />
# all interior wires mark a hole and must reverse their orientation, otherwise Part.Face fails<br />
for i in wires:<br />
i.reverse()<br />
<br />
# make sure that the exterior wires comes as first in the lsit<br />
wires.insert(0, ext)<br />
faces.append(Part.Face(wires))<br />
<br />
shell=Part.Compound(faces)<br />
Part.show(shell)<br />
#solid = Part.Solid(Part.Shell(faces))<br />
#Part.show(solid)<br />
<br />
{{docnav|Topological data scripting|Scenegraph}}<br />
<br />
{{languages |{{cn|Mesh to Part/cn}} {{es|Mesh to Part/es}} {{fr|Mesh to Part/fr}} {{it|Mesh to Part/it}} {{jp|Mesh to Part/jp}} {{ru|Mesh to Part/ru}} {{se|Mesh to Part/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Mesh_Scripting&diff=16732Mesh Scripting2013-02-02T06:12:56Z<p>Htsubota: Add Japanese to languages</p>
<hr />
<div>=== Introduction ===<br />
<br />
First of all you have to import the Mesh module:<br />
import Mesh<br />
After that you have access to the Mesh module and the Mesh class which facilitate the functions<br />
of the FreeCAD C++ Mesh-Kernel.<br />
<br />
=== Creation and Loading === <br />
<br />
To create an empty mesh object just use the standard constructor:<br />
mesh = Mesh.Mesh()<br />
You can also create an object from a file<br />
mesh = Mesh.Mesh('D:/temp/Something.stl')<br />
(A list of compatible filetypes can be found under 'Meshes' [[Feature_list#IO|here]].)<br />
<br />
Or create it out of a set of triangles described by their corner points:<br />
<br />
planarMesh = [<br />
# triangle 1<br />
[-0.5000,-0.5000,0.0000],[0.5000,0.5000,0.0000],[-0.5000,0.5000,0.0000],<br />
#triangle 2<br />
[-0.5000,-0.5000,0.0000],[0.5000,-0.5000,0.0000],[0.5000,0.5000,0.0000],<br />
]<br />
planarMeshObject = Mesh.Mesh(planarMesh)<br />
<br />
The Mesh-Kernel takes care about creating a topological correct data structure by sorting<br />
coincident points and edges together. <br />
<br />
Later on you will see how you can test and examine mesh data.<br />
<br />
=== Modeling === <br />
<br />
To create regular geometries you can use the Python script BuildRegularGeoms.py.<br />
import BuildRegularGeoms<br />
This script provides methods to define simple rotation bodies like spheres, ellipsoids, cylinders, toroids and cones. And it also has a method to create a simple cube.<br />
To create a toroid, for instance, can be done as follows:<br />
t = BuildRegularGeoms.Toroid(8.0, 2.0, 50) # list with several thousands triangles<br />
m = Mesh.Mesh(t)<br />
<br />
The first two parameters define the radiuses of the toroid and the third parameter is a sub-sampling factor for how many triangles are created. The higher this value the smoother and the lower the coarser the body is.<br />
The Mesh class provides a set of boolean functions that can be used for modeling purposes. It provides union, intersection and difference of two mesh objects.<br />
m1, m2 # are the input mesh objects<br />
m3 = Mesh.Mesh(m1) # create a copy of m1<br />
m3.unite(m2) # union of m1 and m2, the result is stored in m3<br />
m4 = Mesh.Mesh(m1)<br />
m4.intersect(m2) # intersection of m1 and m2<br />
m5 = Mesh.Mesh(m1)<br />
m5.difference(m2) # the difference of m1 and m2<br />
m6 = Mesh.Mesh(m2)<br />
m6.difference(m1) # the difference of m2 and m1, usually the result is different to m5<br />
Finally, a full example that computes the intersection between a sphere and a cylinder that intersects the sphere.<br />
import Mesh, BuildRegularGeoms<br />
sphere = Mesh.Mesh( BuildRegularGeoms.Sphere(5.0, 50) )<br />
cylinder = Mesh.Mesh( BuildRegularGeoms.Cylinder(2.0, 10.0, True, 1.0, 50) )<br />
diff = sphere<br />
diff.difference(cylinder)<br />
d = FreeCAD.newDocument()<br />
d.addObject("Mesh::Feature","Diff_Sphere_Cylinder").Mesh=diff<br />
d.recompute()<br />
<br />
=== Examining and Testing === <br />
<br />
=== Write your own Algorithms === <br />
<br />
=== Exporting === <br />
<br />
You can even write the mesh to a python module:<br />
m.write("D:/Develop/Projekte/FreeCAD/FreeCAD_0.7/Mod/Mesh/SavedMesh.py")<br />
import SavedMesh<br />
m2 = Mesh.Mesh(SavedMesh.faces)<br />
<br />
=== Gui related stuff === <br />
<br />
=== Odds and Ends === <br />
An extensive (though hard to use) source of Mesh related scripting are the unit test scripts of the Mesh-Module. <br />
In this unit tests literally all methods are called and all properties/attributes are tweaked.<br />
So if you are bold enough, take a look at the [http://free-cad.svn.sourceforge.net/viewvc/free-cad/trunk/src/Mod/Mesh/App/MeshTestsApp.py?view=markup Unit Test module].<br />
<br />
{{docnav|FreeCAD Scripting Basics|Topological data scripting}}<br />
<br />
{{languages | {{cn|Mesh Scripting/cn}} {{de|Mesh Scripting/de}} {{es|Mesh Scripting/es}} {{fr|Mesh Scripting/fr}} {{it|Mesh Scripting/it}} {{jp|Mesh Scripting/jp}} {{ru|Mesh Scripting/ru}} {{se|Mesh Scripting/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Python_scripting_tutorial&diff=16731Python scripting tutorial2013-02-02T06:11:28Z<p>Htsubota: Add Japanese to language</p>
<hr />
<div>[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a programming language, very simple to use and very fast to learn. It is open-source, multi-platform, and can be used alone for a wide array of things, from programming simple shell scripts to very complex programs. But one of its most widespread uses is as a scripting language, since it is easy to embed in other applications. That's exactly how it is used inside FreeCAD. From the python console, or from your custom scripts, you can pilot FreeCAD, and make it perform very complex actions for which there is still no graphical user interface tool.<br />
<br />
For example, from a python script, you can:<br />
* create new objects<br />
* modify existing objects<br />
* modify the 3D representation of those objects<br />
* modify the FreeCAD interface<br />
<br />
There are also several different ways to use python in FreeCAD:<br />
* From the [[FreeCAD Scripting Basics|FreeCAD python interpreter]], where you can issue simple commands like in a "command line"-style interface<br />
* From [[macros]], which are a convenient way to quickly add a missing tool to the FreeCAD interface<br />
* From external scripts, which can be used to program much more complex things. like entire [[Workbenches]].<br />
<br />
In this tutorial, we'll work on a couple of simple examples to get you started, but there is also much more [[Power users hub|documentation about python scripting]] available on this wiki. If you are totally new to python and want to understand how it works, we also have a basic [[introduction to python]].<br />
<br />
== Writing python code ==<br />
<br />
There are two easy ways to write python code in FreeCAD: From the python console (available from the View -> Views -> Python console menu) or from the Macro editor (Tools -> Macros). In the console, you write python commands one by one, which are executed when you press return, while the macros can contain a more complex script made of several lines, which is executed only when the macro is executed.<br />
<br />
[[Image:Screenshot_pythoninterpreter.jpg|center|frame|The FreeCAD python console]]<br />
<br />
In this tutorial, you will be able to use both methods, either by copying/pasting each line one by one in the python console and pressing {{KEY|Return}} after each line, or by copying/pasting the entire code in a new Macro window.<br />
<br />
== Exploring FreeCAD ==<br />
<br />
Let's start by creating a new empty document:<br />
<br />
doc = FreeCAD.newDocument()<br />
<br />
If you type this in the FreeCAD python console, you will notice that as soon as you type "FreeCAD.", a windows pops up, allowing to quickly autocomplete the rest of your line. Even better, each entry in the autocomplete list has a tooltip explaining what it does. This makes it very easy to explore the functionality available. Before choosing "newDocument", have a look at the other options available.<br />
<br />
[[Image:Screenshot_classbrowser.jpg|center|frame|The autocomplete mechanism of the FreeCAD python console]]<br />
<br />
Now our new document will be created. This is similar to pressing the "new document" button on the toolbar. In fact, most buttons in FreeCAD do nothing else than executing a line or two of python code. Even better, you can set an option in Edit -> Preferences -> General -> Macro to "show script commands in python console". This will print in the console all python code executed when you press buttons. Very useful to learn how to reproduce actions in python.<br />
<br />
Now let's get back to our document. Let's see what we can do with it:<br />
<br />
doc.<br />
<br />
Explore the available options. Usually names that begin with a capital letter are attributes, they contain a value, while names that begin with small letter are functions (also called methods), they "do something". Names that begin with an underscore are usually there for the internal working of the module, and you shouldn't care about them. Let's use one of the methods to add a new object to our document:<br />
<br />
box = doc.addObject("Part::Box","myBox")<br />
<br />
Nothing happens. Why? Because FreeCAD is made for the big picture. One day, it will work with hundreds of complex objects, all depending one from another. Making a small change somewhere could have a big impact, you may need to recalculate the whole document, which could take a long time... For that reason, almost no command updates the scene automatically. You must do it manually:<br />
<br />
doc.recompute()<br />
<br />
See? Now our box appeared! Many of the buttons that add objects in FreeCAD actually do 2 things: add the object, and recompute. If you turned on the "show script commands in python console" option above, try now adding a sphere with the GUI button, you'll see the two lines of python code being executed one after the other.<br />
<br />
What about the "Part::Box" will you ask? How can I know what other kind of objects can be added? It's all here:<br />
<br />
doc.supportedTypes()<br />
<br />
Now let's explore the contents of our box:<br />
<br />
box.<br />
<br />
You'll immediately see a couple of very interesting things such as:<br />
<br />
box.Height<br />
<br />
This will print the current height of our box. Now let's try to change that:<br />
<br />
box.Height = 5<br />
<br />
If you select your box with the mouse, you'll see that in the properties panel, in the "Data" tab, our "Height" property appears. All properties of a FreeCAD object that appear there (and also in the "View" tab, more about that later), are directly accessible by python too, by their names, like we did with the "Height" property. Try changing the other dimensions of that box.<br />
<br />
== Vectors and Placements ==<br />
<br />
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are a very fundamental concept in any 3D application. It is a list of 3 numbers (x, y and z), describing a point or position in the 3D space. A lot of things can be done with vectors, such as additions, subtractions, projections and [http://en.wikipedia.org/wiki/Vector_space much more]. In FreeCAD vectors work like this:<br />
<br />
myvec = FreeCAD.Vector(2,0,0)<br />
myvec<br />
myvec.x<br />
myvec.y<br />
othervec = FreeCAD.Vector(0,3,0)<br />
sumvec = myvec.add(othervec)<br />
<br />
Another common feature of FreeCAD objects is their [[Placement|placement]]. Each object has a Placement attributes, which contains the position (Base) and orientation (Rotation) of the object. It is easy to manipulate, for example to move our object:<br />
<br />
box.Placement.<br />
box.Placement.Base<br />
box.Placement.Base = sumvec<br />
<br />
otherpla = FreeCAD.Placement()<br />
box.Placement = otherpla<br />
<br />
Now you must understand a couple of important concepts before we get further.<br />
<br />
== App and Gui ==<br />
<br />
FreeCAD is made from the beginning to work as a command-line application, without its user interface. As a result, almost everything is separated between a "geometry" component and a "visual" component. When you work in command-line mode, the geometry part is present, but all the visual part is simply disabled. Almost any object in FreeCAD therefore is made of two parts, an Object and a ViewObject.<br />
<br />
To illustrate the concept, see our cube object, the geometric properties of the cube, such as its dimensions, position, etc... are stored in the object, while its visual properties, such as its color, line thickness, etc... are stored in the viewobject. This corresponds to the "Data" and "View" tabs in the property window. The view object of an object is accessed like this:<br />
<br />
vo = box.ViewObject<br />
<br />
Now you can also change the properties of the "View" tab:<br />
<br />
vo.Transparency = 80<br />
vo.hide()<br />
vo.show()<br />
<br />
When you start FreeCAD, the python console already loads 2 base modules: FreeCAD and FreeCADGui (which can also be accessed by their shortcuts App and Gui). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both FreeCAD and FreeCADGui contain an ActiveDocument attribute, which is the currently opened document. FreeCAD.ActiveDocument and FreeCADGui.ActiveDocument are not the same object. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example, FreeCADGui.ActiveDocument contains ActiveView, which is the currently opened 3D view<br />
<br />
== Modules ==<br />
<br />
Now you must surely wonder, what else than "Part::Box" can I do? The FreeCAD base application is more or less an empty container. Without its modules, it can do little more than creating new, empty documents. The true power of FreeCAD is in its faithful modules. Each of them adds not only new workbenches to the interface, but also new python commands and new object types. As a result, several different or even totally incompatible object types can coexist in the same document. The most important modules in FreeCAD, that we'll look at in this tutorial, are [[Part Module|Part]], [[Mesh Module|Mesh]], [[Sketcher Workbench|Sketcher]] or [[Draft Module|Draft]].<br />
<br />
[[Sketcher Workbench|Sketcher]] and [[Draft Module|Draft]] both use the [[Part Module|Part]] module to create and handle their geometry, which are BRep while[[Mesh Module|Mesh]] is totally independent, and handles its own objects. More about that below.<br />
<br />
You can check all the available base object types for the current document like this:<br />
<br />
doc.supportedTypes()<br />
<br />
The different FreeCAD modules, although they added their object types to FreeCAD, are not automatically loaded in the python console. This is to avoid having a very slow startup. Modules are loaded only when you need them. So, for example, to explore what's inside the Part module:<br />
<br />
import Part<br />
Part.<br />
<br />
But we'll talk more about the Part module below.<br />
<br />
By now, you know a bit more about the different modules of FreeCAD: The core modules (FreeCAD, FreeCADGui), and the workbenches modules (Part, Mesh, Sketcher). The other important modules are the 3d scene module (pivy) and the interface module (pyqt), we'll talk about them too below. <br />
<br />
Now it's time to explore a bit deeper the important ones, which are the workbench modules.<br />
<br />
== Mesh ==<br />
<br />
[http://en.wikipedia.org/wiki/Polygon_mesh Meshes] are a very simple kind of 3D objects, used for example by [http://en.wikipedia.org/wiki/SketchUp Sketchup], [http://en.wikipedia.org/wiki/Blender_%28software%29 Blender] or [http://en.wikipedia.org/wiki/Autodesk_3ds_Max 3D studio Max]. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. But of course nothing prevents you from having a bigger plane face made of several coplanar triangles.<br />
<br />
Meshes are simple, this can be a bad thing, but for many applications such as those above, it turns to be an advantage, because they are so simple that you can easily have millions of them in a single document. In FreeCAD, though, they have less use, and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. It was also extensively used as the main test module in the first month of life of FreeCAD.<br />
<br />
Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (like, we'll see below, for Part objects too). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object:<br />
<br />
import Mesh<br />
mymesh = Mesh.createSphere()<br />
mymesh.<br />
mymesh.Facets<br />
mymesh.Points<br />
<br />
meshobj = doc.addObject("Mesh::Feature","MyMesh")<br />
meshobj.Mesh = mymesh<br />
doc.recompute()<br />
<br />
This is a standard example, that uses the createSphere() method to automatically create a sphere, but you can very well create custom meshes from scratch, by defining their vertices and faces.<br />
<br />
[[Mesh Scripting|Read more about mesh scripting...]]<br />
<br />
== Part ==<br />
<br />
The [[Part Module]] is the most powerful module of the whole FreeCAD. It allows to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation BRep] objects. This kind of object, unlike meshes, can have a wide variety of components. To resume a bit, Brep means Boundary Representation. which means that they are defined by their surfaces, which enclose and define an inner volume. These surface can be a variety of things, such as plane faces or very complex NURBS surfaces. They also carry the concept of volume.<br />
<br />
The Part module is based on the powerful [http://en.wikipedia.org/wiki/Open_CASCADE_Technology OpenCasCade] library, which allows a wide range of complex operations to be easily performed on those objects, such as boolean operations, filleting, lofts, etc...<br />
<br />
The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object:<br />
<br />
import Part<br />
myshape = Part.makeSphere(10)<br />
myshape.<br />
myshape.Volume<br />
myshape.Area<br />
<br />
shapeobj = doc.addObject("Part::Feature","MyShape")<br />
shapeobj.Shape = myshape<br />
doc.recompute()<br />
<br />
The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and add a shape to it, so you can skip the 3 last lines above:<br />
<br />
Part.show(myshape)<br />
<br />
By exploring the contents of myshape, you will notice many interesting available subcomponents such as Faces, Edges, Vertexes, Solids or Shells, and a wide range of geometry operations such as cut (subtraction), common (intersection) or fuse (union). The [[Topological data scripting]] page explains all that in detail.<br />
<br />
[[Topological data scripting|Read more about part scripting...]]<br />
<br />
== Draft ==<br />
<br />
FreeCAD features many more modules, such as [[Sketcher Workbench|Sketcher]] or [[Draft Module|Draft]], which also create Part objects, but add parameters to it, or even carry a whole new way to handle the Part geometry in them. Our box example above, is a perfect example of parametric object. All you need, to define the box, is to specify a couple of parameters, such as height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to [[Scripted objects|create such objects in python]].<br />
<br />
The [[Draft Module]] adds a couple of 2D parametric objects types (which are all Part objects) such as lines and circles, and also provides some generic functions that work not only on Draft-made objects, but on any Part object. To explore what is available, simply do:<br />
<br />
import Draft<br />
Draft.<br />
rec = Draft.makeRectangle(5,2)<br />
mvec = FreeCAD.Vector(4,4,0)<br />
Draft.move(rec,mvec)<br />
Draft.move(box,mvec)<br />
<br />
== Interface ==<br />
<br />
The FreeCAD user interface is made with [http://en.wikipedia.org/wiki/Qt_%28framework%29 Qt], a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars, buttons around the 3D view. Qt provides a module, called PyQt, which allows python to access and modify Qt interfaces, such as FreeCAD. Let's try to fiddle with the Qt interface and produce a simple dialog:<br />
<br />
from PyQt4 import QtGui<br />
QtGui.QMessageBox.information(None,"Apollo program","Houston, we have a problem")<br />
<br />
See that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. We can therefore easily directly manipulate any part of the FreeCAD interface.<br />
<br />
Qt is a very powerful interface system, that allows you to do very complex things, but also has a couple of very easy-to use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a couple of lines of python.<br />
<br />
[[PyQt|Read more about pyqt here...]]<br />
<br />
== Macros ==<br />
<br />
Now that you have a good understanding of the basics, where are we going to keep our python scripts, and how are we going to launch them easily from FreeCAD? There is an easy mechanism for that, called [[Macros]]. A macro is simply a python script, that can then be added to a toolbar and be launched from a simple mouse click. FreeCAD provides you with a simple text editor (Macro -> Macros -> Create) where you can write or paste scripts. Once it is done, the Tools -> Customize -> Macros allow you to define a button for it, that can be added to toolbars.<br />
<br />
Now you are ready for more in-depth FreeCAD scripting. Head on to the [[Power users hub]]!<br />
<br />
{{docnav|Introduction to Python|FreeCAD Scripting Basics}}<br />
<br />
{{languages | {{cn|Python_scripting_tutorial/cn}} {{es|Python_scripting_tutorial/es}} {{fr|Python_scripting_tutorial/fr}} {{it|Python_scripting_tutorial/it}} {{jp|Python_scripting_tutorial/jp}} }}<br />
<br />
[[Category:Tutorials]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Introduction_to_Python&diff=16730Introduction to Python2013-02-02T06:10:12Z<p>Htsubota: Add Japanese to language</p>
<hr />
<div>This is a short tutorial made for who is totally new to Python. [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is an open-source, multiplatform [http://en.wikipedia.org/wiki/Programming_language programming language]. Python has several features that make it very different than other common programming languages, and very accessible to new users like yourself: <br />
<br />
*It has been designed specially to be easy to read by human beings, and so it is very easy to learn and understand.<br />
*It is interpreted, that is, unlike compiled languages like C, your program doesn't need to be compiled before it is executed. The code you write can be immediately executed, line by line if you want so. This makes it extremely easy to learn and to find errors in your code, because you go slowly, step-by-step.<br />
*It can be embedded in other programs to be used as scripting language. FreeCAD has an embedded Python interpreter, so you can write Python code in FreeCAD, that will manipulate parts of FreeCAD, for example to create geometry. This is extremely powerful, because instead of just clicking a button labeled "create sphere", that a programmer has placed there for you, you have the freedom to create easily your own tool to create exactly the geometry you want.<br />
*It is extensible, you can easily plug new modules in your Python installation and extend its functionality. For example, you have modules that allow Python to read and write jpg images, to communicate with twitter, to schedule tasks to be performed by your operating system, etc.<br />
<br />
So, hands on! Be aware that what will come next is a very simple introduction, by no means a complete tutorial. But my hope is that after that you'll get enough basics to explore deeper into the FreeCAD mechanisms.<br />
<br />
==The interpreter==<br />
<br />
Usually, when writing computer programs, you simply open a text editor or your special programming environment which is in most case a text editor with several tools around it, write your program, then compile it and execute it. Most of the time you made errors while writing, so your program won't work, and you will get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, and so on until your program works fine.<br />
<br />
That whole process, in Python, can be done transparently inside the Python interpreter. The interpreter is a Python window with a command prompt, where you can simply type Python code. If you install Python on your computer (download it from the [http://www.python.org Python website] if you are on Windows or Mac, install it from your package repository if you are on GNU/Linux), you will have a Python interpreter in your start menu. But FreeCAD also has a Python interpreter in its bottom part:<br />
<br />
[[Image:Screenshot_pythoninterpreter.jpg]]<br />
<br />
(If you don't have it, click on View → Views → Python console.)<br />
<br />
The interpreter shows the Python version, then a >>> symbol, which is the command prompt, that is, where you enter Python code. Writing code in the interpreter is simple: one line is one instruction. When you press Enter, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this:<br />
<br />
print "hello"<br />
<br />
<code>print</code> is a special Python keyword that means, obviously, to print something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write:<br />
<br />
print hello<br />
<br />
Python will tell us that it doesn't know what hello is. The " characters specify that the content is a string, which is simply, in programming jargon, a piece of text. Without the ", the print command believed hello was not a piece of text but a special Python keyword. The important thing is, you immediately get notified that you made an error. By pressing the up arrow (or, in the FreeCAD interpreter, CTRL+up arrow), you can go back to the last command you wrote and correct it.<br />
<br />
The Python interpreter also has a built-in help system. Try typing:<br />
<br />
help<br />
<br />
or, for example, let's say we don't understand what went wrong with our print hello command above, we want specific information about the "print" command:<br />
<br />
help("print")<br />
<br />
You'll get a long and complete description of everything the print command can do.<br />
<br />
Now we dominate totally our interpreter, we can begin with serious stuff.<br />
<br />
==Variables==<br />
<br />
Of course, printing "hello" is not very interesting. More interesting is printing stuff you don't know before, or let Python find for you. That's where the concept of variable comes in. A variable is simply a value that you store under a name. For example, type this:<br />
<br />
a = "hello"<br />
print a<br />
<br />
I guess you understood what happened, we "saved" the string "hello" under the name a. Now, a is not an unknown name anymore! We can use it anywhere, for example in the print command. We can use any name we want, just respecting simple rules, like not using spaces or punctuation. For example, we could very well write:<br />
<br />
hello = "my own version of hello"<br />
print hello<br />
<br />
See? now hello is not an undefined word anymore. What if, by terrible bad luck, we choosed a name that already exists in Python? Let's say we want to store our string under the name "print":<br />
<br />
print = "hello"<br />
<br />
Python is very intelligent and will tell us that this is not possible. It has some "reserved" keywords that cannot be modified. But our own variables can be modified anytime, that's exactly why they are called variables, the contents can vary. For example:<br />
<br />
myVariable = "hello"<br />
print myVariable<br />
myVariable = "good bye"<br />
print myVariable<br />
<br />
We changed the value of myVariable. We can also copy variables:<br />
<br />
var1 = "hello"<br />
var2 = var1<br />
print var2<br />
<br />
Note that it is interesting to give good names to your variables, because when you'll write long programs, after a while you won't remember what your variable named "a" is for. But if you named it for example myWelcomeMessage, you'll remember easily what it is used for when you'll see it.<br />
<br />
==Numbers==<br />
<br />
Of course you must know that programming is useful to treat all kind of data, and especially numbers, not only text strings. One thing is important, Python must know what kind of data it is dealing with. We saw in our print hello example, that the print command recognized our "hello" string. That is because by using the ", we told specifically the print command that what it would come next is a text string.<br />
<br />
We can always check what data type is the contents of a variable with the special Python keyword type:<br />
<br />
myVar = "hello"<br />
type(myVar)<br />
<br />
It will tell us the contents of myVar is 'str', or string in Python jargon. We have also other basic types of data, such as integer and float numbers:<br />
<br />
firstNumber = 10<br />
secondNumber = 20<br />
print firstNumber + secondNumber<br />
type(firstNumber)<br />
<br />
This is already much more interesting, isn't it? Now we already have a powerful calculator! Look well at how it worked, Python knows that 10 and 20 are integer numbers. So they are stored as "int", and Python can do with them everything it can do with integers. Look at the results of this:<br />
<br />
firstNumber = "10"<br />
secondNumber = "20"<br />
print firstNumber + secondNumber<br />
<br />
See? We forced Python to consider that our two variables are not numbers but mere pieces of text. Python can add two pieces of text together, but it won't try to find out any sum. But we were talking about integer numbers. There are also float numbers. The difference is that integer numbers don't have decimal part, while foat numbers can have a decimal part:<br />
<br />
var1 = 13<br />
var2 = 15.65<br />
print "var1 is of type ", type(var1)<br />
print "var2 is of type ", type(var2)<br />
<br />
Int and Floats can be mixed together without problem:<br />
<br />
total = var1 + var2<br />
print total<br />
print type(total)<br />
<br />
Of course the total has decimals, right? Then Python automatically decided that the result is a float. In several cases such as this one, Python automatically decides what type to give to something. In other cases it doesn't. For example:<br />
<br />
varA = "hello 123"<br />
varB = 456<br />
print varA + varB<br />
<br />
This will give us an error, varA is a string and varB is an int, and Python doesn't know what to do. But we can force Python to convert between types:<br />
<br />
varA = "hello"<br />
varB = 123<br />
print varA + str(varB)<br />
<br />
Now both are strings, the operation works! Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:<br />
<br />
varB = str(varB)<br />
<br />
We can also use int() and float() to convert to int and float if we want:<br />
<br />
varA = "123"<br />
print int(varA)<br />
print float(varA)<br />
<br />
'''Note on Python commands'''<br />
<br />
You must have noticed that in this section we used the print command in several ways. We printed variables, sums, several things separated by commas, and even the result of other Python command such as type(). Maybe you also saw that doing those two commands:<br />
<br />
type(varA)<br />
print type(varA)<br />
<br />
have exactly the same result. That is because we are in the interpreter, and everything is automatically printed on screen. When we'll write more complex programs that run outside the interpreter, they won't print automatically everything on screen, so we'll need to use the print command. But from now on, let's stop using it here, it'll go faster. So we can simply write:<br />
<br />
myVar = "hello friends"<br />
myVar<br />
<br />
You must also have seen that most of the Python commands (or keywords) we already know have parenthesis used to tell them on what contents the command must work: type(), int(), str(), etc. Only exception is the print command, which in fact is not an exception, it also works normally like this: print("hello"), but, since it is used often, the Python programmers made a simplified version.<br />
<br />
==Lists==<br />
<br />
Another interesting data type is lists. A list is simply a list of other data. The same way as we define a text string by using " ", we define lists by using [ ]:<br />
<br />
myList = [1,2,3]<br />
type(myList)<br />
myOtherList = ["Bart", "Frank", "Bob"]<br />
myMixedList = ["hello", 345, 34.567]<br />
<br />
You see that it can contain any type of data. Lists are very useful because you can group variables together. You can then do all kind of things within that groups, for example counting them:<br />
<br />
len(myOtherList)<br />
<br />
or retrieving one item of a list:<br />
<br />
myName = myOtherList[0]<br />
myFriendsName = myOtherList[1]<br />
<br />
You see that while the len() command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more stuff with lists such as you can read [http://www.diveintopython.net/native_data_types/lists.html here], such as sorting contents, removing or adding elements.<br />
<br />
A funny and interesting thing for you: a text string is very similar to a list of characters! Try doing this:<br />
<br />
myvar = "hello"<br />
len(myvar)<br />
myvar[2]<br />
<br />
Usually all you can do with lists can also be done with strings. In fact both lists and strings are sequences.<br />
<br />
Outside strings, ints, floats and lists, there are more built-in data types, such as [http://www.diveintopython.net/native_data_types/index.html#d0e5174 dictionnaries], or you can even create your own data types with [http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm classes].<br />
<br />
==Indentation==<br />
<br />
One big cool use of lists is also browsing through them and do something with each item. For example look at this:<br />
<br />
alldaltons = ["Joe", "William", "Jack", "Averell"]<br />
for dalton in alldaltons:<br />
print dalton + " Dalton"<br />
<br />
We iterated (programming jargon again!) through our list with the "for ... in ..." command and did something with each of the items. Note the special syntax: the for command terminates with : which indicates that what will comes after will be a block of one of more commands. Immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that a :-ended line has happened and that what will come next will be part of it. <br />
<br />
How will Python know how many of the next lines will be to be executed inside the for...in operation? For that, Python uses indentation. That is, your next lines won't begin immediately. You will begin them with a blank space, or several blank spaces, or a tab, or several tabs. Other programming languages use other methods, like putting everythin inside parenthesis, etc.<br />
As long as you write your next lines with the '''same''' indentation, they will be considered part of the for-in block. If you begin one line with 2 spaces and the next one with 4, there will be an error.<br />
When you finished, just write another line without indentation, or simply press Enter to come back from the for-in block<br />
<br />
Indentation is cool because if you make big ones (for example use tabs instead of spaces because it's larger), when you write a big program you'll have a clear view of what is executed inside what. We'll see that many other commands than for-in can have indented blocks of code too.<br />
<br />
For-in commands can be used for many things that must be done more than once. It can for example be combined with the range() command:<br />
<br />
serie = range(1,11)<br />
total = 0<br />
print "sum"<br />
for number in serie:<br />
print number<br />
total = total + number<br />
print "----"<br />
print total<br />
<br />
Or more complex things like this:<br />
<br />
alldaltons = ["Joe", "William", "Jack", "Averell"]<br />
for n in range(4):<br />
print alldaltons[n], " is Dalton number ", n<br />
<br />
You see that the range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:<br />
<br />
alldaltons = ["Joe", "William", "Jack", "Averell"]<br />
total = len(alldaltons)<br />
for n in range(total):<br />
print alldaltons[n]<br />
<br />
Another interesting use of indented blocks is with the if command. If executes a code block only if a certain condition is met, for example:<br />
<br />
alldaltons = ["Joe", "William", "Jack", "Averell"]<br />
if "Joe" in alldaltons:<br />
print "We found that Dalton!!!"<br />
<br />
Of course this will always print the first sentence, but try replacing the second line by:<br />
<br />
if "Lucky" in alldaltons:<br />
<br />
Then nothing is printed. We can also specify an else: statement:<br />
<br />
alldaltons = ["Joe", "William", "Jack", "Averell"]<br />
if "Lucky" in alldaltons:<br />
print "We found that Dalton!!!"<br />
else:<br />
print "Such Dalton doesn't exist!"<br />
<br />
==Functions==<br />
<br />
The [http://docs.python.org/reference/lexical_analysis.html#identifiers standard Python commands] are not many. In current version of Python there are about 30, and we already know several of them. But imagine if we could invent our own commands? Well, we can, and it's extremely easy. In fact, most the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:<br />
<br />
def printsqm(myValue):<br />
print str(myValue)+" square meters"<br />
<br />
printsqm(45)<br />
<br />
Extremely simple: the def() command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len() alone, Python will tell you it needs an argument. That is, you want len() of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len() function. The len() function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.<br />
<br />
The "myValue" name can be anything, and it will be used only inside the function. It is just a name you give to the argument so you can do something with it, but it also serves so the function knows how many arguments to expect. For example, if you do this:<br />
<br />
printsqm(45,34)<br />
<br />
There will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. We could instead do something like this:<br />
<br />
def sum(val1,val2):<br />
total = val1 + val2<br />
return total<br />
<br />
sum(45,34)<br />
myTotal = sum(45,34)<br />
<br />
We made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable. Of course, since we are in the interpreter and everything is printed, doing:<br />
<br />
sum(45,34)<br />
<br />
will print the result on the screen, but outside the interpreter, since there is no more print command inside the function, nothing would appear on the screen. You would need to do:<br />
<br />
print sum(45,34)<br />
<br />
to have something printed. Read more about functions [http://www.diveintopython.net/getting_to_know_python/declaring_functions.html here].<br />
<br />
==Modules==<br />
<br />
Now that we have a good idea of how Python works, we'll need one last thing: How to work with files and modules.<br />
<br />
Until now, we wrote Python instructions line by line in the interpreter, right? What if we could write several lines together, and have them executed all at once? It would certainly be handier for doing more complex things. And we could save our work too. Well, that too, is extremely easy. Simply open a text editor (such as the windows notepad), and write all your Python lines, the same way as you write them in the interpreter, with indentations, etc. Then, save that file somewhere, preferably with a .py extension. That's it, you have a complete Python program. Of course, there are much better editors than notepad, but it is just to show you that a Python program is nothing else than a text file.<br />
<br />
To make Python execute that program, there are hundreds of ways. In windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your .py program is. In FreeCAD, the easiest way is to place your program in a place that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. Suppose we write a file like this:<br />
<pre><br />
def sum(a,b):<br />
return a + b<br />
<br />
print "test.py succesfully loaded"<br />
</pre><br />
<br />
and we save it as test.py in our FreeCAD/bin directory. Now, let's start FreeCAD, and in the interpreter window, write:<br />
<br />
import test<br />
<br />
without the .py extension. This will simply execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. There is one big difference: the import command is made not only to execute programs written in files, like ours, but also to load the functions inside, so they become available in the interpreter. Files containing functions, like ours, are called modules.<br />
<br />
Normally when we write a sum() function in the interpreter, we execute it simply like that:<br />
<br />
sum(14,45)<br />
<br />
Like we did earlier. When we import a module containing our sum() function, the syntax is a bit different. We do:<br />
<br />
test.sum(14,45)<br />
<br />
That is, the module is imported as a "container", and all its functions are inside. This is extremely useful, because we can import a lot of modules, and keep everything well organized. So, basically, everywhere you see something.somethingElse, with a dot in between, that means somethingElse is inside something.<br />
<br />
We can also throw out the test part, and import our sum() function directly into the main interpreter space, like this:<br />
<br />
from test import *<br />
sum(12,54)<br />
<br />
Basically all modules behave like that. You import a module, then you can use its functions like that: module.function(argument). Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you to import modules inside your module!<br />
<br />
One last extremely useful thing. How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We saw already that Python has a help() function. Doing:<br />
<br />
help()<br />
modules<br />
<br />
Will give us a list of all available modules. We can now type q to get out of the interactive help, and import any of them. We can even browse their content with the dir() command<br />
<br />
import math<br />
dir(math)<br />
<br />
We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. The __doc__ is extremely useful, it is a documentation text. Every function of (well-made) modules has a __doc__ that explains how to use it. For example, we see that there is a sin function in side the math module. Want to know how to use it?<br />
<br />
print math.sin.__doc__<br />
<br />
And finally one last little goodie: When we work on programming a new module, we often want to test it. So once we wrote a little piece of module, in a python interpreter, we do something like this, to test our new code:<br />
<br />
import myModule<br />
myModule.myTestFunction()<br />
<br />
But what if we see that myTestFunction() doesn't work correctly? We go back to our editor and modifiy it. Then, instead of closing and reopening the python interpreter, we can simply update the module like this:<br />
<br />
reload(myModule)<br />
<br />
==Starting with FreeCAD==<br />
<br />
Well, I think you must know have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. So, just do<br />
<br />
dir()<br />
<br />
and read on to [[FreeCAD Scripting Basics]]...<br />
<br />
Of course, we saw here only a very small part of the Python world. There are many important concepts that we didn't mention here. There are three very important Python reference documents on the net:<br />
* the [http://docs.python.org/3/tutorial/index.html official Python tutorial with way more information than this one]<br />
* the [http://docs.python.org/reference/ official Python reference]<br />
* the [http://www.diveintopython.net Dive into Python] wikibook/ book.<br />
Be sure to bookmark them!<br />
<br />
<br />
{{docnav|Macros|Python scripting tutorial}}<br />
<br />
{{languages | {{cn|Introduction to python/cn}} {{de|Introduction to python/de}} {{fr|Introduction to python/fr}} {{es|Introduction to Python/es}} {{it|Introduction to Python/it}} {{jp|Introduction to python/jp}} {{pl|Introduction to python/pl}} {{ru|Introduction to python/ru}} {{se|Introduction to python/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Macros&diff=16729Macros2013-02-02T06:08:05Z<p>Htsubota: Add Japanese to language</p>
<hr />
<div>Macros are a convenient way to create complex actions in FreeCAD. You simply record actions as you do them, then save that under a name, and replay them whenever you want. Since macros are in reality a list of python commands, you can also edit them, and create very complex scripts.<br />
<br />
===How it works===<br />
<br />
If you enable console output (Menu Edit -> Preferences -> General -> Macros -> Show scripts commands in python console), you will see that in FreeCAD, every action you do, such as pressing a button, outputs a python command. Thos commands are what can be recorded in a macro. The main tool for making macros is the macros toolbar: [[Image:Macros_toolbar.jpg]]. On it you have 4 buttons: Record, stop recording, edit and play the current macro.<br />
<br />
It is very simple to use: Press the record button, you will be asked to give a name to your macro, then perform some actions. When you are done, click the stop recording button, and your actions will be saved. You can now access the macro dialog with the edit button:<br />
<br />
[[Image:Macros.jpg]]<br />
<br />
There you can manage your macros, delete, edit or create new ones from scratch. If you edit a macro, it will be opened in an editor window where you can make changes to its code.<br />
<br />
===Example===<br />
<br />
Press the record button, give a name, let's say "cylinder 10x10", then, in the [[Part Workbench]], create a cylinder with radius = 10 and height = 10. Then, press the "stop recording" button. In the edit macros dialog, you can see the python code that has been recorded, and, if you want, make alterations to it. To execute your macro, simply press the execute button on the toolbar while your macro is in the editor. You macro is always saved to disk, so any change you make, or any new macro you create, will always be available next time you start FreeCAD.<br />
<br />
===Customizing===<br />
<br />
Of course it is not practical to load a macro in the editor in order to use it. FreeCAD provides much better ways to use your macro, such as assigning a keyboard shortcut to it or putting an entry in the menu. Once your macro is created, all this can be done via the Tools -> Customize menu:<br />
<br />
[[Image:Macros config.jpg]]<br />
<br />
This way you can make your macro become a real tool, just like any standard FreeCAD tool. This, added to the power of python scripting within FreeCAD, makes it possible to easily add your own tools to the interface. Read on to the [[Scripting]] page if you want to know more about python scripting...<br />
<br />
===Creating macros without recording===<br />
<br />
You can also directly copy/paste python code into a macro, without recording GUI action. Simply create a new macro, edit it, and paste your code. You can then save your macro the same way as you save a FreeCAD document. Next time you start FreeCAD, the macro will appear under the "Installed Macros" item of the Macro menu.<br />
<br />
===Macros repository===<br />
<br />
Visit the [[Macros recipes]] page to pick some useful macros to add to your FreeCAD installation.<br />
<br />
{{docnav|Image Module|Introduction to python}}<br />
<br />
{{languages | {{cn|Macros/cn}} {{de|Macros/de}} {{es|Macros/es}} {{fr|Macros/fr}} {{it|Macros/it}} {{jp|Macros/jp}} {{pl|Macros/pl}} {{ru|Macros/ru}} {{se|Macros/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Licence&diff=16611Licence2013-01-26T04:27:56Z<p>Htsubota: Change because Coin3D is relicenced by BSD</p>
<hr />
<div>=== Statement of the maintainer ===<br />
<br />
I know that the discussion on the ''"right"'' licence for open source occupied a significant portion of internet bandwidth and so is here the reason why, in my opinion, FreeCAD should have this one.<br />
<br />
I chose the [http://en.wikipedia.org/wiki/LGPL LGPL] for the project and I know the pro and cons about the LGPL and will give you some reasons for that decision.<br />
<br />
FreeCAD is a mixture of a library and an application, so the GPL would be a little bit strong for that. It would prevent writing commercial modules for FreeCAD because it would prevent linking with the FreeCAD base libs. You may ask why commercial modules at all? Therefore Linux is good example. Would Linux be so successful when the GNU C Library would be GPL and therefore prevent linking against non-GPL applications? And although I love the freedom of Linux, I also want to be able to use the very good NVIDIA 3D graphic driver. I understand and accept the reason NVIDIA does not wish to give away driver code. We all work for companies and need payment or at least food. So for me, a coexistence of open source and closed source software is not a bad thing, when it obeys the rules of the LGPL. I would like to see someone writing a Catia import/export processor for FreeCAD and distribute it for free or for some money. I don't like to force him to give away more than he wants to. That wouldn't be good neither for him nor for FreeCAD.<br />
<br />
Nevertheless this decision is made only for the core system of FreeCAD. Every writer of an application module may make his own decision.<br />
<br />
=== Used Licences ===<br />
<br />
Here the two licences under which FreeCAD is published:<br />
<br />
;[[wikipedia:LGPL|Lesser General Public Licence (LGPL2+)]]: For the core libs as stated in the .h and .cpp files in src/App src/Gui src/Base and most [[Modules|modules]] in src/Mod and for the executable as stated in the .h and .cpp files in src/main. The icons and other graphic parts are also LGPL.<br />
;[[wikipedia:Open Publication License|Open Publication Licence]]: For the documentation on http://free-cad.sourceforge.net/ as not marked differently by the author <br />
<br />
<br />
See FreeCAD's [http://free-cad.git.sourceforge.net/git/gitweb.cgi?p=free-cad/free-cad;a=blob;f=package/debian/copyright;h=a97cf019d020edba596f2d0f614c9b09ce546b0f;hb=HEAD debian copyright file] for more details about the licenses used in FreeCAD<br />
<br />
=== License side effects ===<br />
Up to Version 0.13 FreeCAD is delivered as GPL2+, although the source itself is under LGPL2+. Thats because of linkage of Coin3D (GPL2) and PyQt(GPL). Starting with 0.14 we will be completely GPL free. PyQt will be replaced by PySide, and Coin3D was re-licensed under BSD. One problem, we still have to face, license-wise, the [http://www.opencascade.org/getocc/license/ OCTPL (Open CASCADE Technology Public License)]. Its a License mostly LGPL similar, with certain changes. On of the originators, Roman Lygin, elaborated on the License on his [http://opencascade.blogspot.de/2008/12/license-to-kill-license-to-use.html Blog]. The home-brew OCTPL license leads to all kind of side effects for FreeCAD, which where widely discussed on different forums and mailing lists, e.g. on [http://www.opencascade.org/org/forum/thread_15859/?forum=3 OpenCasCade forum itself]. I will link here some articles for the biggest problems.<br />
<br />
<br />
==== GPL2/GPL3/OCTLP incompatibility ====<br />
<br />
We first discovered the problem by a discussion on the [http://www.fsf.org/ FSF] high priority project [https://groups.google.com/forum/#!topic/polignu/XRergtwsm80 discussion list]. It was about a library we look at, which was licensed with GPL3. Since we linked back then with Coin3D, with GPL2 only, we was not able to adopt that lib. Also the <br />
OCTPL is considered [http://www.opencascade.org/occt/faq/ GPL incompatible]. This Libre Graphics World article [http://libregraphicsworld.org/blog/entry/libredwg-drama-the-end-or-the-new-beginning "LibreDWG drama: the end or the new beginning?"] shows up the drama of LibreDWG project not acceptably in FreeCAD or LibreCAD. <br />
<br />
==== Debian ====<br />
The incompatibility of the OCTPL [http://lists.debian.org/debian-legal/2009/10/msg00000.html was discussed on the debian legal list] and lead to a [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=617613 bug report on the FreeCAD package] which prevent (ignor-tag) the transition from debian-testing to the main distribution. But its also mentioned thats a FreeCAD, which is free of GPL code and libs, would be acceptably. With a re-licensed Coin3D V4 and a substituted PyQt we will hopefully reach GPL free with the 0.14 release. <br />
<br />
==== Fedora/RedHat non-free ====<br />
In the Fedora project OpenCasCade is listed "non-free". This means basically it won't make it into Fedora or RedHat. This means also FreeCAD won't make it into Fedora/RedHat until OCC is changing its license. Here the links to the license evaluation:<br />
* [http://lists.fedoraproject.org/pipermail/legal/2011-September/001713.html Discussion on the Fedora-legal-list]<br />
* [https://bugzilla.redhat.com/show_bug.cgi?id=458974#c10 License review entry in the RedHat bug tracker]<br />
The main problem they have AFIK is that the OCC license demand non discriminatory support fees if you want to do paid support. It has nothing to do with "free" or OpenSource, its all about RedHat's business model!<br />
<br />
=== Impact of the licences ===<br />
<br />
==== Private users ====<br />
Private users can use FreeCAD free of charge and can do basically whatever they want to do with it....<br />
<br />
==== Professional users ====<br />
Can use FreeCAD freely, for any kind of private or professional work. They can customize the application as they wish. They can write open or closed source extensions to FreeCAD. They are always master of their data, they are not forced to update FreeCAD, change their usage of FreeCAD. Using FreeCAD doesn't bind them to any kind of contract or obligation.<br />
<br />
==== Open Source developers ====<br />
Can use FreeCAD as the groundwork for own extension modules for special purposes. They can choose either the GPL or the LGPL to allow the use of their work in proprietary software or not.<br />
<br />
==== Commercial developers ====<br />
Commercial developers can use FreeCAD as the groundwork for their own extension modules for special purposes and are not forced to make their modules open source. They can use all modules which use the LGPL. They are allowed to distribute FreeCAD along with their proprietary software. They will get the support of the author(s) as long as it is not a one way street.<br />
<br />
{{docnav|Dialog creation|Tracker}}<br />
<br />
{{languages | {{cn|Licence/cn}} {{de|Licence/de}} {{es|Licence/es}} {{fr|Licence/fr}} {{jp|Licence/jp}} {{ru|Licence/ru}} {{se|Licence/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Licence&diff=16610Licence2013-01-26T03:59:22Z<p>Htsubota: /* Used Licences */</p>
<hr />
<div>=== Statement of the maintainer ===<br />
<br />
I know that the discussion on the ''"right"'' licence for open source occupied a significant portion of internet bandwidth and so is here the reason why, in my opinion, FreeCAD should have this one.<br />
<br />
I chose the [http://en.wikipedia.org/wiki/LGPL LGPL] for the project and I know the pro and cons about the LGPL and will give you some reasons for that decision.<br />
<br />
FreeCAD is a mixture of a library and an application, so the GPL would be a little bit strong for that. It would prevent writing commercial modules for FreeCAD because it would prevent linking with the FreeCAD base libs. You may ask why commercial modules at all? Therefore Linux is good example. Would Linux be so successful when the GNU C Library would be GPL and therefore prevent linking against non-GPL applications? And although I love the freedom of Linux, I also want to be able to use the very good NVIDIA 3D graphic driver. I understand and accept the reason NVIDIA does not wish to give away driver code. We all work for companies and need payment or at least food. So for me, a coexistence of open source and closed source software is not a bad thing, when it obeys the rules of the LGPL. I would like to see someone writing a Catia import/export processor for FreeCAD and distribute it for free or for some money. I don't like to force him to give away more than he wants to. That wouldn't be good neither for him nor for FreeCAD.<br />
<br />
Nevertheless this decision is made only for the core system of FreeCAD. Every writer of an application module may make his own decision.<br />
<br />
=== Used Licences ===<br />
<br />
Here the two licences under which FreeCAD is published:<br />
<br />
;[[wikipedia:LGPL|Lesser General Public Licence (LGPL2+)]]: For the core libs as stated in the .h and .cpp files in src/App src/Gui src/Base and most [[Modules|modules]] in src/Mod and for the executable as stated in the .h and .cpp files in src/main. The icons and other graphic parts are also LGPL.<br />
;[[wikipedia:Open Publication License|Open Publication Licence]]: For the documentation on http://free-cad.sourceforge.net/ as not marked differently by the author <br />
<br />
<br />
See FreeCAD's [http://free-cad.git.sourceforge.net/git/gitweb.cgi?p=free-cad/free-cad;a=blob;f=package/debian/copyright;h=a97cf019d020edba596f2d0f614c9b09ce546b0f;hb=HEAD debian copyright file] for more details about the licenses used in FreeCAD<br />
<br />
=== License side effects ===<br />
Up to Version 0.13 FreeCAD is delivered as GPL2+, although the source itself is under LGPL2+. Thats because of linkage of Coin3D (GPL2) and PyQt(GPL). Starting with 0.14 we will be completely GPL free. PyQt will be replaced by PySide, and Coin3D was re-licensed under BSD. One problem, we still have to face, license-wise, the [http://www.opencascade.org/getocc/license/ OCTPL (Open CASCADE Technology Public License)]. Its a License mostly LGPL similar, with certain changes. On of the originators, Roman Lygin, elaborated on the License on his [http://opencascade.blogspot.de/2008/12/license-to-kill-license-to-use.html Blog]. The home-brew OCTPL license leads to all kind of side effects for FreeCAD, which where widely discussed on different forums and mailing lists, e.g. on [http://www.opencascade.org/org/forum/thread_15859/?forum=3 OpenCasCade forum itself]. I will link here some articles for the biggest problems.<br />
<br />
<br />
==== GPL2/GPL3/OCTLP incompatibility ====<br />
<br />
We first discovered the problem by a discussion on the [http://www.fsf.org/ FSF] high priority project [https://groups.google.com/forum/#!topic/polignu/XRergtwsm80 discussion list]. It was about a library we look at, which was licensed with GPL3. Since we linked back then with Coin3D, with GPL2 only, we was not able to adopt that lib. Also the <br />
OCTPL is considered [http://www.opencascade.org/occt/faq/ GPL incompatible]. This Libre Graphics World article [http://libregraphicsworld.org/blog/entry/libredwg-drama-the-end-or-the-new-beginning "LibreDWG drama: the end or the new beginning?"] shows up the drama of LibreDWG project not acceptably in FreeCAD or LibreCAD. <br />
<br />
==== Debian ====<br />
The incompatibility of the OCTPL [http://lists.debian.org/debian-legal/2009/10/msg00000.html was discussed on the debian legal list] and lead to a [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=617613 bug report on the FreeCAD package] which prevent (ignor-tag) the transition from debian-testing to the main distribution. But its also mentioned thats a FreeCAD, which is free of GPL code and libs, would be acceptably. With a re-licensed Coin3D V4 and a substituted PyQt we will hopefully reach GPL free with the 0.14 release. <br />
<br />
==== Fedora/RedHat non-free ====<br />
In the Fedora project OpenCasCade is listed "non-free". This means basically it won't make it into Fedora or RedHat. This means also FreeCAD won't make it into Fedora/RedHat until OCC is changing its license. Here the links to the license evaluation:<br />
* [http://lists.fedoraproject.org/pipermail/legal/2011-September/001713.html Discussion on the Fedora-legal-list]<br />
* [https://bugzilla.redhat.com/show_bug.cgi?id=458974#c10 License review entry in the RedHat bug tracker]<br />
The main problem they have AFIK is that the OCC license demand non discriminatory support fees if you want to do paid support. It has nothing to do with "free" or OpenSource, its all about RedHat's business model!<br />
<br />
=== Impact of the licences ===<br />
<br />
==== Private users ====<br />
Private users can use FreeCAD free of charge and can do basically whatever they want to do with it....<br />
<br />
==== Professional users ====<br />
Can use FreeCAD freely, for any kind of private or professional work. They can customize the application as they wish. They can write open or closed source extensions to FreeCAD. They are always master of their data, they are not forced to update FreeCAD, change their usage of FreeCAD. Using FreeCAD doesn't bind them to any kind of contract or obligation.<br />
<br />
==== Open Source developers ====<br />
Can use FreeCAD as the groundwork for own extension modules for special purposes. They can choose either the GPL or the LGPL to allow the use of their work in proprietary software or not.<br />
<br />
==== Commercial developers ====<br />
Commercial developers can use FreeCAD as the groundwork for their own extension modules for special purposes and are not forced to make their modules open source. They can use all modules which use the LGPL. They are allowed to distribute FreeCAD along with their proprietary software. They will get the support of the author(s) as long as it is not a one way street. If you want to sell your module you need a Coin3D licence, otherwise you are forced by this library to make it open source.<br />
<br />
{{docnav|Dialog creation|Tracker}}<br />
<br />
{{languages | {{cn|Licence/cn}} {{de|Licence/de}} {{es|Licence/es}} {{fr|Licence/fr}} {{jp|Licence/jp}} {{ru|Licence/ru}} {{se|Licence/se}} }}<br />
<br />
[[Category:Developer Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Dialog_creation&diff=16573Dialog creation2013-01-25T12:55:44Z<p>Htsubota: /* Making our dialog do something */</p>
<hr />
<div>In this page we will show how to build a simple Qt Dialog with [http://doc.trolltech.com/4.3/designer-manual.html Qt Designer], Qt's official tool for designing interfaces, then convert it to python code, then use it inside FreeCAD. I'll assume in the example that you know how to edit and run python scripts already, and that you can do simple things in a terminal window such as navigate, etc. You must also have, of course, pyqt installed.<br />
<br />
== Designing the dialog ==<br />
<br />
In CAD applications, designing a good UI (User Interface) is very important. About everything the user will do will be through some piece of interface: reading dialog boxes, pressing buttons, choosing between icons, etc. So it is very important to think carefully to what you want to do, how you want the user to behave, and how will be the workflow of your action.<br />
<br />
There are a couple of concepts to know when designing interface:<br />
* [http://en.wikipedia.org/wiki/Modal_window Modal/non-modal dialogs]: A modal dialog appears in front of your screen, stopping the action of the main window, forcing the user to respond to the dialog, while a non-modal dialog doesn't stop you from working on the main window. In some case the first is better, in other cases not.<br />
* Identifying what is required and what is optional: Make sure the user knows what he must do. Label everything with proper description, use tooltips, etc.<br />
* Separating commands from parameters: This is usually done with buttons and text input fields. The user knows that clicking a button will produce an action while changing a value inside a text field will change a parameter somewhere. Nowadays, though, users usually know well what is a button, what is an input field, etc. The interface toolkit we are using, Qt, is a state-of-the-art toolkit, and we won't have to worry much about making things clear, since they will already be very clear by themselves.<br />
<br />
So, now that we have well defined what we will do, it's time to open the qt designer. Let's design a very simple dialog, like this:<br />
<br />
[[Image:Qttestdialog.jpg]]<br />
<br />
We will then use this dialog in FreeCAD to produce a nice rectangular plane. You might find it not very useful to produce nice rectangular planes, but it will be easy to change it later to do more complex things. When you open it, Qt Designer looks like this:<br />
<br />
[[Image:Qtdesigner-screenshot.jpg]]<br />
<br />
It is very simple to use. On the left bar you have elements that can be dragged on your widget. On the right side you have properties panels displaying all kinds of editable properties of selected elements. So, begin with creating a new widget. Select "Dialog without buttons", since we don't want the default Ok/Cancel buttons. Then, drag on your widget '''3 labels''', one for the title, one for writing "Height" and one for writing "Width". Labels are simple texts that appear on your widget, just to inform the user. If you select a label, on the right side will appear several properties that you can change if you want, such as font style, height, etc.<br />
<br />
Then, add '''2 LineEdits''', which are text fields that the user can fill in, one for the height and one for the width. Here too, we can edit properties. For example, why not set a default value? For example 1.00 for each. This way, when the user will see the dialog, both values will be filled already and if he is satisfied he can directly press the button, saving precious time. Then, add a '''PushButton''', which is the button the user will need to press after he filled the 2 fields.<br />
<br />
Note that I choosed here very simple controls, but Qt has many more options, for example you could use Spinboxes instead of LineEdits, etc... Have a look at what is available, you will surely have other ideas.<br />
<br />
That's about all we need to do in Qt Designer. One last thing, though, let's rename all our elements with easier names, so it will be easier to identify them in our scripts:<br />
<br />
[[Image:Qtpropeditor.jpg]]<br />
<br />
== Converting our dialog to python ==<br />
<br />
Now, let's save our widget somewhere. It will be saved as an .ui file, that we will easily convert to python script with pyuic. On windows, the pyuic program is bundled with pyqt (to be verified), on linux you probably will need to install it separately from your package manager (on debian-based systems, it is part of the pyqt4-dev-tools package). To do the conversion, you'll need to open a terminal window (or a command prompt window on windows), navigate to where you saved your .ui file, and issue:<br />
<br />
pyuic mywidget.ui > mywidget.py<br />
<br />
On some systems the program is called pyuic4 instead of pyuic. This will simply convert the .ui file into a python script. If we open the mywidget.py file, its contents are very easy to understand:<br />
<br />
from PyQt4 import QtCore, QtGui<br />
<br />
class Ui_Dialog(object):<br />
def setupUi(self, Dialog):<br />
Dialog.setObjectName("Dialog")<br />
Dialog.resize(187, 178)<br />
self.title = QtGui.QLabel(Dialog)<br />
self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))<br />
self.title.setObjectName("title")<br />
self.label_width = QtGui.QLabel(Dialog)<br />
...<br />
<br />
self.retranslateUi(Dialog)<br />
QtCore.QMetaObject.connectSlotsByName(Dialog)<br />
<br />
def retranslateUi(self, Dialog):<br />
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))<br />
self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))<br />
...<br />
<br />
As you see it has a very simple structure: a class named Ui_Dialog is created, that stores the interface elements of our widget. That class has two methods, one for setting up the widget, and one for translating its contents, that is part of the general Qt mechanism for translating interface elements. The setup method simply creates, one by one, the widgets as we defined them in Qt Designer, and sets their options as we decided earlier. Then, the whole interface gets translated, and finally, the slots get connected (we'll talk about that later).<br />
<br />
We can now create a new widget, and use this class to create its interface. We can already see our widget in action, by putting our mywidget.py file in a place where FreeCAD will find it (in the FreeCAD bin directory, or in any of the Mod subdirectories), and, in the FreeCAD python interpreter, issue:<br />
<br />
from PyQt4 import QtGui<br />
import mywidget<br />
d = QtGui.QWidget()<br />
d.ui = mywidget.Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
And our dialog will appear! Note that our python interpreter is still working, we have a non-modal dialog. So, to close it, we can (apart from clicking its close icon, of course) issue:<br />
d.hide()<br />
<br />
== Making our dialog do something ==<br />
<br />
Now that we can show and hide our dialog, we just need to add one last part: To make it do something! If you play a bit with Qt designer, you'll quickly discover a whole section called "signals and slots". Basically, it works like this: elements on your widgets (in Qt terminology, those elements are themselves widgets) can send signals. Those signals differ according to the widget type. For example, a button can send a signal when it is pressed and when it is released. Those signals can be connected to slots, which can be special functionality of other widgets (for example a dialog has a "close" slot to which you can connect the signal from a close button), or can be custom functions. The [http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html PyQt Reference Documentation] lists all the qt widgets, what they can do, what signals they can send, etc...<br />
<br />
What we will do here, is to create a new function that will create a plane based on height and width, and to connect that function to the pressed signal emitted by our "Create!" button. So, let's begin with importing our FreeCAD modules, by putting the following line at the top of the script, where we already import QtCore and QtGui:<br />
<br />
import FreeCAD, Part<br />
<br />
Then, let's add a new function to our Ui_Dialog class:<br />
<br />
def createPlane(self):<br />
try:<br />
# first we check if valid numbers have been entered<br />
w = float(self.width.text())<br />
h = float(self.height.text())<br />
except ValueError:<br />
print "Error! Width and Height values must be valid numbers!"<br />
else:<br />
# create a face from 4 points<br />
p1 = FreeCAD.Vector(0,0,0)<br />
p2 = FreeCAD.Vector(w,0,0)<br />
p3 = FreeCAD.Vector(w,h,0)<br />
p4 = FreeCAD.Vector(0,h,0)<br />
pointslist = [p1,p2,p3,p4,p1]<br />
mywire = Part.makePolygon(pointslist)<br />
myface = Part.Face(mywire)<br />
Part.show(myface)<br />
self.hide()<br />
<br />
Then, we need to inform Qt to connect the button to the function, by placing the following line just before QtCore.QMetaObject.connectSlotsByName(Dialog):<br />
<br />
QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)<br />
<br />
This, as you see, connects the pressed() signal of our create object (the "Create!" button), to a slot named createPlane, which we just defined. That's it! Now, as a final touch, we can add a little function to create the dialog, it will be easier to call. Outside the Ui_Dialog class, let's add this code:<br />
<br />
class plane():<br />
d = QtGui.QWidget()<br />
d.ui = Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
<br />
Then, from FreeCAD, we only need to do:<br />
<br />
import mywidget<br />
mywidget.plane()<br />
<br />
That's all Folks... Now you can try all kinds of things, like for example inserting your widget in the FreeCAD interface (see the [[Code snippets]] page), or making much more advanced custom tools, by using other elements on your widget.<br />
<br />
== The complete script ==<br />
<br />
This is the complete script, for reference:<br />
<br />
# -*- coding: utf-8 -*-<br />
<br />
# Form implementation generated from reading ui file 'mywidget.ui'<br />
#<br />
# Created: Mon Jun 1 19:09:10 2009<br />
# by: PyQt4 UI code generator 4.4.4<br />
#<br />
# WARNING! All changes made in this file will be lost!<br />
<br />
from PyQt4 import QtCore, QtGui<br />
import FreeCAD, Part <br />
<br />
class Ui_Dialog(object):<br />
def setupUi(self, Dialog):<br />
Dialog.setObjectName("Dialog")<br />
Dialog.resize(187, 178)<br />
self.title = QtGui.QLabel(Dialog)<br />
self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))<br />
self.title.setObjectName("title")<br />
self.label_width = QtGui.QLabel(Dialog)<br />
self.label_width.setGeometry(QtCore.QRect(10, 50, 57, 16))<br />
self.label_width.setObjectName("label_width")<br />
self.label_height = QtGui.QLabel(Dialog)<br />
self.label_height.setGeometry(QtCore.QRect(10, 90, 57, 16))<br />
self.label_height.setObjectName("label_height")<br />
self.width = QtGui.QLineEdit(Dialog)<br />
self.width.setGeometry(QtCore.QRect(60, 40, 111, 26))<br />
self.width.setObjectName("width")<br />
self.height = QtGui.QLineEdit(Dialog)<br />
self.height.setGeometry(QtCore.QRect(60, 80, 111, 26))<br />
self.height.setObjectName("height")<br />
self.create = QtGui.QPushButton(Dialog)<br />
self.create.setGeometry(QtCore.QRect(50, 140, 83, 26))<br />
self.create.setObjectName("create")<br />
<br />
self.retranslateUi(Dialog)<br />
QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)<br />
QtCore.QMetaObject.connectSlotsByName(Dialog)<br />
<br />
def retranslateUi(self, Dialog):<br />
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))<br />
self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label_width.setText(QtGui.QApplication.translate("Dialog", "Width", None, QtGui.QApplication.UnicodeUTF8))<br />
self.label_height.setText(QtGui.QApplication.translate("Dialog", "Height", None, QtGui.QApplication.UnicodeUTF8))<br />
self.create.setText(QtGui.QApplication.translate("Dialog", "Create!", None, QtGui.QApplication.UnicodeUTF8))<br />
<br />
def createPlane(self):<br />
try:<br />
# first we check if valid numbers have been entered<br />
w = float(self.width.text())<br />
h = float(self.height.text())<br />
except ValueError:<br />
print "Error! Width and Height values must be valid numbers!"<br />
else:<br />
# create a face from 4 points<br />
p1 = FreeCAD.Vector(0,0,0)<br />
p2 = FreeCAD.Vector(w,0,0)<br />
p3 = FreeCAD.Vector(w,h,0)<br />
p4 = FreeCAD.Vector(0,h,0)<br />
pointslist = [p1,p2,p3,p4,p1]<br />
mywire = Part.makePolygon(pointslist)<br />
myface = Part.Face(mywire)<br />
Part.show(myface)<br />
<br />
class plane():<br />
d = QtGui.QWidget()<br />
d.ui = Ui_Dialog()<br />
d.ui.setupUi(d)<br />
d.show()<br />
<br />
<br />
{{docnav|Line drawing function|License}}<br />
<br />
{{languages | {{cn|Dialog creation/cn}} {{de|Dialog creation/de}} {{es|Dialog creation/es}} {{fr|Dialog creation/fr}} {{it|Dialog creation/it}} {{ru|Dialog creation/ru}} {{se|Dialog creation/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Line_drawing_function&diff=16492Line drawing function2013-01-22T12:54:53Z<p>Htsubota: /* So you want more? */</p>
<hr />
<div>This page shows how advanced functionality can easily be built in Python. In this exercise, we will be building a new tool that draws a line. This tool can then be linked to a FreeCAD command, and that command can be called by any element of the interface, like a menu item or a toolbar button.<br />
<br />
==The main script==<br />
<br />
First we will write a script containing all our functionality. Then, we will save this in a file, and import it in FreeCAD, so all classes and functions we write will be availible to FreeCAD. So, launch your favorite text editor, and type the following lines:<br />
<br />
import FreeCADGui, Part<br />
from pivy.coin import *<br />
<br />
class line:<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
def __init__(self):<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
self.stack = []<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint) <br />
<br />
def getpoint(self,event_cb):<br />
event = event_cb.getEvent()<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
pos = event.getPosition()<br />
point = self.view.getPoint(pos[0],pos[1])<br />
self.stack.append(point)<br />
if len(self.stack) == 2:<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
shape = l.toShape()<br />
Part.show(shape)<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
<br />
==Detailed explanation==<br />
<br />
import Part, FreeCADGui<br />
from pivy.coin import *<br />
<br />
In Python, when you want to use functions from another module, you need to import it. In our case, we will need functions from the [[Part Module]], for creating the line, and from the Gui module (FreeCADGui), for accessing the 3D view. We also need the complete contents of the coin library, so we can use directly all coin objects like SoMouseButtonEvent, etc...<br />
<br />
class line:<br />
<br />
Here we define our main class. Why do we use a class and not a function? The reason is that we need our tool to stay "alive" while we are waiting for the user to click on the screen. A function ends when its task has been done, but an object (a class defines an object) stays alive until it is destroyed.<br />
<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
<br />
In Python, every class or function can have a description string. This is particularly useful in FreeCAD, because when you'll call that class in the interpreter, the description string will be displayed as a tooltip.<br />
<br />
def __init__(self):<br />
<br />
Python classes can always contain an __init__ function, which is executed when the class is called to create an object. So, we will put here everything we want to happen when our line tool begins.<br />
<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
<br />
In a class, you usually want to append ''self.'' before a variable name, so it will be easily accessible to all functions inside and outside that class. Here, we will use self.view to access and manipulate the active 3D view.<br />
<br />
self.stack = []<br />
<br />
Here we create an empty list that will contain the 3D points sent by the getpoint function.<br />
<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)<br />
<br />
This is the important part: Since it is actually a [http://www.coin3d.org/ coin3D] scene, the FreeCAD uses coin callback mechanism, that allows a function to be called everytime a certain scene event happens. In our case, we are creating a callback for [http://doc.coin3d.org/Coin/group__events.html SoMouseButtonEvent] events, and we bind it to the getpoint function. Now, everytime a mouse button is pressed or released, the getpoint function will be executed.<br />
<br />
Note that there is also an alternative to addEventCallbackPivy() called addEventCallback() which dispenses the use of pivy. But since pivy is a very efficient and natural way to access any part of the coin scene, it is much better to use it as much as you can!<br />
<br />
def getpoint(self,event_cb):<br />
<br />
Now we define the getpoint function, that will be executed when a mouse button is pressed in a 3D view. This function will receive an argument, that we will call event_cb. From this event callback we can access the event object, which contains several pieces of information (mode info [[Code_snippets#Observing_mouse_events_in_the_3D_viewer_via_Python|here]]).<br />
<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
<br />
The getpoint function will be called when a mouse button is pressed or released. But we want to pick a 3D point only when pressed (otherwise we would get two 3D points very close to each other). So we must check for that here.<br />
<br />
pos = event.getPosition()<br />
<br />
Here we get the screen coordinates of the mouse cursor<br />
<br />
point = self.view.getPoint(pos[0],pos[1])<br />
<br />
This function gives us a FreeCAD vector (x,y,z) containing the 3D point that lies on the focal plane, just under our mouse cursor. If you are in camera view, imagine a ray coming from the camera, passing through the mouse cursor, and hitting the focal plane. There is our 3D point. If we are in orthogonal view, the ray is parallel to the view direction.<br />
<br />
self.stack.append(point)<br />
<br />
We add our new point to the stack<br />
<br />
if len(self.stack) == 2:<br />
<br />
Do we have enough points already? if yes, then let's draw the line!<br />
<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
<br />
Here we use the function Line() from the [[Part Module]] that creates a line from two FreeCAD vectors. Everything we create and modify inside the Part module, stays in the Part module. So, until now, we created a Line Part. It is not bound to any object of our active document, so nothing appears on the screen.<br />
<br />
shape = l.toShape()<br />
<br />
The FreeCAD document can only accept shapes from the Part module. Shapes are the most generic type of the Part module. So, we must convert our line to a shape before adding it to the document.<br />
<br />
Part.show(shape)<br />
<br />
The Part module has a very handy show() function that creates a new object in the document and binds a shape to it. We could also have created a new object in the document first, then bound the shape to it manually.<br />
<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
<br />
Since we are done with our line, let's remove the callback mechanism, that consumes precious CPU cycles.<br />
<br />
==Testing & Using the script==<br />
<br />
Now, let's save our script to some place where the FreeCAD python interpreter will find it. When importing modules, the interpreter will look in the following places: the python installation paths, the FreeCAD bin directory, and all FreeCAD modules directories. So, the best solution is to create a new directory in one of the FreeCAD [[Installing_more_workbenches|Mod directories]], and to save our script in it. For example, let's make a "MyScripts" directory, and save our script as "exercise.py".<br />
<br />
Now, everything is ready, let's start FreeCAD, create a new document, and, in the python interpreter, issue:<br />
<br />
import exercise<br />
<br />
If no error message appear, that means our exercise script has been loaded. We can now check its contents with:<br />
<br />
dir(exercise)<br />
<br />
The command dir() is a built-in python command that lists the contents of a module. We can see that our line() class is there, waiting for us. Now let's test it:<br />
<br />
exercise.line()<br />
<br />
Then, click two times in the 3D view, and bingo, here is our line! To do it again, just type exercise.line() again, and again, and again... Feels great, no?<br />
<br />
==Registering the script in the FreeCAD interface==<br />
<br />
Now, for our new line tool to be really cool, it should have a button on the interface, so we don't need to type all that stuff everytime. The easiest way is to transform our new MyScripts directory into a full FreeCAD workbench. It is easy, all that is needed is to put a file called '''InitGui.py''' inside your MyScripts directory. The InitGui.py will contain the instructions to create a new workbench, and add our new tool to it. Besides that we will also need to transform a bit our exercise code, so the line() tool is recognized as an official FreeCAD command. Let's start by making an InitGui.py file, and write the following code in it:<br />
<br />
class MyWorkbench (Workbench): <br />
MenuText = "MyScripts"<br />
def Initialize(self):<br />
import exercise<br />
commandslist = ["line"]<br />
self.appendToolbar("My Scripts",commandslist)<br />
Gui.addWorkbench(MyWorkbench())<br />
<br />
By now, you should already understand the above script by yourself, I think: We create a new class that we call MyWorkbench, we give it a title (MenuText), and we define an Initialize() function that will be executed when the workbench is loaded into FreeCAD. In that function, we load in the contents of our exercise file, and append the FreeCAD commands found inside to a command list. Then, we make a toolbar called "My Scripts" and we assign our commands list to it. Currently, of course, we have only one tool, so our command list contains only one element. Then, once our workbench is ready, we add it to the main interface.<br />
<br />
But this still won't work, because a FreeCAD command must be formatted in a certain way to work. So we will need to transform a bit our line() tool. Our new exercise.py script will now look like this:<br />
<br />
import FreeCADGui, Part<br />
from pivy.coin import *<br />
class line:<br />
"this class will create a line after the user clicked 2 points on the screen"<br />
def Activated(self):<br />
self.view = FreeCADGui.ActiveDocument.ActiveView<br />
self.stack = []<br />
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint) <br />
def getpoint(self,event_cb):<br />
event = event_cb.getEvent()<br />
if event.getState() == SoMouseButtonEvent.DOWN:<br />
pos = event.getPosition()<br />
point = self.view.getPoint(pos[0],pos[1])<br />
self.stack.append(point)<br />
if len(self.stack) == 2:<br />
l = Part.Line(self.stack[0],self.stack[1])<br />
shape = l.toShape()<br />
Part.show(shape)<br />
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)<br />
def GetResources(self): <br />
return {'Pixmap' : 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'} <br />
FreeCADGui.addCommand('line', line())<br />
<br />
What we did here is transform our __init__() function into an Activated() function, because when FreeCAD commands are run, they automatically execute the Activated() function. We also added a GetResources() function, that informs FreeCAD where it can find an icon for the tool, and what will be the name and tooltip of our tool. Any jpg, png or svg image will work as an icon, it can be any size, but it is best to use a size that is close to the final aspect, like 16x16, 24x24 or 32x32.<br />
Then, we add the line() class as an official FreeCAD command with the addCommand() method.<br />
<br />
That's it, we now just need to restart FreeCAD and we'll have a nice new workbench with our brand new line tool!<br />
<br />
==So you want more?==<br />
<br />
If you liked this exercise, why not try to improve this little tool? There are many things that can be done, like for example:<br />
* Add user feedback: until now we did a very bare tool, the user might be a bit lost when using it. So we could add some feedback, telling him what to do next. For example, you could issue messages to the FreeCAD console. Have a look in the FreeCAD.Console module<br />
* Add a possibility to type the 3D points coordinates manually. Look at the python input() function, for example<br />
* Add the possibility to add more than 2 points<br />
* Add events for other things: Now we just check for Mouse button events, what if we would also do something when the mouse is moved, like displaying current coordinates?<br />
* Give a name to the created object<br />
Don't hesitate to write your questions or ideas on the [[Talk:Line_drawing_function|talk page]]!<br />
<br />
{{docnav|Code snippets|Dialog creation}}<br />
<br />
{{languages | {{cn|Line drawing function/cn}} {{es|Line drawing function/es}} {{fr|Line drawing function/fr}} {{it|Line drawing function/it}} {{ru|Line drawing function/ru}} {{se|Line drawing function/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]<br />
[[Category:Python Code]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Help_FreeCAD&diff=16427Help FreeCAD2013-01-20T08:42:24Z<p>Htsubota: /* Translate FreeCAD */</p>
<hr />
<div>If you like FreeCAD and would like to help in its development, there are many things you can do, even if you are not a programmer. Actually, there are things to do for everyone: users, power users and developers:<br />
<br />
=== Work on the documentation ===<br />
<br />
Help us to build, correct and extend this documentation. Correct mistakes, extend or correct pages that are unclear, create new pages if a topic is missing, etc. To edit the wiki, you will need a [http://sourceforge.net SourceForge account], then, you can use the same login and password on this wiki. Then, ask [https://sourceforge.net/apps/phpbb/free-cad/viewtopic.php?f=10&t=2268&start=20 on the forum] or on the irc channel for write permission (the wiki is write-protected to avoid spamming). A couple of areas that would welcome your work:<br />
<br />
* The [[List of Commands]] page list and documents all of the FreeCAD commands. Most of them have few or no information at all. The [[Std_ViewScreenShot]] page is a good example of what every other command should like.<br />
* The [[Tutorials]] section is still very poor. If you developed something cool with FreeCAD, why not write there how you did it?<br />
<br />
=== Share your FreeCAD knowledge ===<br />
<br />
The users community around FreeCAD is still small, but already includes several advanced users who do a very important job in showing to newcomers how to use the software. If you begin to feel comfortable with FreeCAD, your knowledge could be very valuable to others, and you might<br />
contribute with important assets, like:<br />
* Showing the work you do with FreeCAD on this [http://sourceforge.net/apps/phpbb/free-cad/viewtopic.php?f=8&t=1222 forum thread]. You can post screenshots, and, even better, attach the FreeCAD files so other people can examine it and understand how you did it.<br />
* Recording [http://www.youtube.com/user/FreeCADNews videos] showing how you did something interesting in FreeCAD. These videos usually do a great job in showing new features.<br />
* Write [http://freecad-tutorial.blogspot.com/ tutorials] describing or teaching something interesting. You can write tutorials on your own blog, directly on our wiki, or even on the forum.<br />
<br />
=== Translate the documentation ===<br />
<br />
Translate the documentation: Translating this wiki is easy, you just need to add a /languagecode page to create a translation. For example, to translate the [[Part_Module]] page (its url ends with index.php?title=Part_Module) to french, you would just add /fr to the url, which will create a [[Part_Module/fr]] page. <br />
<br />
=== Translate FreeCAD ===<br />
<br />
[[Localisation|Translate]] FreeCAD in your own language. All text of the FreeCAD interface can be easily translated in other languages. All we need is someone who know that other language and is willing to help! We currently have translation in english, german and french. All the translations are done online on [http://crowdin.net/project/freecad crowdin].<br />
<br />
=== Help others to know FreeCAD ===<br />
<br />
* Talk about FreeCAD to other people who might be interested<br />
* Find interesting uses for FreeCAD, and document it, for example with screenshots. FreeCAD is very young, and not many people see what they can do with it. If you are a FreeCAD fan already, you surely know some cool thing FreeCAD can do. Help us to show that to others!<br />
* Hang on the forum, and help newcomers to solve basic questions<br />
* Write tutorials, record videos, etc... showing what you do with FreeCAD<br />
* Contribute with files, drawings, etc... We still lack good example files of what can be done with FreeCAD<br />
<br />
=== Report bugs and ask for interesting features ===<br />
<br />
The place to report bugs and suggest new features is the '''[http://sourceforge.net/apps/mantisbt/free-cad FreeCAD Tracker]'''. In order to save developers time (triaging and handling hard to understand bugs can be very time consuming), and avoid frustrations because your issue was not handled the way you would like, please read the following:<br />
<br />
* Bugs and features requests are handled in the same tracker. Just mark your issue as "bug" (something that doesn't work as it should) or "feature" (something that is not there but you think it would be good to have)<br />
* Although you can submit issues anonymously, please use your sourceforge account (create one if needed), so you can be notified when someone adds notes to the issue. In many cases, the person who will handle the bug will need more information from you.<br />
* When reporting a bug, the most important point is to allow developers to reproduce it. Be sure to include the exact steps needed to make the bug happen, so another person can do the same and see the bug happen on his machine too. If the developer cannot see the bug, he cannot solve it either.<br />
* Also include information that can help developers to situate the problem, like the operating system you are running FreeCAD on, the version of FreeCAD (for example 0.11) and the revision number (for example 4955). Both those numbers are available on the Help -> about FreeCAD dialog.<br />
* If you are not sure whether what you found is a bug or not, the best way is to head to the [http://apps.sourceforge.net/phpbb/free-cad/index.php forum] and discuss it there first.<br />
* Before submitting a feature request, it might also be a good idea to discuss it with other users on the [http://apps.sourceforge.net/phpbb/free-cad/index.php forum], so you might end up with a more solid proposal, with more chances to interest a developer to implement it.<br />
* Remember that FreeCAD is developed by volunteers who use their free time to work on it. Although everyone tries his best to make the best possible application, your bug report might be treated with low priority, or canceled if you cannot give sufficient information, and your feature request might be postponed or even refused if no developer has interest in implement it or if that would request unrealistic amount of work.<br />
<br />
=== Design artwork ===<br />
<br />
See the [[Artwork]] page for guidelines about designing icons for FreeCAD.<br />
<br />
=== Program! ===<br />
<br />
Writing code for FreeCAD is not hard, and you don't need any permission, you can start right now to work on something you want, then [http://sourceforge.net/apps/mantisbt/free-cad submit a patch] or request a merge from a git branch. But to avoid some headache you should meet the following prerequisites first:<br />
<br />
* FreeCAD goes at its own pace, and has a very small team of developers. We have not as much time as we would like to dedicate to FreeCAD, and things are not planned ahead, they are done when some developer sees it fit and when he finds time to do it. So we don't maintain a list of tasks to be done. It is up to you to find something you would like to do, for example a defect you would like to correct, or a small feature you think is missing. The [http://sourceforge.net/apps/mantisbt/free-cad tracker] also contains some items that are not yet assigned to anybody.<br />
* Before you start to code for FreeCAD, you must know well how FreeCAD works. This seems obvious, but if you don't know how it is supposed to work you won't know what to do internally or how to do it.<br />
* Almost everything can be done either in python or C++. The internals work almost the same in both languages. We suggest you read through the [[Power users hub]] pages, even if you're going to code in C++, since it will give you a good overview of the internals.<br />
* If you are going to work in C++, make sure you can compile FreeCAD without problems first.<br />
* Present yourself to other developers. FreeCAD is before anything a social project, we discuss a lot of things on the [http://sourceforge.net/apps/phpbb/free-cad forum] before implementing it, and it's always best to discuss your ideas and tell people what you are planning to do before actually doing it. We also have an [irc://chat.freenode.net/freecad IRC channel], but the forum is the one and only place where you can meet all the developers.<br />
<br />
<br />
{{languages | {{es|Help_FreeCAD/es}} {{fr|Help_FreeCAD/fr}} {{it|Help_FreeCAD/it}} {{se|Help_FreeCAD/se}} }}</div>Htsubotahttps://wiki.freecad.org/index.php?title=TopoShape_API&diff=16283TopoShape API2013-01-15T12:50:09Z<p>Htsubota: </p>
<hr />
<div>The TopoShape is the mother object of the Part Module. All shape types (wire, face, solid, etc...) of the Part module are TopoShapes, and share the following attributes and methods. Example:<br />
<br />
import Part<br />
sh = Part.makeBox(10,10,10)<br />
print sh.Faces<br />
for f in sh.Faces:<br />
print f.Edges<br />
<br />
{{APIProperty|Area|The total area of the faces of the shape.}}<br />
{{APIProperty|CompSolids|Lists the subsequent shapes in this shape.}}<br />
{{APIProperty|Compounds|Lists the coumpounds in this shape.}}<br />
{{APIProperty|Edges|Lists the Edges in this shape.}}<br />
{{APIProperty|Faces|Lists the faces in this shape.}}<br />
{{APIProperty|Length|Total length of the edges of the shape.}}<br />
{{APIProperty|Orientation|the orientation of the shape.}}<br />
{{APIProperty|ShapeType|The type of the shape.}}<br />
{{APIProperty|Shells|Lists the subsequent shapes in this shape.}}<br />
{{APIProperty|Solids|List of subsequent shapes in this shape.}}<br />
{{APIProperty|Vertexes|List of vertexes in this shape.}}<br />
{{APIProperty|Volume|Total volume of the solids of the shape.}}<br />
{{APIProperty|Wires|List of wires in this shape.}}<br />
{{APIProperty|BoundBox|The BoundBox of the object}}<br />
{{APIProperty|Matrix|The current transformation of the object as matrix}}<br />
{{APIProperty|Placement|The current transformation of the object as placement}}<br />
{{APIFunction|getAllDerivedFrom| |Returns all descentences of this object type|a list}}<br />
{{APIFunction|isDerivedFrom|string|Returns true if given type is a father|boolean}}<br />
{{APIFunction|approximate| |Approximates a B-Spline-curve from this wire|a BSplineCurve object}}<br />
{{APIFunction|makeHomogenousWires|wire|Makes this and the given wire homogenous to have the same number of edges| a wire}}<br />
{{APIFunction|makeOffset|float|Offsets the shape by a given ammount|a TopoShape}}<br />
{{APIProperty|CenterOfMass|The center of mass of the current system. If the gravitational field is uniform, it is the center of gravity. The coordinates returned for the center of mass are expressed in the absolute Cartesian coordinate system.}}<br />
{{APIFunction|check| |Checks the shape and report errors in the shape structure. This is a more detailed check as done in isValid().| }}<br />
{{APIFunction|common|TopoShape|Intersection of this and a given topo shape.|a TopoShape}}<br />
{{APIFunction|complement| |Computes the complement of the orientation of this shape, i.e. reverses the interior/exterior status of boundaries of this shape.|a TopoShape}}<br />
{{APIFunction|copy| |Creates a copy of this shape|a TopoShape}}<br />
{{APIFunction|cut|TopoShape|Difference of this and a given topo shape.|a TopoShape}}<br />
{{APIFunction|exportBrep| string |Exports the content of this shape to an BREP file. BREP is a CasCade native format.| }}<br />
{{APIFunction|exportIges| string |Exports the content of this shape to an IGES file.| }}<br />
{{APIFunction|exportStep| string |Exports the content of this shape to an STEP file.| }}<br />
{{APIFunction|exportStl| string |Exports the content of this shape to an STL mesh file.| }}<br />
{{APIFunction|extrude|Vector|Extrudes the shape along a direction.|a TopoShape}}<br />
{{APIFunction|fuse|TopoShape|Union of this and a given topo shape.|a TopoShape}}<br />
{{APIFunction|hashCode| |This value is computed from the value of the underlying shape reference and the location. Orientation is not taken into account.|a string}}<br />
{{APIFunction|isClosed| |Checks if the shape is closed.|a boolean}}<br />
{{APIFunction|isEqual|TopoShape|Checks if both shapes are equal.|a boolean}}<br />
{{APIFunction|isInside|Vector,float,Boolean|Checks if a point is inside a solid with a certain tolerance. If the 3rd parameter is True a point on a face is considered as inside|a boolean}}<br />
{{APIFunction|isNull| |Checks if the shape is null.|a boolean}}<br />
{{APIFunction|isSame|TopoShape|Checks if both shapes share the same geometry.|a boolean}}<br />
{{APIFunction|isValid| |Checks if the shape is valid, i.e. neither null, nor empty nor corrupted.|a boolean}}<br />
{{APIFunction|makeFillet| |Makes fillet.| }}<br />
{{APIFunction|makePipe|wire|Makes a pipe by sweeping along a wire.|a TopoShape}}<br />
{{APIFunction|makePipeShell|wire|Makes a loft defined by profiles along a wire.|a TopoShape}}<br />
{{APIFunction|makeShapeFromMesh|mesh|Makes a compound shape out of mesh data. Note: This should be used for rather small meshes only.|a TopoShape}}<br />
{{APIFunction|makeThickness|list,float,float|A hollowed solid is built from an initial solid and a set of faces on this solid, which are to be removed. The remaining faces of the solid become the walls of the hollowed solid, their thickness defined at the time of construction. The arguments to be passed are a list of faces to be skipped, the thickness of the walls and a tolerance value.|a TopoShape}}<br />
{{APIFunction|nullify| |Destroys the reference to the underlying shape stored in this shape. As a result, this shape becomes null.|}}<br />
{{APIFunction|project|TopoShape|Project a shape on this shape|a TopoShape}}<br />
{{APIFunction|read|string|Reads in an IGES, STEP or BREP file.|a TopoShape}}<br />
{{APIFunction|reverse| |Reverses the orientation of this shape.| }}<br />
{{APIFunction|revolve|Vector, Vector, float|Revolves the shape around a Axis to a given degree. ex: Part.revolve(Vector(0,0,0),Vector(0,0,1),360) revolves the shape around the Z Axis 360 degree.|a TopoShape}}<br />
{{APIFunction|rotate|Vector, Vector, float|Applies the rotation (degree) to the current location of this shape. ex: Shp.rotate(Vector(0,0,0),Vector(0,0,1),180) rotate the shape around the Z Axis 180 degrees.|a TopoShape}}<br />
{{APIFunction|scale| |Applies scaling with point and factor to this shape.|a TopoShape}}<br />
{{APIFunction|section|TopoShape|Section of this with a given topo shape.|a TopoShape}}<br />
{{APIFunction|sewShape| |Sews the shape if there is a gap.| }}<br />
{{APIFunction|tessellate|float|Tessellate the the shape and return a list of vertices and face indices. The given float is the tolerance.|a list}}<br />
{{APIFunction|toNurbs| |Conversion of the complete geometry of a shape into NURBS geometry. For example, all curves supporting edges of the basis shape are converted into BSpline curves, and all surfaces supporting its faces are converted into BSpline surfaces.|a NURBS curve}}<br />
{{APIFunction|transformGeometry|matrix|Applies geometric transformation on a copy of the shape. The transformation to be applied is defined as a 4x4 matrix. The underlying geometry of the following shapes may change to a curve which supports an edge of the shape, or a surface which supports a face of the shape. For example, a circle may be transformed into an ellipse when applying an affinity transformation. It may also happen that the circle then is represented as a b-spline curve. The transformation is applied to all the curves which support edges of the shape, and all the surfaces which support faces of the shape. Note: If you want to transform a shape without changing the underlying geometry then use the methods translate or rotate.|a TopoShape}}<br />
{{APIFunction|transformShape|matrix|Applies transformation on a shape without changing the underlying geometry.| }}<br />
{{APIFunction|translate|Vector|Applies the translation to the current location of this shape.| }}<br />
{{APIFunction|writeInventor| |Writes the mesh in OpenInventor format to a string.|a string}}<br />
<br />
{{languages | {{es|TopoShape_API/es}} {{fr|TopoShape_API/fr}} }}<br />
<br />
[[Category:API]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Mesh_API&diff=16177Mesh API2013-01-14T06:55:42Z<p>Htsubota: </p>
<hr />
<div>The Mesh objects can be manipulated by adding new facets, deleting facets, importing from an STL file, transforming the mesh and much more. For a complete overview of what can be done see also the [[Mesh Module]] documentation. A mesh object cannot be added to an existing document directly. Therefore the document must create an object with a property class that supports meshes. Example:<br />
<br />
m = Mesh.Mesh()<br />
... # Manipulate the mesh<br />
d = FreeCAD.activeDocument() # Get a reference to the actie document<br />
f = d.addObject("Mesh::Feature", "Mesh") # Create a mesh feature<br />
f.Mesh = m # Assign the mesh object to the internal property<br />
d.recompute()<br />
<br />
{{APIFunction|addFacet|Facet|Adds a facet to the mesh| }}<br />
{{APIFunction|addFacets|list|Adds a list of facets to the mesh| }}<br />
{{APIFunction|addMesh|Mesh|Combines this mesh with another mesh.| }}<br />
{{APIFunction|clear| |Clears the mesh| }}<br />
{{APIFunction|coarsen| |Coarsens the mesh| }}<br />
{{APIFunction|collapseEdge|Edge|Removes an edge and both facets that share this edge| }}<br />
{{APIFunction|collapseFacet|Facet|Removes a facet| }}<br />
{{APIFunction|collapseFacets|list|Removes a list of facets| }}<br />
{{APIFunction|copy| |Creates a copy of this mesh|a Mesh object}}<br />
{{APIFunction|countComponents| |Get the number of topological independent areas|an integer}}<br />
{{APIFunction|countNonUniformOrientedFacets| |Get the number of wrong oriented facets|an integer}}<br />
{{APIFunction|countSegments| |Get the number of segments which may also be 0|an integer}}<br />
{{APIFunction|crossSections| |Get cross-sections of the mesh through several planes| }}<br />
{{APIFunction|difference|Mesh|Difference of this and the given mesh object.| }}<br />
{{APIFunction|fillupHoles| |Fillup holes| }}<br />
{{APIFunction|fixDeformations| |Repair deformed facets| }}<br />
{{APIFunction|fixDegenerations| |Remove degenerated facets| }}<br />
{{APIFunction|fixIndices| |Repair any invalid indices| }}<br />
{{APIFunction|fixSelfIntersections| |Repair self-intersections| }}<br />
{{APIFunction|flipNormals| |Flip the mesh normals| }}<br />
{{APIFunction|foraminate| |Get a list of facet indices and intersection points| }}<br />
{{APIFunction|getPlanes| |Get all planes of the mesh as segment. In the worst case each triangle can be regarded as single plane if none of its neighbors is coplanar.| }}<br />
{{APIFunction|getSegment|integer|Get a list of facet indices that describes a segment| }}<br />
{{APIFunction|getSeparateComponents| |Returns a list containing the different components (separated areas) of the mesh as separate meshes|a list}}<br />
{{APIFunction|harmonizeNormals| |Adjust wrong oriented facets| }}<br />
{{APIFunction|hasNonManifolds| |Check if the mesh has non-manifolds|a boolean}}<br />
{{APIFunction|hasNonUniformOrientedFacets| |Checks if the mesh has facets with inconsistent orientation| }}<br />
{{APIFunction|hasSelfIntersections| |Check if the mesh intersects itself| }}<br />
{{APIFunction|inner| |Get the part inside of the intersection| }}<br />
{{APIFunction|insertVertex|Vertex|Inserts a vertex into a facet| }}<br />
{{APIFunction|intersect|Mesh|Intersection of this and the given mesh object.| }}<br />
{{APIFunction|isSolid| |Check if the mesh is a solid| }}<br />
{{APIFunction|meshFromSegment| |Create a mesh from segment| }}<br />
{{APIFunction|nearestFacetOnRay|tuple, tuple|Get the index and intersection point of the nearest facet to a ray. The first parameter is a tuple of three floats the base point of the ray, the second parameter is ut uple of three floats for the direction. The result is a dictionary with an index and the intersection point or an empty dictionary if there is no intersection.|a dictionary}}<br />
{{APIFunction|offset|float|Move the point along their normals| }}<br />
{{APIFunction|offsetSpecial|float|Move the point along their normals| }}<br />
{{APIFunction|optimizeEdges| |Optimize the edges to get nicer facets| }}<br />
{{APIFunction|optimizeTopology| |Optimize the edges to get nicer facets| }}<br />
{{APIFunction|outer| |Get the part outside the intersection| }}<br />
{{APIFunction|printInfo| |Get detailed information about the mesh| }}<br />
{{APIFunction|read| |Read in a mesh object from file.| }}<br />
{{APIFunction|refine| |Refine the mesh| }}<br />
{{APIFunction|removeComponents|integer|Remove components with less or equal to number of given facets| }}<br />
{{APIFunction|removeDuplicatedFacets| |Remove duplicated facets| }}<br />
{{APIFunction|removeDuplicatedPoints| |Remove duplicated points| }}<br />
{{APIFunction|removeFacets|list|Remove a list of facet indices from the mesh| }}<br />
{{APIFunction|removeFoldsOnSurface| |Remove folds on surfaces| }}<br />
{{APIFunction|removeNonManifolds| |Remove non-manifolds| }}<br />
{{APIFunction|rotate| |Apply a rotation to the mesh| }}<br />
{{APIFunction|setPoint|int, Vector|Sets the point at index.| }}<br />
{{APIFunction|smooth| |Smooth the mesh| }}<br />
{{APIFunction|snapVertex| |Insert a new facet at the border| }}<br />
{{APIFunction|splitEdge| |Split edge| }}<br />
{{APIFunction|splitEdges| |Split all edges| }}<br />
{{APIFunction|splitFacet| |Split facet| }}<br />
{{APIFunction|swapEdge| |Swap the common edge with the neighbor| }}<br />
{{APIFunction|transform| |Apply a transformation to the mesh| }}<br />
{{APIFunction|transformToEigen| |Transform the mesh to its eigenbase| }}<br />
{{APIFunction|translate|Vector|Apply a translation to the mesh| }}<br />
{{APIFunction|unite|Mesh|Union of this and the given mesh object.| }}<br />
{{APIFunction|write|string|Write the mesh object into file.| }}<br />
{{APIFunction|writeInventor| |Write the mesh in OpenInventor format to a string.|a string}}<br />
{{APIProperty|Area|the area of the mesh object.}}<br />
{{APIProperty|CountFacets|the number of facets of the mesh object.}}<br />
{{APIProperty|CountPoints|the number of vertices of the mesh object.}}<br />
{{APIProperty|Facets|A collection of facets; With this attribute it is possible to get access to the facets of the mesh: for p in mesh.Facets: print p}}<br />
{{APIProperty|Points|A collection of the mesh points; With this attribute it is possible to get access to the points of the mesh: for p in mesh.Points: print p.x, p.y, p.z}}<br />
{{APIProperty|Topology|the points and face indices as tuple.}}<br />
{{APIProperty|Volume|the volume of the mesh object.}}<br />
{{APIProperty|BoundBox|the BoundBox of the object}}<br />
{{APIProperty|Matrix|the current transformation of the object as matrix}}<br />
{{APIProperty|Placement|the current transformation of the object as placement}}<br />
<br />
{{languages | {{es|Mesh_API/es}} }}<br />
<br />
[[Category:API]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Console_API&diff=16087Console API2013-01-11T10:21:48Z<p>Htsubota: Undo revision 16054 by Htsubota (Talk)</p>
<hr />
<div>This module is contained inside the FreeCAD module and contains methods to send text to FreeCAD's output console and status bar. The messages will have different color if they are message, warning or error. Example:<br />
<br />
import FreeCAD<br />
FreeCAD.PrintMessage("Hello World!\n")<br />
<br />
{{APIFunction|GetStatus|"Log" or "Msg" or "Wrn" or "Err"|Get the status for either Log, Msg, Wrn or Error for an observer|a status string.}}<br />
{{APIFunction|PrintError|string|Prints an error message to the output|nothing}}<br />
{{APIFunction|PrintLog|string|Prints a log message to the output|nothing}}<br />
{{APIFunction|PrintMessage|string|Prints a message to the output|nothing}}<br />
{{APIFunction|PrintWarning|string|Prints a warning to the output|nothing}}<br />
{{APIFunction|SetStatus|string|Set the stats for either Log, Msg, Wrn or Error for an observer| }}<br />
<br />
{{languages | {{es|Console_API/es}} {{it|Console_API/it}} }}<br />
<br />
[[Category:API]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD_API&diff=16056FreeCAD API2013-01-10T12:47:13Z<p>Htsubota: </p>
<hr />
<div>This is the principal (root) module of FreeCAD. It can also be called by "App" from the FreeCAD interpreter. It contains everything that is needed to manipulate documents and their contents (objects).<br />
<br />
Example:<br />
import FreeCAD<br />
print FreeCAD.listDocuments()<br />
mydoc = FreeCAD.activeDocument()<br />
<br />
<br />
{{APIFunction|ConfigDump| |Prints a dictionary containing all the FreeCAD configuration environment.| }}<br />
<br />
{{APIFunction|ConfigGet|[string]|Returns the value of the given key. If no key is given, the complete configuration is returned|A string.}}<br />
<br />
{{APIFunction|ConfigSet|string, string|Set the given key (first string) to the given value (second string).| }}<br />
<br />
{{APIFunction|Version| |Prints the FreeCAD version.| }}<br />
<br />
{{APIFunction|activeDocument| |Return the active document or None if there is no active document.|A FreeCAD Document.}}<br />
<br />
{{APIFunction|addExportType|string, string|Adds a new export file type to FreeCAD. The first string must be formatted like this example: "Word Document (*.doc)". The second string is the name of a python script/module containing an export() function.| }}<br />
<br />
{{APIFunction|addImportType|string, string|Adds a new import file type to FreeCAD, works the same way as addExportType, the handling python module must contain an open() and/or an import() function.| }}<br />
<br />
{{APIFunction|closeDocument|Document name|Closes the given document| }}<br />
<br />
{{APIFunction|getDocument|Document name|Returns a document or raise an exception if there is no document with the given name.| }}<br />
<br />
{{APIFunction|getExportType|string|Returns the name of the module that can export the specified filetype.| A string.}}<br />
<br />
{{APIFunction|getImportType|string|Returns the name of the module that can import the specified filetype.|A string.}}<br />
<br />
{{APIFunction|listDocuments| |Returns a list of names of all documents.|A list of names.}}<br />
<br />
{{APIFunction|newDocument|[string]|Creates and returns a new document with a given name. The document name must be unique, which is checked automatically. If no name is supplied, the document will be named "Untitled".|The newly created document.}}<br />
<br />
{{APIFunction|open|string|See openDocument| }}<br />
<br />
{{APIFunction|openDocument|filepath|Creates and returns a document and load a project file into the document. The string argument must point to an existing file. If the file doesn't exist or the file cannot be loaded an I/O exception is thrown. In this case the created document is kept, but will be empty.|The opened FreeCAD Document.}}<br />
<br />
{{APIFunction|setActiveDocument|Document name|Set the active document by its name.| }}<br />
<br />
{{languages | {{es|FreeCAD_API/es}} }}<br />
<br />
[[Category:API]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD_API&diff=16055FreeCAD API2013-01-10T12:44:14Z<p>Htsubota: </p>
<hr />
<div>This is the principal (root) module of FreeCAD. It can also be called by "App" from the FreeCAD interpreter. It contains everything that is needed to manipulate documents and their contents (objects).<br />
<br />
Example:<br />
import FreeCAD<br />
print FreeCAD.listDocuments()<br />
mydoc = FreeCAD.activeDocument()<br />
<br />
<br />
{{APIFunction|ConfigDump| |Prints a dictionnnary containing all the FreeCAD configuration environment.| }}<br />
<br />
{{APIFunction|ConfigGet|[string]|Returns the value of the given key. If no key is given, the complete configuration is returned|A string.}}<br />
<br />
{{APIFunction|ConfigSet|string, string|Set the given key (first string) to the given value (second string).| }}<br />
<br />
{{APIFunction|Version| |Prints the FreeCAD version.| }}<br />
<br />
{{APIFunction|activeDocument| |Return the active document or None if there is no active document.|A FreeCAD Document.}}<br />
<br />
{{APIFunction|addExportType|string, string|Adds a new export file type to FreeCAD. The first string must be formatted like this example: "Word Document (*.doc)". The second string is the name of a python script/module containing an export() function.| }}<br />
<br />
{{APIFunction|addImportType|string, string|Adds a new import file type to FreeCAD, works the same way as addExportType, the handling python module must contain an open() and/or an import() function.| }}<br />
<br />
{{APIFunction|closeDocument|Document name|Closes the given document| }}<br />
<br />
{{APIFunction|getDocument|Document name|Returns a document or raise an exception if there is no document with the given name.| }}<br />
<br />
{{APIFunction|getExportType|string|Returns the name of the module that can export the specified filetype.| A string.}}<br />
<br />
{{APIFunction|getImportType|string|Returns the name of the module that can import the specified filetype.|A string.}}<br />
<br />
{{APIFunction|listDocuments| |Returns a list of names of all documents.|A list of names.}}<br />
<br />
{{APIFunction|newDocument|[string]|Creates and returns a new document with a given name. The document name must be unique, which is checked automatically. If no name is supplied, the document will be named "Untitled".|The newly created document.}}<br />
<br />
{{APIFunction|open|string|See openDocument| }}<br />
<br />
{{APIFunction|openDocument|filepath|Creates and returns a document and load a project file into the document. The string argument must point to an existing file. If the file doesn't exist or the file cannot be loaded an I/O exception is thrown. In this case the created document is kept, but will be empty.|The opened FreeCAD Document.}}<br />
<br />
{{APIFunction|setActiveDocument|Document name|Set the active document by its name.| }}<br />
<br />
{{languages | {{es|FreeCAD_API/es}} }}<br />
<br />
[[Category:API]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Console_API&diff=16054Console API2013-01-10T12:36:51Z<p>Htsubota: </p>
<hr />
<div>このモジュールはFreeCADモジュール内部に含まれ、FreeCADの出力用コンソールとステータスバーにテキストを送信するためのメソッドが含まれています。メッセージ、警告、エラーの場合にはメッセージ文字列が異なる色になります。サンプル:<br />
<br />
import FreeCAD<br />
FreeCAD.PrintMessage("Hello World!\n")<br />
<br />
{{APIFunction/jp|GetStatus|"Log" または "Msg" または "Wrn" または "Err"|Log、Msg、Wrn、Wrnのいずれかのステータスを監視用に取得します。|ステータス文字列}}<br />
{{APIFunction/jp|PrintError|string|出力にエラーメッセージをプリントします。|なし}}<br />
{{APIFunction/jp|PrintLog|string|出力にログメッセージをプリントします。|なし}}<br />
{{APIFunction/jp|PrintMessage|string|出力にメッセージをプリントします。|なし}}<br />
{{APIFunction/jp|PrintWarning|string|出力に警告をプリントします。|なし}}<br />
{{APIFunction/jp|SetStatus|string|Log、Msg、Wrn、Wrnのいずれかのステータスを監視用に設定します。| }}<br />
<br />
{{languages/jp | {{en|Console_API}} {{es|Console_API/es}} {{it|Console_API/it}} }}<br />
<br />
[[Category:API/jp]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Scenegraph&diff=15958Scenegraph2013-01-06T12:04:18Z<p>Htsubota: </p>
<hr />
<div>FreeCAD is basically a collage of different powerful libraries, the most important being [http://en.wikipedia.org/wiki/Open_CASCADE openCascade], for managing and constructing geometry, [http://en.wikipedia.org/wiki/Coin3D Coin3d] to display that geometry, and [http://en.wikipedia.org/wiki/Qt_(toolkit) Qt] to put all this in a nice Graphical User Interface.<br />
<br />
The geometry that appears in the 3D views of FreeCAD are rendered by the Coin3D library. Coin3D is an implementation of the [http://en.wikipedia.org/wiki/Open_Inventor OpenInventor] standard. The openCascade software also provides the same functionality, but it was decided, at the very beginnings of FreeCAD, not to use the built-in openCascade viewer and rather switch to the more performant coin3D software. A good way to learn about that library is the book [http://www-evasion.imag.fr/Membres/Francois.Faure/doc/inventorMentor/sgi_html/ Open Inventor Mentor].<br />
<br />
[http://en.wikipedia.org/wiki/Open_Inventor OpenInventor] is actually a 3D scene description language. The scene described in openInventor is then rendered in OpenGL on your screen. Coin3D takes care of doing this, so the programmer doesn't need to deal with complex openGL calls, he just has to provide it with valid OpenInventor code. The big advantage is that openInventor is a very well-known and well documented standard.<br />
<br />
One of the big jobs FreeCAD does for you is basically to translate openCascade geometry information into openInventor language.<br />
<br />
OpenInventor describes a 3D scene in the form of a [http://en.wikipedia.org/wiki/Scene_graph scenegraph], like the one below:<br />
<br />
[[Image:Scenegraph.gif]]<br />
image from [http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html Inventor mentor]<br />
<br />
An openInventor scenegraph describes everything that makes part of a 3D scene, such as geometry, colors, materials, lights, etc, and organizes all that data in a convenient and clear structure. Everything can be grouped into sub-structures, allowing you to organize your scene contents pretty much the way you like. Here is an example of an openInventor file:<br />
<br />
#Inventor V2.0 ascii<br />
<br />
Separator { <br />
RotationXYZ { <br />
axis Z<br />
angle 0<br />
}<br />
Transform {<br />
translation 0 0 0.5<br />
}<br />
Separator { <br />
Material {<br />
diffuseColor 0.05 0.05 0.05<br />
}<br />
Transform {<br />
rotation 1 0 0 1.5708<br />
scaleFactor 0.2 0.5 0.2<br />
}<br />
Cylinder {<br />
}<br />
}<br />
}<br />
<br />
As you can see, the structure is very simple. You use separators to organize your data into blocks, a bit like you would organize your files into folders. Each statement affects what comes next, for example the first two items of our root separator are a rotation and a translation, both will affect the next item, which is a separator. In that separator, a material is defined, and another transformation. Our cylinder will therefore be affected by both transformations, the one who was applied directly to it and the one that was applied to its parent separator.<br />
<br />
We also have many other types of elements to organize our scene, such as groups, switches or annotations. We can define very complex materials for our objects, with color, textures, shading modes and transparency. We can also define lights, cameras, and even movement. It is even possible to embed pieces of scripting in openInventor files, to define more complex behaviours.<br />
<br />
If you are interested in learning more about openInventor, head directly to its most famous reference, the [http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html Inventor mentor].<br />
<br />
In FreeCAD, normally, we don't need to interact directly with the openInventor scenegraph. Every object in a FreeCAD document, being a mesh, a part shape or anything else, gets automatically converted to openInventor code and inserted in the main scenegraph that you see in a 3D view. That scenegraph gets updated continuously when you do modifications, add or remove objects to the document. In fact, every object (in App space) has a view provider (a corresponding object in Gui space), responsible for issuing openInventor code.<br />
<br />
But there are many advantages to be able to access the scenegraph directly. For example, we can temporarily change the appearence of an object, or we can add objects to the scene that have no real existence in the FreeCAD document, such as construction geometry, helpers, graphical hints or tools such as manipulators or on-screen information.<br />
<br />
FreeCAD itself features several tools to see or modify openInventor code. For example, the following python code will show the openInventor representation of a selected object:<br />
<br />
obj = FreeCAD.ActiveDocument.ActiveObject<br />
viewprovider = obj.ViewObject<br />
print viewprovider.toString()<br />
<br />
But we also have a python module that allows complete access to anything managed by Coin3D, such as our FreeCAD scenegraph. So, read on to [[Pivy]].<br />
<br />
{{docnav|Mesh to Part|Pivy}}<br />
<br />
{{languages | {{es|Scenegraph/es}} {{fr|Scenegraph/fr}} {{it|Scenegraph/it}} {{ru|Scenegraph/ru}} {{se|Scenegraph/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD_Scripting_Basics&diff=15674FreeCAD Scripting Basics2013-01-02T09:39:28Z<p>Htsubota: /* The App and Gui objects */</p>
<hr />
<div>== Python scripting in FreeCAD ==<br />
<br />
FreeCAD is built from scratch to be totally controlled by Python scripts. Almost all parts of FreeCAD, such as the interface, the scene contents, and even the representation of this content in the 3D views, are accessible from the built-in Python interpreter or from your own scripts. As a result, FreeCAD is probably one of the most deeply customizable engineering applications available today.<br />
<br />
In its current state however, FreeCAD has very few 'native' commands to interact with your 3D objects, mainly because it is still in the early stages of development, but also because the philosophy behind it is more to provide a platform for CAD development than a specific use application. But the ease of Python scripting inside FreeCAD is a quick way to see new functionality being developed by 'power users', typically users who know a bit of Python programming. Python is one of the most popular interpreted languages, and because it is generally regarded as easy to learn, you too can soon be making your own FreeCAD 'power user' scripts.<br />
<br />
If you are not familiar with Python, we recommend you search for tutorials on the internet and have a quick look at its structure. Python is a very easy language to learn, especially because it can be run inside an interpreter, where simple commands, right up to complete programs, can be executed on the fly without the need to compile anything. FreeCAD has a built-in Python interpreter. If you don't see the window labeled 'Python console' as shown below, you can activate it under the View -> Views -> Python console to bring-up the interpreter.<br />
<br />
===The interpreter===<br />
<br />
From the interpreter, you can access all your system-installed Python modules, as well as the built-in FreeCAD modules, and all additional FreeCAD modules you installed later. The screenshot below shows the Python interpreter:<br />
<br />
[[Image:screenshot_pythoninterpreter.jpg|The FreeCAD Python interpreter]]<br />
<br />
From the interpreter, you can execute Python code and browse through the available classes and functions. FreeCAD provides a very handy class browser for exploration of your new FreeCAD world: When you type the name of a known class followed by a period (meaning you want to add something from that class), a class browser window opens, where you can navigate between available subclasses and methods. When you select something, an associated help text (if it exists) is displayed:<br />
<br />
[[Image:screenshot_classbrowser.jpg|The FreeCAD class browser]]<br />
<br />
So, start here by typing '''App.''' or '''Gui.''' and see what happens. Another more generic Python way of exploring the content of modules and classes is to use the 'print dir()' command. For example, typing '''print dir()''' will list all modules currently loaded in FreeCAD. '''print dir(App)''' will show you everything inside the App module, etc.<br />
<br />
Another useful feature of the interpreter is the possibility to go back through the command history and retrieve a line of code that you already typed earlier. To navigate through the command history, just use CTRL+UP or CTRL+DOWN.<br />
<br />
By right-clicking in the interpreter window, you also have several other options, such as copy the entire history (useful when you want to experiment with things before making a full script of them), or insert a filename with complete path.<br />
<br />
===Python Help===<br />
<br />
In the FreeCAD Help menu, you'll find an entry labeled 'Python help', which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but usually Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work.<br />
<br />
==Built-in modules==<br />
<br />
Since FreeCAD is designed to be run without a Graphical User Interface (GUI), almost all its functionality is separated into two groups: Core functionality, named 'App', and GUI functionality, named 'Gui'. So, our two main FreeCAD built-in modules are called App and Gui. These two modules can also be accessed from scripts outside of the interpreter, by the names 'FreeCAD' and 'FreeCADGui' respectively.<br />
<br />
* In the '''App module''', you'll find everything related to the application itself, like methods for opening or closing files, and to the documents, like setting the active document or listing their contents.<br />
<br />
* In the '''Gui module''', you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interestingly, the graphical representation of all FreeCAD content. <br />
<br />
Listing all the content of those modules is a bit counter-productive task, since they grow quite fast with FreeCAD development. But the two browsing tools provided (the class browser and the Python help) should give you, at any moment, complete and up-to-date documentation of these modules.<br />
<br />
===The App and Gui objects===<br />
<br />
As we said, in FreeCAD, everything is separated between core and representation. This includes the 3D objects too. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it, (like width, length, height) that are stored in an App object, and representation properties, (like faces color, drawing mode) that are stored in a corresponding Gui object.<br />
<br />
This way of doing things allows a very wide range of uses, like having algorithms work only on the definition part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis.<br />
<br />
For every App object in your document, there exists a corresponding Gui object. Infact the document itself has both App and a Gui objects. This, of course, is only valid when you run FreeCAD with its full interface. In the command-line version no GUI exists, so only App objects are availible. Note that the Gui part of objects is re-generated every time an App object is marked as 'to be recomputed' (for example when one of its parameters changes), so changes you might have made directly to the Gui object may be lost.<br />
<br />
To access the App part of something, you type:<br />
myObject = App.ActiveDocument.getObject("ObjectName")<br />
where "ObjectName" is the name of your object. You can also type:<br />
myObject = App.ActiveDocument.ObjectName<br />
<br />
To access the Gui part of the same object, you type:<br />
myViewObject = Gui.ActiveDocument.getObject("ObjectName")<br />
where "ObjectName" is the name of your object. You can also type:<br />
myViewObject = App.ActiveDocument.ObjectName.ViewObject<br />
<br />
If we have no GUI (for example we are in command-line mode), the last line will return 'None'.<br />
<br />
=== The Document objects ===<br />
<br />
In FreeCAD all your work resides inside Documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or point of view. These views are all part of your document's Gui object.<br />
<br />
To access the App part the currently open (active) document, you type:<br />
myDocument = App.ActiveDocument<br />
To create a new document, type:<br />
myDocument = App.newDocument("Document Name")<br />
To access the Gui part the currently open (active) document, you type:<br />
myGuiDocument = Gui.ActiveDocument<br />
To access the current view, you type:<br />
myView = Gui.ActiveDocument.ActiveView<br />
<br />
== Using additional modules ==<br />
<br />
The FreeCAD and FreeCADGui modules are solely responsibles for creating and managing objects in the FreeCAD document. They don't actually do anything such as creating or modifying geometry. That is because that geometry can be of several types, and so it is managed by additional modules, each responsible for managing a certain geometry type. For example, the [[Part Module]] uses the OpenCascade kernel, and therefore is able to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation B-rep] type geometry, which is what OpenCascade is built for. The [[Mesh Module]] is able to build and modify mesh objects. That way, FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types could be added easily in the future.<br />
<br />
=== Creating objects ===<br />
<br />
Each module has its own way to treat its geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:<br />
<br />
FreeCAD.ActiveDocument.supportedTypes()<br />
<br />
will list you all the possible objects you can create. For example, let's create a mesh (treated by the mesh module) and a part (treated by the part module):<br />
<br />
myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature","myMeshName")<br />
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature","myPartName")<br />
<br />
The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one, myMesh has a "Mesh" property and "Part" has a "Shape" property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:<br />
<br />
import Part<br />
cube = Part.makeBox(2,2,2)<br />
myPart.Shape = cube<br />
<br />
You could try storing the cube inside the Mesh property of the myMesh object, it will return an error complaining of the wrong type. That is because those properties are made to store only a certain type. In the myMesh's Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:<br />
<br />
import Part<br />
cube = Part.makeBox(2,2,2)<br />
Part.show(cube)<br />
<br />
=== Modifying objects ===<br />
<br />
Modifying an object is done the same way:<br />
<br />
import Part<br />
cube = Part.makeBox(2,2,2)<br />
myPart.Shape = cube<br />
<br />
Now let's change the shape by a bigger one:<br />
<br />
biggercube = Part.makeBox(5,5,5)<br />
myPart.Shape = biggercube<br />
<br />
=== Querying objects ===<br />
<br />
You can always look at the type of an object like this:<br />
<br />
myObj = FreeCAD.ActiveDocument.getObject("myObjectName")<br />
print myObj.Type<br />
<br />
or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):<br />
<br />
print myObj.isDerivedFrom("Part::Feature")<br />
<br />
Now you can really start playing with FreeCAD! To look at what you can do with the [[Part Module]], read the [[Topological data scripting|Part scripting]] page, or the [[Mesh Scripting]] page for working with the [[Mesh Module]]. Note that, although the Part and Mesh modules are the most complete and widely used, other modules such as the [[Draft Module]] also have [[Draft API|scripting]] APIs that can be useful to you. For a complete list of each modules and their available tools, visit the [[:Category:API]] section.<br />
<br />
{{docnav|Python scripting tutorial|Mesh Scripting}}<br />
<br />
{{languages | {{es|FreeCAD Scripting Basics/es}} {{fr|FreeCAD Scripting Basics/fr}} {{it|FreeCAD Scripting Basics/it}} {{jp|FreeCAD Scripting Basics/jp}} {{ru|FreeCAD Scripting Basics/ru}} {{se|FreeCAD Scripting Basics/se}} }}<br />
<br />
[[Category:Poweruser Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Main_Page&diff=15668Main Page2013-01-02T04:49:45Z<p>Htsubota: /* FreeCAD */</p>
<hr />
<div>= FreeCAD =<br />
<br />
<div class="main-menu"><br />
<br />
{{Languages-top| {{cn|Main Page/cn}} {{de|Main Page/de}} {{es|Main Page/es}} {{fr|Main Page/fr}} {{it|Main Page/it}} {{jp|Main Page/jp}} {{pl|Main Page/pl}} {{ru|Main Page/ru}} {{se|Main Page/se}} {{tr|Main Page/tr}} }}<br />
<br />
<i>A parametric 3D CAD modeler</i><br />
<br />
</div><br />
<br />
<div class="main-toolbox"><br />
<br />
{{downloads}}<br />
<br />
{{screenshot|Rim_bling.png|a screenshot showing version 0.12}}<br />
<br />
{{feedsbox}}<br />
<br />
{{mantisbox}}<br />
<br />
{{booksbox}}<br />
<br />
{{facebookbox}}<br />
<br />
</div><br />
<br />
<div class="main-content"><br />
<br />
'''FreeCAD''' is a general purpose [http://en.wikipedia.org/wiki/Parametric_feature_based_modeler feature-based, parametric 3D modeler] for [http://en.wikipedia.org/wiki/CAD CAD], MCAD, [http://en.wikipedia.org/wiki/CAx CAx], [http://en.wikipedia.org/wiki/Computer-aided_engineering CAE] and [http://en.wikipedia.org/wiki/Product_Lifecycle_Management PLM], aimed directly at [http://en.wikipedia.org/wiki/Mechanical_engineering mechanical engineering] and [http://en.wikipedia.org/wiki/Product_design product design] but also fits a wider range of uses in engineering, such as architecture or other engineering specialties. It is 100% [http://en.wikipedia.org/wiki/Open_source Open Source] and extremely modular, allowing for very advanced extension and customization.<br />
<br />
FreeCAD is based on [http://en.wikipedia.org/wiki/Open_CASCADE OpenCasCade], a powerful geometry kernel, features an [http://en.wikipedia.org/wiki/Open_Inventor Open Inventor]-compliant 3D scene representation model provided by the [http://en.wikipedia.org/wiki/Coin3D Coin 3D] library, and a broad [http://en.wikipedia.org/wiki/Python_(programming_language) Python] API. The interface is built with [http://en.wikipedia.org/wiki/Qt_(framework) Qt]. FreeCAD runs exactly the same way on Windows, Mac OSX and Linux platforms.<br />
<br />
[[Image:Right arrow.png]] [[About FreeCAD|Learn more here...]]<br />
<br />
== Key features ==<br />
<br />
* [[Image:Feature1.jpg|left]] A complete [http://en.wikipedia.org/wiki/Open_CASCADE Open CASCADE Technology]-based '''geometry kernel''' allowing complex 3D operations on complex shape types, with native support for concepts like brep, nurbs, boolean operations and fillets {{clear}}<br />
* [[Image:Feature6.jpg|left]] A '''modular architecture''' that allow plugins (modules) to add functionality to the core application. Those extensions can be as complex as whole new applications or as simple as [[Scripting|Python scripts]] or self-recorded [[macros]] {{clear}}<br />
* [[Image:Feature3.jpg|left]] A full '''parametric model''' allowing any type of parameter-driven custom objects, that can even be [[Scripted objects|fully programmed in Python]]{{clear}}<br />
* [[Image:Feature4.jpg|left]] Complete access from '''Python''' built-in interpreter, macros or external scripts to almost any part of FreeCAD, being [[Topological data scripting|geometry creation and transformation]], the 2D or 3D representation of that geometry ([[scenegraph]]) or even the [[PyQt|FreeCAD interface]] {{clear}}<br />
* [[Image:Feature5.jpg|left]] Import/export to '''standard formats''' such as [http://en.wikipedia.org/wiki/ISO_10303 STEP], [http://en.wikipedia.org/wiki/IGES IGES], [http://en.wikipedia.org/wiki/Obj OBJ], [http://en.wikipedia.org/wiki/Dxf DXF], [http://en.wikipedia.org/wiki/Svg SVG], [http://en.wikipedia.org/wiki/STL_(file_format) STL], [http://en.wikipedia.org/wiki/COLLADA DAE], [http://en.wikipedia.org/wiki/Industry_Foundation_Classes IFC] or [http://people.sc.fsu.edu/~jburkardt/data/off/off.html OFF], in addition to FreeCAD's native [[Fcstd file format]].{{clear}}<br />
* [[Image:Feature7.jpg|left]] A [[Sketcher Workbench|Sketcher]] with constraint-solver, allowing to sketch geometry-constrained 2D shapes. The sketcher currently allows you to build several types of constrained geomerty, and use them as a base to build other objects throughout FreeCAD.{{clear}}<br />
* [[Image:Feature9.jpg|left]] A [[Robot Workbench|Robot simulation]] module that allows to study robot movements. The robot module already has an extended graphical interface allowing GUI-only workflow.{{clear}}<br />
<br />
== In development ==<br />
<br />
* [[Image:Feature8.jpg|left]] A [[Drawing Module|Drawing sheets]] module that permit to put 2D views of your 3D models on a sheet. This modules then produces ready-to-export SVG or PDF sheets. The module is still sparse but already features a powerful Python functionality.{{clear}}<br />
* [[Image:Feature-raytracing.jpg|left]] A [[Raytracing Module|Rendering]] module that can export 3D objects for rendering with external renderers. Currently only supports [http://en.wikipedia.org/wiki/POV-Ray povray], but is expected to be extended to other renderers in the future.{{clear}}<br />
* [[Image:Feature-arch.jpg|left]] An [[Arch Module|Architecture]] module that allows [http://en.wikipedia.org/wiki/Building_Information_Modeling BIM]-like workflow, with [http://en.wikipedia.org/wiki/Industry_Foundation_Classes IFC] compatibility. The making of the Arch module is heavily discussed by the community [http://sourceforge.net/apps/phpbb/free-cad/viewtopic.php?f=10&t=821 here].{{clear}}<br />
* [[Image:Feature-assembly.jpg|left]] An [[Assembly project|Assembly]] module that allows to work with multiple shapes, multiple documents, multiple files, multiple relationships...{{clear}}<br />
<br />
== Manual ==<br />
<br />
The FreeCAD manual is a work-in-progress community effort to provide state-of-the-art documentation about using FreeCAD, and is already available in several languages. It still lacks much information, so feel free to join and [[Help FreeCAD|contribute]]!<br />
<br />
{|border="0" width="100%" style="background:transparent;"<br />
|- <br />
| <br />
* [[Image:Flag-en.jpg]] [[Online Help Toc|Table of contents]]<br />
* [[Image:Flag-cn.jpg]] [[Online Help Toc/cn|目录]]<br />
* [[Image:Flag-de.jpg]] [[Online Help Toc/de|Inhaltsverzeichnis]]<br />
* [[Image:Flag-es.jpg]] [[Online Help Toc/es|Índice de contenidos]]<br />
||<br />
* [[Image:Flag-fr.jpg]] [[Online Help Toc/fr|Table des matières]]<br />
* [[Image:Flag-it.jpg]] [[Online Help Toc/it|Indice dei contenuti]]<br />
* [[Image:Flag-jp.jpg]] [[Online Help Toc/jp|目次]]<br />
* [[Image:Flag-pl.jpg]] [[Online Help Toc/pl|Spis Treści]]<br />
||<br />
* [[Image:Flag-pt.jpg]] [[Online Help Toc/pt|Tabela de conteúdos]]<br />
* [[Image:Flag-ru.jpg]] [[Online Help Toc/ru|Содержание]]<br />
* [[Image:Flag-se.jpg]] [[Online Help Toc/se|Innehallsforteckning]]<br />
* [[Image:Flag-tr.jpg]] [[Online Help Toc/tr|İçindekiler]]<br />
|}<br />
<br />
== Get involved ==<br />
<br />
=== How to participate ===<br />
<br />
There is plenty to do inside the FreeCAD project, if you are interested in helping us. There are programming tasks, for C++ or python programmers, but there are also many things you can do even if you cannot code, such as writing documentation, helping newcomers, translating the application and documentation, help packaging the latest release of FreeCAD for your favourite operating system, or simply help other people to discover FreeCAD around you. The [[help FreeCAD]] page describes it all with more details.<br />
<br />
=== Source code ===<br />
<br />
FreeCAD can be compiled using cMake or autotools, the git link is git://free-cad.git.sourceforge.net/gitroot/free-cad/free-cad and there are build instructions for [[CompileOnWindows|Windows]], [[CompileOnUnix|Unix/Linux]] and [[CompileOnMac|MacOSX]].<br />
<br />
=== About the development ===<br />
<br />
Check the [[Development roadmap]] for news about what is being planned, the [http://sourceforge.net/apps/mantisbt/free-cad/changelog_page.php Changelog] and [http://sourceforge.net/apps/mantisbt/free-cad/roadmap_page.php Roadmap] mantis pages to see the progresses towards next release, or the [http://www.ohloh.net/p/freecad Project statistics] for even more information about the FreeCAD codebase. All the development communication happens on the [http://sourceforge.net/apps/phpbb/free-cad/ forum], so be sure to visit it if you are interested in participating.<br />
<br />
=== Follow FreeCAD anywhere! ===<br />
<br />
[[Image:Twitter.png|link=http://www.twitter.com/FreeCADNews]] [[Image:Facebook.png|link=http://www.facebook.com/FreeCAD]] [[Image:Youtube.png|link=http://www.youtube.com/user/FreeCADNews]] [[Image:Googleplus.png|24px|link=http://plus.google.com/u/0/107660967460246172334]]<br />
<br />
</div><br />
<br />
__NOTOC__</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD-Ship_s60_tutorial&diff=15151FreeCAD-Ship s60 tutorial2012-12-15T13:14:20Z<p>Htsubota: /* Hydrostatics */</p>
<hr />
<div>In this tutorial we will work with Series 60 ship, from the Iowa University. The tutorial is aimed to show how to work with a symmetric monohull ship, but multihull or non symmetric ships can be performed with the same proceeding.<br />
<br />
You can learn more about [[FreeCADShip_Workbench|FreeCAD-Ship here]]<br />
<br />
{{VeryImportantMessage|<center>'''Windows users'''</center><br />
<center>FreeCAD-Ship have been recently integrated into FreeCAD package, so some bugs can be detected.</center><br />
<center>If your Ship module have icons lost, please rename '''ShipIcons''' folder at</center><br />
<center>C:\Program Files (x86)\FreeCAD0.13\Mod\Ship</center><br />
<center>path as '''Icons''' folder, and then restart FreeCAD.</center>}}<br />
<br />
== Loading geometry ==<br />
<br />
=== Introduction ===<br />
<br />
FreeCAD-Ship works over '''Ship entities''', that must be created on top of provided geometry. Geometry must be a solid, or set of solids, following criteria must be taken into account:<br />
<br />
* All hull geometry must be provided (including symmetric bodies).<br />
* Starboard geometry must be included at negatives ''y'' domain.<br />
* Origin (0,0,0) point is the '''Midship section''' (Midpoint between after and forward perpendicular) and '''base line''' intersection.<br />
<br />
[[Image:FreeCAD-Ship-SignCriteria.jpg|center|Schematic view of sign criteria]]<br />
<center><span style="font-variant:small-caps">FreeCAD-Ship sign criteria</span></center><br />
<br />
=== Loading Series 60 geometry ===<br />
<br />
In order to help new users FreeCAD-Ship includes an example geometries loader, with almost famous ship geometries.<br />
<br />
[[Image:FreeCAD-Ship-LoadIco.png|center|Example ship geometries loader icon.]]<br />
<center><span style="font-variant:small-caps">Example ship geometries loader icon</span></center><br />
<br />
Executing the tool (Ship design/Load an example ship geometry) a task dialogue will shown. Select '''Series 60 from Iowa University''' and press Accept. Tool loads new document with '''s60_IowaUniversity''' geometry.<br />
<br />
{{VeryImportantMessage|<center>'''Warning, before editing anything!'''</center><br />
<center>You are now working with the original example file.</center><br />
<center>To preserve the original unedited example, '''you must first save it as a new file, before editing anything.'''</center>}}<br />
<br />
== Create ship instance ==<br />
<br />
In order to create a '''Ship instance''' select s60 geometry and execute the '''ship creation tool''' (Ship design/Create a new ship).<br />
<br />
[[Image:FreeCAD-Ship-Ico.png|center|Ship creation tool.]]<br />
<center><span style="font-variant:small-caps">Ship creation tool icon</span></center><br />
<br />
Creating ship task dialogue and some annotations at 3D view will shown. The annotations will removed when you close Ship creation tool, so don't worry about this.<br />
<br />
Most relevant ship data must be introduced (FreeCAD-Ship uses a progressive data introduction system, so basic operations can be performed knowing only basic ship data, more information is needed as the operations become more complex).<br />
<br />
=== Ship data ===<br />
<br />
Main dimensions must be introduced here:<br />
<br />
* Length: Length between perpendiculars, 25.5 m for this ship.<br />
* Beam: Total ship beam, 3.389 m for this ship.<br />
* Draft: Design draft, 1.0 m for this ship.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationFront.png|center|Front view annotations]]<br />
<center><span style="font-variant:small-caps">Length annotations.</span></center><br />
<br />
Usually the Length between perpendiculars depends on design draft, so if you don't know what is the length of your ship you can set draft, and fit length in order to get bow and draft intersection.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationSide.png|center|Side view annotations]]<br />
<center><span style="font-variant:small-caps">Beam annotations.</span></center><br />
<br />
Same process is valid for Beam fit. Note that requested value is total beam, but annotation is only refered to starboard half ship.<br />
<br />
When you press '''Accept''' button program creates your new Ship instance called '''Ship''' at ''Tags & Attributes'' dialog. We don't need geometry anymore, so you can hide it.<br />
<br />
[[Image:FreeCAD-Ship-ShipInstance.png|center|Ship instance icon]]<br />
<center><span style="font-variant:small-caps">Ship instance icon.</span></center><br />
<br />
From here onwards, you must have '''Ship''' selected before you execute any FreeCAD-Ship tool.<br />
<br />
== Outline draw ==<br />
<br />
FreeCAD-Ship provides a tool in order to make easy exporting ship outline draw.<br />
<br />
[[Image:FreeCAD-Ship-OutlineDrawIco.png|center|Outline draw tool.]]<br />
<center><span style="font-variant:small-caps">Outline draw tool icon</span></center><br />
<br />
Outline draw is a set of cuts that allows to meet the hull geometry with a standardized plot. Outline drawing needs the cuts set.<br />
<br />
=== Transversal cuts ===<br />
<br />
Usually 21 transversal equi-distance sections between perpendiculars must be performed. in order to do it FreeCAD provides an automatic tool in order to do it, simply select '''Transversal''' type of sections, go to '''Auto create''' box and set '''21''' sections, then press '''Create sections'''.<br />
<br />
[[Image:S60OutlineTransversal.png|center|Outline draw transversal sections preview.]]<br />
<center><span style="font-variant:small-caps">Outline draw transversal sections preview</span></center><br />
<br />
Sections table is filled, and sections preview called '''OutlineDraw''' shown. Usually more sections was added at bow and stern, where more complex curvatures are registered, in order to do it go to the end of the table, and do ''double click'' at empty item in order to edit it, pressing intro to confirm. Add following sections:<br />
<br />
* X<sub>22</sub> = -12.1125 m<br />
* X<sub>23</sub> = 12.1125 m<br />
<br />
Depending hull geometry complexity, sections preview can take some time.<br />
<br />
=== Longitudinal cuts ===<br />
<br />
Two longitudinal cuts must be added, so select '''Longitudinal''' type of sections, go to '''Auto create''' box and set '''2''' sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
=== Water lines ===<br />
<br />
6 Water lines between base line and design draft must be added, so select '''Water lines''' type of sections, go to '''Auto create''' box and set '''5''' (Z = 0 m will not be considered, add it manually if you need it) sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
Several additional water lines must be added:<br />
<br />
* Z<sub>6</sub> = 1.2 m<br />
* Z<sub>7</sub> = 1.4 m<br />
* Z<sub>8</sub> = 1.6 m<br />
* Z<sub>9</sub> = 1.8 m<br />
* Z<sub>10</sub> = 2.0 m<br />
<br />
=== Perform plot ===<br />
<br />
Select '''1:100''' scale and press '''Accept'''. Plot is performed, you can learn more about plotting and how to edit it [[Drawing_Workbench|here]] (Depending on version, projected version of plot can be bad represented, or not represented).<br />
<br />
[[Image:FreeCAD-Ship-S60OutlinePlot.png|center|Outline draw plot.]]<br />
<center><span style="font-variant:small-caps">Outline draw plot.</span></center><br />
<br />
3D sections are preserved to in order you can work with them (i.e.- Multisolid ships may have undesired edges at plot).<br />
<br />
[[Image:FreeCAD-Ship-S60Outline3DSections.png|center|Resultant sections.]]<br />
<center><span style="font-variant:small-caps">Resultant sections.</span></center><br />
<br />
== Transversal areas curve ==<br />
<br />
One typical ship design hydrodynamic parameter is the transversal areas curve, that retrieves some indicators about the behaviour of the hull (towing resistance, seakeeping, ...). FreeCAD-Ship provides a simple tool in order to perform transversal areas curve.<br />
<br />
[[Image:FreeCAD-Ship-AreaCurveIco.png|center|Transversal areas curve tool icon.]]<br />
<center><span style="font-variant:small-caps">Transversal areas curve tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown, and free surface prewied is created at 3D view (Free surface preview will be removed when tool finished, so don't worry about them). Into task dialog input and output data is present.<br />
<br />
=== Input data ===<br />
<br />
Draft and trim (Hull ''y edge'' rotation angle, positive if stern draft may increase) must be provided. Several areas curves may be performed, depending on ship load situations, but two typical plot should be performed:<br />
<br />
* Design transversal areas curve: Without triming angle and using design draft, 1.0 m in this case.<br />
* Maximum draft transversal areas curve: Without trimin angle, and maximum draft allowed, 2.0 m in this case.<br />
<br />
=== Output data ===<br />
<br />
Some relevant data is shown at real time:<br />
<br />
* '''L''': Lenght between perpendiculars, value set at ship instance creation.<br />
* '''B''': Beam selected at ship creation.<br />
* '''T''': Actual draft amidships.<br />
* '''Trim''': Trim angle.<br />
* '''T<sub>AP</sub>''': After perpendicular draft.<br />
* '''T<sub>FP</sub>''': Forward perpendicular draft.<br />
* '''Displacement''': Ship displacement (salt water considered, divide by 1.025 in order to know displaced volume).<br />
* '''XCB''': Buoyancy centre point X coordinate (relative to midship section).<br />
<br />
When '''Accept''' button is pressed a plot is performed (depending on geometry complexity can take some time, you can see progress on terminal, and stop work pressing '''Ctrl+C''').<br />
<br />
You need to have pyxplot installed on your computer. As it is a big dependency it is not a default option.<br />
<br />
[[Image:FreeCAD-Ship-s60Areas.png|center|Design draft transversal areas curve. ]]<br />
<center><span style="font-variant:small-caps">Design draft transversal areas curve. </span></center><br />
<br />
You can perform maximum draft transversal areas curve in order to see the differences (for instance areas curve pass through length perpendiculars).<br />
<br />
FreeCAD-Ship use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plot as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert it to '''*.png''' image. You can see where '''areas.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''areas.dat''': Contains transversal areas data.<br />
* '''areas.pyxplot''': pyxplot layout in order to plot '''areas.dat''' sheet.<br />
* '''areas.eps''': EPS image version (best choice in order to edit it).<br />
* '''areas.png''': Final image PNG version.<br />
<br />
When new transversal areas curve is performed files will be overwritten, so copy it at other place if you want to preserve it.<br />
<br />
== Hydrostatics ==<br />
<br />
Hydrostatics computation is a critical stage at ship design due to know principal stability hull parameters. Hydrostatics are mandatory data in order to classification societies certificates ship, and joined with loading condition data (weights and gravity position) provides essential data about ship stability. FreeCAD-Ship provides a tool to obtain main hydrostatics curves (GZ curves are considered in other tool).<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsIco.png|center|Hydrostatics tool icon.]]<br />
<center><span style="font-variant:small-caps">Hydrostatics tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown. Usually Hydrostatics curves are presented for each trim angle, in this tutorial only upright trimming angle will considered (0º), with an interval around every loading condition draft. Since we don't know what loading conditions we can get, we will consider almost draft possibilities (Usually, in order to get as many resolution as possible, naval architects fits the interval to feasible drafts).<br />
<br />
So we set following data:<br />
* '''Trim''' = 0º<br />
* '''Minimum Draft''' = 0.1 m<br />
* '''Maximum Draft''' = 2.0 m<br />
* '''Number of points''' = 39. A lot of points or really complex geometries imply long computation times, in this case around 1 minute can be expend.<br />
<br />
When '''Accept''' button is pressed plots are performed.<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsCurves.jpg|center|Hydrostatics curves. ]]<br />
<center><span style="font-variant:small-caps">Hydrostatics curves. </span></center><br />
<br />
As transversal areas curve tool, Hydrostatics tools use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plots as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert to '''*.png''' images. You can see where '''hydrostatics.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''hydrostatics.dat''': Computed hydrostatics data.<br />
* '''volume.pyxplot''': pyxplot layout in order to plot the curves.<br />
* '''volume.eps''': EPS image version of volume related Hydrostatics.<br />
* '''volume.png''': Final volume related hydrostatics PNG version.<br />
* '''stability.eps''': EPS image version of stability related Hydrostatics.<br />
* '''stability.png''': Final stability related hydrostatics PNG version.<br />
* '''coeffs.eps''': EPS image version of forms coeffcients related Hydrostatics.<br />
* '''coeffs.png''': Final forms coefficients related hydrostatics PNG version.<br />
<br />
All files will overwritten when new hydrostatics are computed, so save them before repeat the process.<br />
<br />
== Continue learning FreeCAD-Ship ==<br />
<br />
Now you are ready to continue learning [[FreeCADShip_Workbench|FreeCAD-Ship]], [[FreeCAD-Ship_s60_tutorial_(II)|here]] is the second chapter of Series 60 from Iowa university ship.<br />
<br />
[[Category:Tutorials]]<br />
<br />
{{languages | {{es|FreeCAD-Ship_s60_tutorial/es}} {{fr|FreeCAD-Ship_s60_tutorial/fr}}}}</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD-Ship_s60_tutorial&diff=15113FreeCAD-Ship s60 tutorial2012-12-13T11:50:07Z<p>Htsubota: /* Transversal cuts */</p>
<hr />
<div>In this tutorial we will work with Series 60 ship, from the Iowa University. The tutorial is aimed to show how to work with a symmetric monohull ship, but multihull or non symmetric ships can be performed with the same proceeding.<br />
<br />
You can learn more about [[FreeCADShip_Workbench|FreeCAD-Ship here]]<br />
<br />
{{VeryImportantMessage|<center>'''Windows users'''</center><br />
<center>FreeCAD-Ship have been recently integrated into FreeCAD package, so some bugs can be detected.</center><br />
<center>If your Ship module have icons lost, please rename '''ShipIcons''' folder at</center><br />
<center>C:\Program Files (x86)\FreeCAD0.13\Mod\Ship</center><br />
<center>path as '''Icons''' folder, and then restart FreeCAD.</center>}}<br />
<br />
== Loading geometry ==<br />
<br />
=== Introduction ===<br />
<br />
FreeCAD-Ship works over '''Ship entities''', that must be created on top of provided geometry. Geometry must be a solid, or set of solids, following criteria must be taken into account:<br />
<br />
* All hull geometry must be provided (including symmetric bodies).<br />
* Starboard geometry must be included at negatives ''y'' domain.<br />
* Origin (0,0,0) point is the '''Midship section''' (Midpoint between after and forward perpendicular) and '''base line''' intersection.<br />
<br />
[[Image:FreeCAD-Ship-SignCriteria.jpg|center|Schematic view of sign criteria]]<br />
<center><span style="font-variant:small-caps">FreeCAD-Ship sign criteria</span></center><br />
<br />
=== Loading Series 60 geometry ===<br />
<br />
In order to help new users FreeCAD-Ship includes an example geometries loader, with almost famous ship geometries.<br />
<br />
[[Image:FreeCAD-Ship-LoadIco.png|center|Example ship geometries loader icon.]]<br />
<center><span style="font-variant:small-caps">Example ship geometries loader icon</span></center><br />
<br />
Executing the tool (Ship design/Load an example ship geometry) a task dialogue will shown. Select '''Series 60 from Iowa University''' and press Accept. Tool loads new document with '''s60_IowaUniversity''' geometry.<br />
<br />
{{VeryImportantMessage|<center>'''Warning, before editing anything!'''</center><br />
<center>You are now working with the original example file.</center><br />
<center>To preserve the original unedited example, '''you must first save it as a new file, before editing anything.'''</center>}}<br />
<br />
== Create ship instance ==<br />
<br />
In order to create a '''Ship instance''' select s60 geometry and execute the '''ship creation tool''' (Ship design/Create a new ship).<br />
<br />
[[Image:FreeCAD-Ship-Ico.png|center|Ship creation tool.]]<br />
<center><span style="font-variant:small-caps">Ship creation tool icon</span></center><br />
<br />
Creating ship task dialogue and some annotations at 3D view will shown. The annotations will removed when you close Ship creation tool, so don't worry about this.<br />
<br />
Most relevant ship data must be introduced (FreeCAD-Ship uses a progressive data introduction system, so basic operations can be performed knowing only basic ship data, more information is needed as the operations become more complex).<br />
<br />
=== Ship data ===<br />
<br />
Main dimensions must be introduced here:<br />
<br />
* Length: Length between perpendiculars, 25.5 m for this ship.<br />
* Beam: Total ship beam, 3.389 m for this ship.<br />
* Draft: Design draft, 1.0 m for this ship.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationFront.png|center|Front view annotations]]<br />
<center><span style="font-variant:small-caps">Length annotations.</span></center><br />
<br />
Usually the Length between perpendiculars depends on design draft, so if you don't know what is the length of your ship you can set draft, and fit length in order to get bow and draft intersection.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationSide.png|center|Side view annotations]]<br />
<center><span style="font-variant:small-caps">Beam annotations.</span></center><br />
<br />
Same process is valid for Beam fit. Note that requested value is total beam, but annotation is only refered to starboard half ship.<br />
<br />
When you press '''Accept''' button program creates your new Ship instance called '''Ship''' at ''Tags & Attributes'' dialog. We don't need geometry anymore, so you can hide it.<br />
<br />
[[Image:FreeCAD-Ship-ShipInstance.png|center|Ship instance icon]]<br />
<center><span style="font-variant:small-caps">Ship instance icon.</span></center><br />
<br />
From here onwards, you must have '''Ship''' selected before you execute any FreeCAD-Ship tool.<br />
<br />
== Outline draw ==<br />
<br />
FreeCAD-Ship provides a tool in order to make easy exporting ship outline draw.<br />
<br />
[[Image:FreeCAD-Ship-OutlineDrawIco.png|center|Outline draw tool.]]<br />
<center><span style="font-variant:small-caps">Outline draw tool icon</span></center><br />
<br />
Outline draw is a set of cuts that allows to meet the hull geometry with a standardized plot. Outline drawing needs the cuts set.<br />
<br />
=== Transversal cuts ===<br />
<br />
Usually 21 transversal equi-distance sections between perpendiculars must be performed. in order to do it FreeCAD provides an automatic tool in order to do it, simply select '''Transversal''' type of sections, go to '''Auto create''' box and set '''21''' sections, then press '''Create sections'''.<br />
<br />
[[Image:S60OutlineTransversal.png|center|Outline draw transversal sections preview.]]<br />
<center><span style="font-variant:small-caps">Outline draw transversal sections preview</span></center><br />
<br />
Sections table is filled, and sections preview called '''OutlineDraw''' shown. Usually more sections was added at bow and stern, where more complex curvatures are registered, in order to do it go to the end of the table, and do ''double click'' at empty item in order to edit it, pressing intro to confirm. Add following sections:<br />
<br />
* X<sub>22</sub> = -12.1125 m<br />
* X<sub>23</sub> = 12.1125 m<br />
<br />
Depending hull geometry complexity, sections preview can take some time.<br />
<br />
=== Longitudinal cuts ===<br />
<br />
Two longitudinal cuts must be added, so select '''Longitudinal''' type of sections, go to '''Auto create''' box and set '''2''' sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
=== Water lines ===<br />
<br />
6 Water lines between base line and design draft must be added, so select '''Water lines''' type of sections, go to '''Auto create''' box and set '''5''' (Z = 0 m will not be considered, add it manually if you need it) sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
Several additional water lines must be added:<br />
<br />
* Z<sub>6</sub> = 1.2 m<br />
* Z<sub>7</sub> = 1.4 m<br />
* Z<sub>8</sub> = 1.6 m<br />
* Z<sub>9</sub> = 1.8 m<br />
* Z<sub>10</sub> = 2.0 m<br />
<br />
=== Perform plot ===<br />
<br />
Select '''1:100''' scale and press '''Accept'''. Plot is performed, you can learn more about plotting and how to edit it [[Drawing_Workbench|here]] (Depending on version, projected version of plot can be bad represented, or not represented).<br />
<br />
[[Image:FreeCAD-Ship-S60OutlinePlot.png|center|Outline draw plot.]]<br />
<center><span style="font-variant:small-caps">Outline draw plot.</span></center><br />
<br />
3D sections are preserved to in order you can work with them (i.e.- Multisolid ships may have undesired edges at plot).<br />
<br />
[[Image:FreeCAD-Ship-S60Outline3DSections.png|center|Resultant sections.]]<br />
<center><span style="font-variant:small-caps">Resultant sections.</span></center><br />
<br />
== Transversal areas curve ==<br />
<br />
One typical ship design hydrodynamic parameter is the transversal areas curve, that retrieves some indicators about the behaviour of the hull (towing resistance, seakeeping, ...). FreeCAD-Ship provides a simple tool in order to perform transversal areas curve.<br />
<br />
[[Image:FreeCAD-Ship-AreaCurveIco.png|center|Transversal areas curve tool icon.]]<br />
<center><span style="font-variant:small-caps">Transversal areas curve tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown, and free surface prewied is created at 3D view (Free surface preview will be removed when tool finished, so don't worry about them). Into task dialog input and output data is present.<br />
<br />
=== Input data ===<br />
<br />
Draft and trim (Hull ''y edge'' rotation angle, positive if stern draft may increase) must be provided. Several areas curves may be performed, depending on ship load situations, but two typical plot should be performed:<br />
<br />
* Design transversal areas curve: Without triming angle and using design draft, 1.0 m in this case.<br />
* Maximum draft transversal areas curve: Without trimin angle, and maximum draft allowed, 2.0 m in this case.<br />
<br />
=== Output data ===<br />
<br />
Some relevant data is shown at real time:<br />
<br />
* '''L''': Lenght between perpendiculars, value set at ship instance creation.<br />
* '''B''': Beam selected at ship creation.<br />
* '''T''': Actual draft amidships.<br />
* '''Trim''': Trim angle.<br />
* '''T<sub>AP</sub>''': After perpendicular draft.<br />
* '''T<sub>FP</sub>''': Forward perpendicular draft.<br />
* '''Displacement''': Ship displacement (salt water considered, divide by 1.025 in order to know displaced volume).<br />
* '''XCB''': Buoyancy centre point X coordinate (relative to midship section).<br />
<br />
When '''Accept''' button is pressed a plot is performed (depending on geometry complexity can take some time, you can see progress on terminal, and stop work pressing '''Ctrl+C''').<br />
<br />
You need to have pyxplot installed on your computer. As it is a big dependency it is not a default option.<br />
<br />
[[Image:FreeCAD-Ship-s60Areas.png|center|Design draft transversal areas curve. ]]<br />
<center><span style="font-variant:small-caps">Design draft transversal areas curve. </span></center><br />
<br />
You can perform maximum draft transversal areas curve in order to see the differences (for instance areas curve pass through length perpendiculars).<br />
<br />
FreeCAD-Ship use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plot as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert it to '''*.png''' image. You can see where '''areas.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''areas.dat''': Contains transversal areas data.<br />
* '''areas.pyxplot''': pyxplot layout in order to plot '''areas.dat''' sheet.<br />
* '''areas.eps''': EPS image version (best choice in order to edit it).<br />
* '''areas.png''': Final image PNG version.<br />
<br />
When new transversal areas curve is performed files will be overwritten, so copy it at other place if you want to preserve it.<br />
<br />
== Hydrostatics ==<br />
<br />
Hydrostatics computation is a critical stage at ship design due to know principal stability hull parameters. Hydrostatics are mandatory data in order to classification societies certificates ship, and joined with loading condition data (weights and gravity position) provides essential data about ship stability. FreeCAD-Ship provides a tool to obtain main hydrostatics curves (GZ curves are considered in other tool).<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsIco.png|center|Hydrostatics tool icon.]]<br />
<center><span style="font-variant:small-caps">Hydrostatics tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown. Ussually Hydrostatics curves are presented for each trim angle, in this tutorial only upright trimming angle will considered (0º), with an interval around every loading condition draft. Since we don't know what loading conditions we can get, we will consider almost draft posibilities (Ussually, in order to get as many resolution as possible, naval architecs fits the interval to feasible drafts).<br />
<br />
So we set following data:<br />
* '''Trim''' = 0º<br />
* '''Minimum Draft''' = 0.1 m<br />
* '''Maximum Draft''' = 2.0 m<br />
* '''Number of points''' = 39. A lot of points or really complex geometries imply long computation times, in this case around 1 minute can be expent.<br />
<br />
When '''Accept''' button is pressed plots are performed.<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsCurves.jpg|center|Hydrostatics curves. ]]<br />
<center><span style="font-variant:small-caps">Hydrostatics curves. </span></center><br />
<br />
As transversal areas curve tool, Hydrostatics tools use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plots as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert to '''*.png''' images. You can see where '''hydrostatics.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''hydrostatics.dat''': Computed hydrostatics data.<br />
* '''volume.pyxplot''': pyxplot layout in order to plot the curves.<br />
* '''volume.eps''': EPS image version of volume related Hydrostatics.<br />
* '''volume.png''': Final volume related hydrostatics PNG version.<br />
* '''stability.eps''': EPS image version of stability related Hydrostatics.<br />
* '''stability.png''': Final stability related hydrostatics PNG version.<br />
* '''coeffs.eps''': EPS image version of forms coeffcients related Hydrostatics.<br />
* '''coeffs.png''': Final forms coeffcients related hydrostatics PNG version.<br />
<br />
All files will overwritten when new hydrostatics are computed, so save them before repeat the process.<br />
<br />
== Continue learning FreeCAD-Ship ==<br />
<br />
Now you are ready to continue learning [[FreeCADShip_Workbench|FreeCAD-Ship]], [[FreeCAD-Ship_s60_tutorial_(II)|here]] is the second chapter of Series 60 from Iowa university ship.<br />
<br />
[[Category:Tutorials]]<br />
<br />
{{languages | {{es|FreeCAD-Ship_s60_tutorial/es}} {{fr|FreeCAD-Ship_s60_tutorial/fr}}}}</div>Htsubotahttps://wiki.freecad.org/index.php?title=FreeCAD-Ship_s60_tutorial&diff=15112FreeCAD-Ship s60 tutorial2012-12-12T12:45:27Z<p>Htsubota: /* Outline draw */</p>
<hr />
<div>In this tutorial we will work with Series 60 ship, from the Iowa University. The tutorial is aimed to show how to work with a symmetric monohull ship, but multihull or non symmetric ships can be performed with the same proceeding.<br />
<br />
You can learn more about [[FreeCADShip_Workbench|FreeCAD-Ship here]]<br />
<br />
{{VeryImportantMessage|<center>'''Windows users'''</center><br />
<center>FreeCAD-Ship have been recently integrated into FreeCAD package, so some bugs can be detected.</center><br />
<center>If your Ship module have icons lost, please rename '''ShipIcons''' folder at</center><br />
<center>C:\Program Files (x86)\FreeCAD0.13\Mod\Ship</center><br />
<center>path as '''Icons''' folder, and then restart FreeCAD.</center>}}<br />
<br />
== Loading geometry ==<br />
<br />
=== Introduction ===<br />
<br />
FreeCAD-Ship works over '''Ship entities''', that must be created on top of provided geometry. Geometry must be a solid, or set of solids, following criteria must be taken into account:<br />
<br />
* All hull geometry must be provided (including symmetric bodies).<br />
* Starboard geometry must be included at negatives ''y'' domain.<br />
* Origin (0,0,0) point is the '''Midship section''' (Midpoint between after and forward perpendicular) and '''base line''' intersection.<br />
<br />
[[Image:FreeCAD-Ship-SignCriteria.jpg|center|Schematic view of sign criteria]]<br />
<center><span style="font-variant:small-caps">FreeCAD-Ship sign criteria</span></center><br />
<br />
=== Loading Series 60 geometry ===<br />
<br />
In order to help new users FreeCAD-Ship includes an example geometries loader, with almost famous ship geometries.<br />
<br />
[[Image:FreeCAD-Ship-LoadIco.png|center|Example ship geometries loader icon.]]<br />
<center><span style="font-variant:small-caps">Example ship geometries loader icon</span></center><br />
<br />
Executing the tool (Ship design/Load an example ship geometry) a task dialogue will shown. Select '''Series 60 from Iowa University''' and press Accept. Tool loads new document with '''s60_IowaUniversity''' geometry.<br />
<br />
{{VeryImportantMessage|<center>'''Warning, before editing anything!'''</center><br />
<center>You are now working with the original example file.</center><br />
<center>To preserve the original unedited example, '''you must first save it as a new file, before editing anything.'''</center>}}<br />
<br />
== Create ship instance ==<br />
<br />
In order to create a '''Ship instance''' select s60 geometry and execute the '''ship creation tool''' (Ship design/Create a new ship).<br />
<br />
[[Image:FreeCAD-Ship-Ico.png|center|Ship creation tool.]]<br />
<center><span style="font-variant:small-caps">Ship creation tool icon</span></center><br />
<br />
Creating ship task dialogue and some annotations at 3D view will shown. The annotations will removed when you close Ship creation tool, so don't worry about this.<br />
<br />
Most relevant ship data must be introduced (FreeCAD-Ship uses a progressive data introduction system, so basic operations can be performed knowing only basic ship data, more information is needed as the operations become more complex).<br />
<br />
=== Ship data ===<br />
<br />
Main dimensions must be introduced here:<br />
<br />
* Length: Length between perpendiculars, 25.5 m for this ship.<br />
* Beam: Total ship beam, 3.389 m for this ship.<br />
* Draft: Design draft, 1.0 m for this ship.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationFront.png|center|Front view annotations]]<br />
<center><span style="font-variant:small-caps">Length annotations.</span></center><br />
<br />
Usually the Length between perpendiculars depends on design draft, so if you don't know what is the length of your ship you can set draft, and fit length in order to get bow and draft intersection.<br />
<br />
[[Image:FreeCAD-Ship-S60ShipCreationSide.png|center|Side view annotations]]<br />
<center><span style="font-variant:small-caps">Beam annotations.</span></center><br />
<br />
Same process is valid for Beam fit. Note that requested value is total beam, but annotation is only refered to starboard half ship.<br />
<br />
When you press '''Accept''' button program creates your new Ship instance called '''Ship''' at ''Tags & Attributes'' dialog. We don't need geometry anymore, so you can hide it.<br />
<br />
[[Image:FreeCAD-Ship-ShipInstance.png|center|Ship instance icon]]<br />
<center><span style="font-variant:small-caps">Ship instance icon.</span></center><br />
<br />
From here onwards, you must have '''Ship''' selected before you execute any FreeCAD-Ship tool.<br />
<br />
== Outline draw ==<br />
<br />
FreeCAD-Ship provides a tool in order to make easy exporting ship outline draw.<br />
<br />
[[Image:FreeCAD-Ship-OutlineDrawIco.png|center|Outline draw tool.]]<br />
<center><span style="font-variant:small-caps">Outline draw tool icon</span></center><br />
<br />
Outline draw is a set of cuts that allows to meet the hull geometry with a standardized plot. Outline drawing needs the cuts set.<br />
<br />
=== Transversal cuts ===<br />
<br />
Usually 21 transversal equi-distance sections between perpendiculars must be performed. in order to do it FreeCAD provides an automatic tool in order to do it, simply select '''Transversal''' type of sections, go to '''Auto create''' box and set '''21''' sections, then press '''Create sections'''.<br />
<br />
[[Image:S60OutlineTransversal.png|center|Outline draw transversal sections preview.]]<br />
<center><span style="font-variant:small-caps">Outline draw transversal sections preview</span></center><br />
<br />
Sections table is filled, and sections preview called '''OutlineDraw''' shown. Ussually mor sections was added at bow and stern, where more complex curvatures are registered, in order to do it go to the end of the table, and do ''double click'' at empty item in order to edit it, pressing intro to confirm. Add following sections:<br />
<br />
* X<sub>22</sub> = -12.1125 m<br />
* X<sub>23</sub> = 12.1125 m<br />
<br />
Depending hull geometry complexity, sections preview can take some time.<br />
<br />
=== Longitudinal cuts ===<br />
<br />
Two longitudinal cuts must be added, so select '''Longitudinal''' type of sections, go to '''Auto create''' box and set '''2''' sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
=== Water lines ===<br />
<br />
6 Water lines between base line and design draft must be added, so select '''Water lines''' type of sections, go to '''Auto create''' box and set '''5''' (Z = 0 m will not be considered, add it manually if you need it) sections, then press '''Create sections'''. Sections table is filled, and sections preview updated.<br />
<br />
Several additional water lines must be added:<br />
<br />
* Z<sub>6</sub> = 1.2 m<br />
* Z<sub>7</sub> = 1.4 m<br />
* Z<sub>8</sub> = 1.6 m<br />
* Z<sub>9</sub> = 1.8 m<br />
* Z<sub>10</sub> = 2.0 m<br />
<br />
=== Perform plot ===<br />
<br />
Select '''1:100''' scale and press '''Accept'''. Plot is performed, you can learn more about plotting and how to edit it [[Drawing_Workbench|here]] (Depending on version, projected version of plot can be bad represented, or not represented).<br />
<br />
[[Image:FreeCAD-Ship-S60OutlinePlot.png|center|Outline draw plot.]]<br />
<center><span style="font-variant:small-caps">Outline draw plot.</span></center><br />
<br />
3D sections are preserved to in order you can work with them (i.e.- Multisolid ships may have undesired edges at plot).<br />
<br />
[[Image:FreeCAD-Ship-S60Outline3DSections.png|center|Resultant sections.]]<br />
<center><span style="font-variant:small-caps">Resultant sections.</span></center><br />
<br />
== Transversal areas curve ==<br />
<br />
One typical ship design hydrodynamic parameter is the transversal areas curve, that retrieves some indicators about the behaviour of the hull (towing resistance, seakeeping, ...). FreeCAD-Ship provides a simple tool in order to perform transversal areas curve.<br />
<br />
[[Image:FreeCAD-Ship-AreaCurveIco.png|center|Transversal areas curve tool icon.]]<br />
<center><span style="font-variant:small-caps">Transversal areas curve tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown, and free surface prewied is created at 3D view (Free surface preview will be removed when tool finished, so don't worry about them). Into task dialog input and output data is present.<br />
<br />
=== Input data ===<br />
<br />
Draft and trim (Hull ''y edge'' rotation angle, positive if stern draft may increase) must be provided. Several areas curves may be performed, depending on ship load situations, but two typical plot should be performed:<br />
<br />
* Design transversal areas curve: Without triming angle and using design draft, 1.0 m in this case.<br />
* Maximum draft transversal areas curve: Without trimin angle, and maximum draft allowed, 2.0 m in this case.<br />
<br />
=== Output data ===<br />
<br />
Some relevant data is shown at real time:<br />
<br />
* '''L''': Lenght between perpendiculars, value set at ship instance creation.<br />
* '''B''': Beam selected at ship creation.<br />
* '''T''': Actual draft amidships.<br />
* '''Trim''': Trim angle.<br />
* '''T<sub>AP</sub>''': After perpendicular draft.<br />
* '''T<sub>FP</sub>''': Forward perpendicular draft.<br />
* '''Displacement''': Ship displacement (salt water considered, divide by 1.025 in order to know displaced volume).<br />
* '''XCB''': Buoyancy centre point X coordinate (relative to midship section).<br />
<br />
When '''Accept''' button is pressed a plot is performed (depending on geometry complexity can take some time, you can see progress on terminal, and stop work pressing '''Ctrl+C''').<br />
<br />
You need to have pyxplot installed on your computer. As it is a big dependency it is not a default option.<br />
<br />
[[Image:FreeCAD-Ship-s60Areas.png|center|Design draft transversal areas curve. ]]<br />
<center><span style="font-variant:small-caps">Design draft transversal areas curve. </span></center><br />
<br />
You can perform maximum draft transversal areas curve in order to see the differences (for instance areas curve pass through length perpendiculars).<br />
<br />
FreeCAD-Ship use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plot as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert it to '''*.png''' image. You can see where '''areas.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''areas.dat''': Contains transversal areas data.<br />
* '''areas.pyxplot''': pyxplot layout in order to plot '''areas.dat''' sheet.<br />
* '''areas.eps''': EPS image version (best choice in order to edit it).<br />
* '''areas.png''': Final image PNG version.<br />
<br />
When new transversal areas curve is performed files will be overwritten, so copy it at other place if you want to preserve it.<br />
<br />
== Hydrostatics ==<br />
<br />
Hydrostatics computation is a critical stage at ship design due to know principal stability hull parameters. Hydrostatics are mandatory data in order to classification societies certificates ship, and joined with loading condition data (weights and gravity position) provides essential data about ship stability. FreeCAD-Ship provides a tool to obtain main hydrostatics curves (GZ curves are considered in other tool).<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsIco.png|center|Hydrostatics tool icon.]]<br />
<center><span style="font-variant:small-caps">Hydrostatics tool icon.</span></center><br />
<br />
When tool is executed a task dialog is shown. Ussually Hydrostatics curves are presented for each trim angle, in this tutorial only upright trimming angle will considered (0º), with an interval around every loading condition draft. Since we don't know what loading conditions we can get, we will consider almost draft posibilities (Ussually, in order to get as many resolution as possible, naval architecs fits the interval to feasible drafts).<br />
<br />
So we set following data:<br />
* '''Trim''' = 0º<br />
* '''Minimum Draft''' = 0.1 m<br />
* '''Maximum Draft''' = 2.0 m<br />
* '''Number of points''' = 39. A lot of points or really complex geometries imply long computation times, in this case around 1 minute can be expent.<br />
<br />
When '''Accept''' button is pressed plots are performed.<br />
<br />
[[Image:FreeCAD-Ship-HydrostaticsCurves.jpg|center|Hydrostatics curves. ]]<br />
<center><span style="font-variant:small-caps">Hydrostatics curves. </span></center><br />
<br />
As transversal areas curve tool, Hydrostatics tools use [http://www.pyxplot.org.uk/ pyxplot] in order to generate plots as '''*.eps''' image, and [http://www.ghostscript.com/ ghostscript] in order to convert to '''*.png''' images. You can see where '''hydrostatics.dat''' output file has been placed at the report view (View/Views/Report view), and load it with datasheet software (for example [http://www.libreoffice.org libreOffice]). Nearby data file several auxiliary files has been created too:<br />
<br />
* '''hydrostatics.dat''': Computed hydrostatics data.<br />
* '''volume.pyxplot''': pyxplot layout in order to plot the curves.<br />
* '''volume.eps''': EPS image version of volume related Hydrostatics.<br />
* '''volume.png''': Final volume related hydrostatics PNG version.<br />
* '''stability.eps''': EPS image version of stability related Hydrostatics.<br />
* '''stability.png''': Final stability related hydrostatics PNG version.<br />
* '''coeffs.eps''': EPS image version of forms coeffcients related Hydrostatics.<br />
* '''coeffs.png''': Final forms coeffcients related hydrostatics PNG version.<br />
<br />
All files will overwritten when new hydrostatics are computed, so save them before repeat the process.<br />
<br />
== Continue learning FreeCAD-Ship ==<br />
<br />
Now you are ready to continue learning [[FreeCADShip_Workbench|FreeCAD-Ship]], [[FreeCAD-Ship_s60_tutorial_(II)|here]] is the second chapter of Series 60 from Iowa university ship.<br />
<br />
[[Category:Tutorials]]<br />
<br />
{{languages | {{es|FreeCAD-Ship_s60_tutorial/es}} {{fr|FreeCAD-Ship_s60_tutorial/fr}}}}</div>Htsubotahttps://wiki.freecad.org/index.php?title=Engine_Block_Tutorial&diff=14937Engine Block Tutorial2012-12-05T12:09:24Z<p>Htsubota: /* Finishing out the Crankcase */</p>
<hr />
<div>[[Image:Engine Block Tutorial - Finished Engine Block.png|thumb|right|300px]]<br />
<br />
This is an introductory tutorial to modeling in FreeCAD. The purposes of the tutorial are to introduce you to the primitive data types for parametric objects, boolean operations, 2D drafting, and the process of converting 2D drafts into 3D models. As a working example we will be modeling the simple engine block and crankcase seen at the right.<br />
<br />
== Getting Started ==<br />
<br />
To begin with, open FreeCAD, go to ''File->New'' to create a new document, and then ''File->Save'' to save it somewhere on your computer, I named my project 'Engine'. You will notice that after you save the project, the ''tree view'' on the left side of the screen will show the name of the project you are working on. You can have more than one project open at a time and each project will be shown as the root of a tree in the tree view.<br />
<br />
== Roughing Out the Block ==<br />
<br />
Now to begin working on the actual model. We will start by adding a Box for the overall outline of the engine block. To do this we need to add a ''part'' to the model, go to View->Workbench->Part to select the [[Part Module]]. You will notice that after you select the workbench, you get a different set of toolbar buttons at the top. Flip through a couple of the other workbenches to familiarize yourself with the workbench system and then return to the part module.<br />
<br />
=== The Billet ===<br />
<br />
On the part module you will see a bunch of buttons for primitive objects like box, sphere, cone, etc. Click the box button ([[Image:Part_Box.png|16px]]) to add a cube to the scene. Each of the primitives listed has a default set of parameters that get set when the primitive is added. If you want you can add one of each of the primitives to see what they all look like. Primitives can be removed from the scene by selecting them and pressing the delete key. There are two ways to select objects, you can either left-click on them in the 3D view, or you can left click on them in the tree view. In either method, holding CTRL will let you select multiple items. You can zoom the 3d view with the scroll wheel on your mouse. To pan the view, middle click and drag. To rotate the view you click and hold the middle mouse button and while holding it you ''also'' push and hold the left mouse button as well, then dragging the mouse will rotate the view. You can also do a single middle click on some part of your 3D object to make the view rotate around that point in 3D space. Also, the numbers 1-6 and the number 0 on the number pad will show you various views of the scene (top, left, axometric, etc). Spend a minute or two getting comfortable with manipulating the 3D view.<br />
<br />
: ''Further reading: [[Mouse Model | Navigating in the 3D space]]''<br />
<br />
Once you have your cube and are comfortable with how the mouse works, we will begin setting up the dimensions of the CAD model. Select the cube by clicking on it in the tree view and then click on the 'Data' tab of the ''Property View'' located below the tree view (go to ''View->Views->Property View'' if you have closed it). In the data tab you can modify the properties of the object you have selected in the tree view. Depending on what kind of object you select there will be different parameters for you to set in the data tab. For a box we need a 3 vectors, one for its position in 3D space, another for its orientation, and a third to specify the dimensions of the box. For a sphere you would be able to specify the central point, and the radius; cones have a radius, height, and position; and so on. We are building a small 2-cylinder engine block so set the size and position of the box to the following values (make sure you set the XYZ under 'Position', the ones under 'Axis' set the axis of rotation and the default values are what we want):<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 0.0 mm || Height: 110.0 mm<br />
|-<br />
| Y: -40.0 mm || Length: 140.0 mm<br />
|-<br />
| Z: 0.0 mm || Width: 80.0 mm<br />
|-<br />
|}<br />
<br />
Now that you have your engine block dimensioned properly we should give it a more descriptive name. Select it in the tree view and either right click to rename it or press the ''F2 key'' on your keyboard. Name this part 'Billet'.<br />
<br />
=== The First Cylinder ===<br />
<br />
Next we will carve out the first cylinder all the way through the engine block. To do this we will add a cylinder to the model with the size we want to bore out and then do a Boolean operation to "subtract" the material away from the block. Click the add cylinder button ([[Image:Part_Cylinder.png|16px]]) to create a new cylinder and then select it in the tree view and set its properties to the following:<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 40.0 mm || Height: 110.0 mm<br />
|-<br />
| Y: 0.0 mm || Radius: 25.0 mm<br />
|-<br />
| Z: 0.0 mm || <br />
|-<br />
|}<br />
<br />
Once the properties are set correctly you should see the circular ends of the cylinder on the top and bottom faces of the engine block. Name this object ''Cylilnder 1'' by selecting it in the tree view.<br />
<br />
=== The Second Cylinder ===<br />
<br />
We could make the second cylinder the same way we made the first, however it would be much easier to just copy the existing work we have done for the one as the only difference between the two is their X coordinate. To do this, select ''Cylinder 1'' in the tree view and then go to ''Edit->Duplicate Selection''. You will see the new cylinder appear in the tree view (name it ''Cylinder 2'' right away), but you will not see it in the 3D view as it is in the same place as the first cylinder. Now select ''Cylinder 2'' in the tree view and then change it's X coordinate to 100 mm. Notice that even as you are updating the numbers in the data field you should see the cylinder moving in the 3D view. Once the second cylinder is properly positioned you can see what they look like by selecting the ''Billet'' in the tree view and then pressing ''Spacebar'' to hide it (notice that hidden objects are grayed out in the tree view). Hide all three objects one by one and then show them all again.<br />
<br />
=== Boring out the Cylinders ===<br />
<br />
[[Image: Engine Block Tutorial - Bored Block.png|thumb|right|300px]]<br />
<br />
Now that both cylinders are in place we want to use them to bore out the block to the appropriate dimensions. To do this we will use ''boolean operations'' on our 3 primitives. We will start by making a union out of the two cylinders so we can subtract them as a group from the block. Select ''Cylinder 1'' in the tree view and then ''CTRL+LeftClick'' to select ''Cylinder 2'' as well. Now press the Union button ([[Image:Part_Fuse.png|16px]]) to fuse the objects together. You will notice that in the tree view, there is now a new object called ''Fusion''. If you click the dropdown arrow next to Fusion you will see the two cylinders but they will be grayed out. Instead of Fusion, lets rename that to ''Cylinders'' so it is easier to find later. Now we bore out the engine block. Select the ''Billet'' and ''then'' select the ''Cylinders'' and press the Make Cut button ([[Image:Part_Cut.png|16px]]). The two selected objects will again be combined like they were for the union operation and the single resulting object will be named ''Cut'' (which you should rename to ''Bored Block''). Press the ''2'' key on the number pad and you should now be able to look straight down through the cylinders out the other side of the engine block, then ''MiddleClick+LeftClick+Drag'' to look at your engine block. To the right you will see what the finished product should look like, notice that I have expanded the tree view on the left to show the individual primitives and have selected ''Cylinder 2'' for examination in the ''Data'' tab of the ''Property View''.<br />
<br />
=== The Key Advantage of Parametric Modeling ===<br />
<br />
Now that we have our cylinders bored out we will take a second to see one of the advantages of this system. Suppose at some point in the development, we find out that we want the cylinders to be a bit bigger. Since the union and intersection operations we performed were recorded as groupings in the tree view, we can change the cylinder size and FreeCAD will just re-run the union and intersection process and arrive at the new engine size. Play around with the radius and position of the two cylinders a bit and then return them to the parameters quoted above, before continuing the tutorial.<br />
<br />
== The Crankcase ==<br />
<br />
=== Billet and Bearing Caps ===<br />
<br />
Next we will work on a crankcase under the engine block. Add a new box, rename it to ''Crankcase Billet'', and give it the following properties:<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 0.0 mm || Height: 85.0 mm<br />
|-<br />
| Y: -50.0 mm || Length: 140.0 mm<br />
|-<br />
| Z: -85.0 mm || Width: 100.0 mm<br />
|-<br />
|}<br />
<br />
In order to tell the crankcase apart from the let's give one of them a different color. You can change color by right clicking on the object to change in the tree view. You can assign a color yourself or give the object a random color (choose random again if you don't like the color). Add another box called ''Bearing carve'', give it the following properties, and then cut the ''Bearing carve'' away from the ''Crankcase Billet'' (i.e. select the billet first):<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 0.0 mm || Height: 30.0 mm<br />
|-<br />
| Y: -40.0 mm || Length: 140.0 mm<br />
|-<br />
| Z: -85.0 mm || Width: 80.0 mm<br />
|-<br />
|}<br />
<br />
Rename the resulting ''Cut'' object to ''Carved crankcase''.<br />
<br />
=== Carving out the journals ===<br />
<br />
Next we will cut out a semi-circular place for the crankshaft to sit and a space in the crankcase for it to spin. We will start with a cylinder, but the orientation of the default cylinder is vertical, whereas we need a horizontal one. This means we need to figure out how to rotate the cylinder to align it properly with our engine. If you look at the guide axis in the bottom right corner of the 3D window you will see we want the crankshaft to lie along the positive x-axis. This means that from its starting location we need to rotate 90 degrees around an axis parallel to the y-axis of the scene. This tells us what we need to enter the parameters for the cylinder. Create a cylinder called ''Cranshaft carve'' and give it these properties (notice that now we have to specify the orientation parameters, as well as the regular dimensions we did for the cylinder bores):<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| Axis X: 0.0 mm || Angle: 90.0 degrees<br />
|-<br />
| Axis Y: 1.0 mm || <br />
|-<br />
| Axis Z: 0.0 mm ||<br />
|-<br />
| Position X: 0.0 mm || Height: 140.0 mm<br />
|-<br />
| Position Y: 0.0 mm || Radius: 20.0 mm<br />
|-<br />
| Position Z: -55.0 mm ||<br />
|-<br />
|}<br />
<br />
Cut the crankshaft carve object away from the ''Carved crankcase'' and rename the resulting object ''Crankcase with journals''.<br />
<br />
=== Finishing out the Crankcase ===<br />
<br />
[[Image: Engine Block Tutorial - Crankcase.png|thumb|right|300px]]<br />
<br />
Lastly we will cut out 2 final boxes so that the piston rods can reach from the crankcase up into the engine block. Make two objects called ''Box carve 1'' and ''Box carve 2'' with the following properties, union them into an object called ''Box carvers'', and cut this object away from the ''Crankcase with journals'', calling the final result ''Crankcase''. Remember, you can hide the ''Bored block'' by selecting it and pushing spacebar so you can see what you are doing; also, you can duplicate ''Box carve 1'' and just change the X coordinate to get the second carver.<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 15.0 mm || Height: 55.0 mm<br />
|-<br />
| Y: -25.0 mm || Length: 50.0 mm<br />
|-<br />
| Z: -55.0 mm || Width: 50.0 mm<br />
|-<br />
|}<br />
<br />
:{| class=wikitable border=1<br />
|-<br />
| X: 75.0 mm || Height: 55.0 mm<br />
|-<br />
| Y: -25.0 mm || Length: 50.0 mm<br />
|-<br />
| Z: -55.0 mm || Width: 50.0 mm<br />
|-<br />
|}<br />
<br />
On the right you can see what the final result should look like. I have fully expanded the tree view so you can see the hierarchy of the boolean operations used to build the device. Remember that you can still dig down into this tree and change cylinder diameters, change the size or position of the crankshaft, etc, without having to rebuild the whole model from scratch. We could continue to carve out the crankcase further but this will be enough for now. Next we will look at using the 2D drafting mode to design the headbolt pattern and cut down on the weight of the engine block by removing much of the unnecessary steel billet that remains around the outside of the cylinders.<br />
<br />
== 2D Drafting the Head Gasket Design ==<br />
<br />
For the head bolts and the shape of the engine block we will be using more boolean operations to "carve" away the parts of the block we don't want. However, if we stop to think about it, every head bolt is going to look the same, it will cut all the way down into the crankcase, the only thing different will be where on the top of the head it is located. This means we can simply "draw" the shape of the head gasket on the top of the engine, and then use that like a pattern to do the carving we want done.<br />
<br />
=== Entering 2D Drafting Mode ===<br />
<br />
First we need to switch to the 2D Drafting workbench, to do this from part mode you can select ''2D Drafting'' from the dropdown box at the top that currently says ''Part''. If you cannot find the dropdown box (not all workbenches show the dropdown) you can also select a workbench from the ''View->Workbench'' menu entry. Even though we are doing 2d drawing, we will draw them in the 3D window by telling FreeCAD what plane we want the drawings projected into. After you have selected the 2D Drafting workbench just above the top-right corner of the 3D view and click on the leftmost button which will say one of the following {none, top, front, size, or d(..., ..., ...)}. Once you click that, the left side of the bar will have a text box for you to enter a plane offset, and 5 buttons: XY, XZ, YZ, View, and None. The first three are the standard top, front, and side views, the ''View'' entry will use the plane perpendicular to the direction the camera is looking (the camera's viewplane), and the last will not project into a plane and let you fully define the XYZ coordinates for every point you draw. We want to set a plane offset of 110 (type it in and press enter) and then click the XY button to project the drawing onto the XY plane, located 110 mm up the Z axis which corresponds to the top of the engine block. Now that we have told FreeCAD what plane to draw in we are ready to start designing the head gasket.<br />
<br />
The last thing to do is set up the 3D view. Even though all the drawings we produce will be projected into our defined 2D plane, we can look at the plane we are drawing on from any angle (including the other side of the plane so we draw "backwards"). Since we have told it the plane is the one co-planar to the top of the engine block, we should probably have the 3D view looking at that, or at least roughly in that direction. Press the 2 key on the number pad to look at the top view (notice that on the num pad, adjacent keys are opposite views so 1 and 4 are front-back, 2 and 5 are top-bottom, and 3 and 6 are front-back). Once you are looking at the engine from the top down, you can center it by dragging the middle mouse button to pan the view. Finally, the 2D drafting mode will allow us to snap parts of the drawing to the corners of the engine block, the center of the cylinders, etc, in order to make this work best we should hide the crankcase so the drawings snap only to the part we are working on (press spacebar to show/hide the selected object).<br />
<br />
=== Laying Out the Head Bolts ===<br />
<br />
Now that the proper plane projection and view is set up we add 2d drawing elements in the same way we added primitives. Click the ''Add Circle'' button ([[Image:Draft_Circle.png|16px]]) and move your mouse around in the 3D view. You then need to tell FreeCAD the XY location for the center of the circle, and the radius, for both of these measurements you can either enter them with the mouse (following the instructions in the bottom left status bar), or you can type in the values in the text entry boxes that appear above the tree view. Go ahead and add a couple random circles on the top of the engine, as well as a few not on the engine, i.e. just out in the empty space surrounding your view of the engine. After you have done this, rotate the camera around the top of the engine block and look at the circles you drew, notice how they are "flat" in the plane we projected them into and this plane lines up with the top of the engine block; this will be important when we extrude the drawing to shape the engine. Now that you see how to add 2D elements you can delete the test circles you added and we will start entering the actual head layout. Note that if your circle disappears inside the engine block, your drawing projection plane is not properly set to XY mode, offset 110 mm.<br />
<br />
Adding drafting elements with the mouse is fast and easy, but it is not very precise. For the actual bolt pattern we use the fact that moving the mouse will update the numbers in the text boxes just above the 3D view so we can see roughly the coordinates of where we want to place things. Once we have these rough coordinates we can type in the real values we want for precise positioning. Reset to the top view of the engine, click the ''Add circle'' button, and move your mouse around the top left corner of the engine block taking not of a good location for the head bolt. It looks like X=10, Y=30, would be a good place for the circle (note the Z coordinate should be grayed out, if it is not you need to set the plane properly like in the previous section, pressing escape will cancel drawing the circle).<br />
<br />
Now that you see how to easily determine the coordinates of drawing elements you can easily design a bolt pattern or other 2 dimensional layout for a part such as fluid channels, circuit-board traces, etc. For our 3 head bolts let's on this side of the engine, let's use the following coordinates. Note that when you are typing in values to the boxes you can press enter to move on to the next box, and it is also a good idea to move your mouse out of the 3D view before you start typing in the coordinates as too much mouse movement will overwrite the numbers you have already entered in the text entry fields. Also, on my system I had trouble with the typed in circles having their Z coordinates set to 12.5 for some reason, if this is a problem for you, you can set the drawing projection plane to ''None'' and then manually enter the Z coordinates for the circles to be 110. Finally, when creating the circles, make sure to check the box labeled ''Filled'' otherwise when we extrude them later they will just create tubes like a toilet paper tube instead of a solid cylinder.<br />
<br />
{| class=wikitable border=1<br />
|-<br />
| X1: 10 || Y1: 25 || Radius: 2.5 mm<br />
|-<br />
| X2: 70 || Y2: 25 || Radius: 2.5 mm<br />
|-<br />
| X3: 130 || Y3: 25 || Radius: 2.5 mm<br />
|}<br />
<br />
Name these circles ''Bolt 1'' through ''Bolt 3''.<br />
<br />
=== The Other Side of the Block ===<br />
<br />
Now that the first three head bolts are in place down one side of the engine we need three more mirrored on the other side, there are three ways we could do this:<br />
<br />
* We could just continue adding circles like we did for the first three and just negate the Y coordinates to put the bolts on the other side of the engine.<br />
<br />
* We could select the three we have added, go to ''Edit->Duplicate Selection'' and then negate the Y coordinates of the three new circles.<br />
<br />
* We could use the mirror functionality in the Part module.<br />
<br />
Since you should already know how to do the first and second way, we will choose the third way for this example model. Each of the three methods has its own advantages and disadvantages, but a good operating rule is that simple models (like this one) probably should use the first or second methods, whereas models with lots of duplication and/or duplication of very complicated shapes/objects should probably use the third method.<br />
<br />
So even though it is a bit of overkill we will mirror these bolts as a demonstration. Switch back to the part workbench (note that you can always switch to the ''Complete'' workbench to see all the tools at once if you would rather not switch back and forth) by going to ''View->Workbench''. Select the three bolt circles in the tree view, and then press the mirror button ([[Image:Part_Mirror.png|16px]]). Once you press the mirror button you should notice a new display called the ''Combo view'' pop up on in the pane underneath the Tree view. Many of the tools need additional input before they can run and the Combo view lets you enter these parameters. You can make the Combo view larger by dragging the divider line separating it from the Property view up or down. Select ''Bolt 1'' from the list on the Combo view and set the ''mirror plane'' to XZ, then press OK (do the same for bolts 2 and 3).<br />
<br />
At this point you should have a basic engine block with the cylinders bored out and the headbolt locations marked.<br />
<br />
=== Cutting Down the Excess Billet Material from the Block ===<br />
<br />
Now that we have holes marked out for headbolts (we could do the same thing for oil channels, water jackets, etc) we will want to "trim" the outside of the block billet down to a more suitable shape. This will make the engine lighter, allow it to cool more easily, mean less steel must be used to cast the block. Like the bolt pattern we will be laying out a 2 dimensional drawing outlining the shape we want on the finished product. We could draw the spline curve directly with the mouse, or use the hybrid approach like we used for the circles where we used the mouse to find approximate coordinates and then typed in the true values we wanted. A more interesting approach is to use the 2D drafting's ''construction mode'' to plot a few guide shapes to help us trace out a nice, symmetric, spline curve by snapping to our constructed guide shapes.<br />
<br />
As a guide we will draw two regular polygons for each cylinder, with the polygons concentric with the cylinder. To begin, switch to the top view of the engine block, hide the crankcase, switch back to the 2D drafting workbench, select the reference plane offset to 110 mm and the XY plane mode (or the ''None'' mode if you prefer), and click the ''Construction mode'' button in the command bar (the construction mode button looks like a trowel and is located just above the top right corner of the 3D view). Construction mode works just like the normal mode except any 2D drawing objects created while in construction mode get drawn in a different color and are automatically put into a separate group in the Tree view, this allows you to hide you guide drawings and leave behind only the real things like bolt hole markings by hiding the construction group, or to delete all of the guide objects by just deleting the group.<br />
<br />
: ''Further reading: [[Draft ConstructionMode | Construction Mode]]''<br />
<br />
Now that your drawing plane is properly set up and you are in construction mode, click the ''Regular Polygon'' button ([[Image:Draft_Polygon.png|16px]]) and move your mouse along the edge of the left cylinder while holding down the CTRL button. You should see that it is snapping a small black dot either to the edge of the cylinder, or to the center of the cylinder, depending on where your mouse is along the circumference. Move so that the black dot snaps to the center of the cylinder and click the left mouse button. This places the center of the polygon at the center of the cylinder, the program prompts us for the number of edges on the polygon and the radius it is inscribed in. Investigating with the mouse a little bit looks like a radius of 30 is good (so type that in) and enter 14 for the number of side, but leave the ''Filled'' box unchecked this time. If you can't get the snap to lock onto the center of the cylinder (I had trouble with mine) you can always enter the coordinates manually (X=40, Y=0, Z=110). Add a second polygon, also centered on the left cylinder but this one should have 22 side and 45 mm radius. Finally add the same two polygons over the right cylinder (centered at X=100, Y=0, Z=110). When you are finished you should have two "figure-8's" surrounding the cylinders and head bolts. (Note that currently the program does not actually prompt you for the number of edges so you will just have to set the center and radius and then change the number of faces in the Property view).<br />
<br />
[[Image: Engine Block Tutorial - Spline.png|thumb|right|300px]]<br />
<br />
Now that we have our guide polygons in place we are ready to draw in the spline curve defining the outside shape of the engine block. Since this curve will be part of the final object you can turn off construction mode by clicking the same button you pressed to turn it on. Now click the ''Add BSpline'' button ([[Image:Draft_BSpline.png|16px]]) and start drawing the BSpline by ''CTRL+left clicking'' on each place you want to add a control point for the spline curve. You will want your first control point to be on the leftmost point of the inner guide polygon for the left cylinder. Continue adding control points all along the spline curve until you click on the last point ''before'' the one you started drawing, then click the ''Close'' button up where you typed in the position and radius for the 2D circles we drew for the headbolts. Clicking this close button finished drawing control points for the spline curve and joins the ends together to form a closed loop. It is very important that you properly close loops like this if you plan to extrude them into solid objects like we will be with this one. For open spline curves you can just click the ''Finish'' button instead of the Close button when you are finished drawing. To the right you can see what you finished spline curve should look like just before you press the close button (notice I have drawn all but the last line segment and my mouse pointer is just about to click the ''Close'' button to finish the spline curve). Also notice that I have checked the ''Filled'' box so the resulting spline curve will form a solid sheet, rather than just an empty ring, this must be done to extrude it into a solid shape that is capped on the ends.<br />
<br />
[[Image: Engine Block Tutorial - Spline Edit Mode.png|thumb|right|300px]]<br />
<br />
The control points are not shown in that picture so I have added a second screenshot showing the finished spline in edit mode (click the ''Edit mode'' button to turn editing on or off for the selected object, make sure to turn it off when you are done editing it or just skip over this step if you are satisfied with your engine block shape). Also, note that there is a discontinuity on the leftmost edge of the spline curve, even though it is closed properly, this is a bug in the program behavior and is currently being fixed, as a result your spline curve may look slightly different if you are running a newer version of the software than is available at this time.<br />
<br />
=== Extruding the 2D Head Design into our 3D Model to Finish the Design ===<br />
<br />
Now we are closing in on the final design of the engine. Return to the Part workbench and click the ''Extrude sketch'' button ([[Image:Part_Extrude.png|16px]]). In the combo box that pops up, use ''CTRL+LeftClick'' to select the 6 head bolts and the spline curve for extrusion. The default direction is the positive Z axis, we want the negative Z axis to extrude the head design "down" and into the engine block so set the direction to X=0, Y=0 and Z=-1, then type in 110 for the length (the height of the engine block). After you get all the values entered and click OK the circles for the bolts will be extruded downward to for cylinders and the spline will be extruded downward to produce a sort of cylinder with "rippled" edges. Select and hide the ''Bored block'' so you can see the extruded spline, then hide that object so you can see the 6 head bolt cylinders. You see that very sophisticated 3D shapes can be made by starting with a 2D drawing and extruding parts of it downward. We could even extrude different parts of the drawing by different amounts to do things like bore in bolt holes that just go part way through the block, but cut separate water jackets that go all the way through. At this point all your extruded objects are just named "Extrude001..." so you will want to go through and name each of them so you can identify them in the next section (I will name mine ''Head bolt bore 1'' though ''6'' and name the spline ''Extruded spline'', I suggest using the same names in your model as well). Now that you have your extruded shapes it is just a few boolean operations now to produce the final block design. Go through and show the major components (the ''Bored block'' and the ''Crankcase''), and all your newly created extruded objects.<br />
<br />
[[Image:Engine Block Tutorial - Finished Engine Block.png|thumb|right|300px]]<br />
<br />
Now that we have 3D objects for the bore holes and the outer shape, we can use a few boolean operations to stitch the whole thing together. Select your 6 extruded head bolts in the tree view and join them into a union (name the resulting object ''Head bolt boreholes''). Then select the ''Bored block'' and the ''Head bolt boreholes'' in that order and perform a cut (like you did when you bored out the cylinders), name the resulting ''Cut'' object ''Block with headbolts''. Finally, select the ''Block with headbolts'' and the ''Extruded spline'' and press the ''Make intersection'' button ([[Image:Part_Common.png|16px]]), and name the resulting object ''Engine block''. Your final object should look like the picture on the right.<br />
<br />
{{languages | {{es|Engine_Block_Tutorial/es}} {{it|Engine_Block_Tutorial/it}} }}<br />
<br />
[[Category:Tutorials]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Basic_modeling_tutorial&diff=14832Basic modeling tutorial2012-11-25T06:06:56Z<p>Htsubota: /* 2nd Method - By extruding a profile */</p>
<hr />
<div>This Basic Modeling Tutorial will show you how to model an iron angle. One thing to know is that FreeCAD is modular by design, and like for many other CAD software, there are always more than one way to do things. We will explore two methods here.<br />
<br />
== Before we begin ==<br />
<br />
Keep in mind that FreeCAD is still in an early stage of development, so you might not be as productive as with another CAD application, and you will certainly encounter bugs, or experience crashes. FreeCAD now has the ability to save backup files. The number of those backup files can be specified in the preferences dialog. Don't hesitate to allow 2 or 3 backup files until you know well how to deal with FreeCAD.<br />
<br />
Save your work often, from time to time save your work under a different name, so you have a "safe" copy to fall back to, and be prepared to the possibilty that some commands might not give you the expected results. <br />
<br />
== Modeling Techniques Intro ==<br />
<br />
The first (and basic) technique of solid modeling is [http://en.wikipedia.org/wiki/Constructive_solid_geometry Constructive Solid Geometry (CSG)]. You work with primitive shapes like cubes, cylinders, spheres and cones to construct your geometry by combining them, subtracting one shape from the other, or intersecting them. These tools are part of the [[Part Workbench]]. You can also apply transformations on shapes, like applying rounds or chamfers on edges. These tools are also in the [[Part Workbench]].<br />
<br />
Then there are more advanced tools. You start by drawing a 2D profile which you'll either extrude or revolve.<br />
<br />
So let's start by trying to do some iron feet for a table with these 2 methods.<br />
<br />
== 1st Method - By Constructive Solid Geometry ==<br />
<br />
* Start with the [[Part Workbench]] ('''View > Workbench > Part''' menu)<br />
* Click on the [[Image:Part_Box.png|32px]] [[Part_Box|Box]] button to create a box<br />
* Change its dimensions by selecting it either in the 3D space, or by clicking it in the Project tab to the left, then<br />
* Click on the Data tab at the bottom, and change values for Height, Length and Width to 750mm, 50 and 50 ''(see Fig. 1.1)''<br />
* Create a second box the same way, but with values 750, 40 and 40mm. By default this box will be superimposed on the first one. ''(see Fig. 1.2)''<br />
* You'll now subtract the second box from the first. Select the first shape first (named Box), then the second one (named Box001), the selection order is important! (Make sure that both shapes are selected in the Project tree. One thing to remember: in Inventor navigation mode, Ctrl + click does not work for multiple selection. [[Mouse_Model|Switch]] to either CAD or Blender selection.)<br />
* On the Part Workbench toolbar, click on the [[Image:Part_Cut.png|32px]] [[Part_Cut|Cut]] tool.<br />
<br />
[[Image:Tutorial-normand01.jpg|center|frame|Fig. 1.1 The first box]]<br />
<br />
[[Image:Tutorial-normand02.jpg|center|frame|Fig. 1.2 The second box on top of the first one, ready to be subtracted]]<br />
<br />
[[Image:Tutorial-normand03.jpg|center|frame|Fig. 1.3 After the subtraction]]<br />
<br />
You now have your first iron angle ''(Fig. 1.3)''. You'll notice that, in the Project tab on the left, both boxes have been replaced by a "Cut" object. Actually, they're not disappeared, but rather grouped under the Cut object. Click on the + in front of it, and you'll see that both boxes are still there, but greyed out ''(Fig. 1.4)''. If you click on either of them and hit the space bar, it will show up. The space bar toggles visibility of selected objects. ''(Fig. 1.5)''<br />
<br />
Don't want the angle oriented that way? You just need to change the placement of the Box001 shape. Select it, unhide it, and in the Data tab, click on the + in front of Placement, then deploy the Position, and change its X and Y coordinates. Hit Enter, hide the Box001 shape again, and your angle orientation is now different. ''(Fig. 1.5)'' You can even change either of your shapes dimensions, and the Cut object will be updated.<br />
<br />
[[Image:Tutorial-normand04.jpg|center|frame|Fig. 1.4 The cut operation retains its original objects (the boxes)]]<br />
<br />
[[Image:Tutorial-normand05.jpg|center|frame|Fig. 1.5 You can still make the original boxes visible]]<br />
<br />
By the way, we can add rounds to the angle so it is more realistic, using the [[Image:Part_Fillet.png|32px]] [[Part_Fillet|Fillet]] tool. ''(Fig. 1.6)''<br />
<br />
[[Image:Tutorial-normand06.jpg|center|frame|Fig. 1.6 The filleted edges]]<br />
<br />
== 2nd Method - By extruding a profile ==<br />
<br />
This method requires that you start by drawing a 2D profile. You need to activate the [[Draft Workbench|2d Drafting workbench]] ('''View > Workbench > 2d Draft''' menu).<br />
<br />
Next we need to set the working plane. Depending on your FreeCAD version, you'll have right under the toolbar, on the right, a "None" button. Click it, and on the left will appear right after "active command": Select Plane Offset, then a text field and a series of buttons. Assuming you want to start your profile on the plan view, select XY. The "None" button will now show "Top" as active plane.<br />
<br />
Select the [[Image:Draft_Wire.png]] [[Draft_Wire|Wire (multiple-point line)]] tool, then start drawing a shape, using the text fields for X and Y positions. The "Relative" box should be checked, as well as the "Filled" box.<br />
<br />
* 1st point: 0,0<br />
* 2nd point: 50,0<br />
* 3rd point: 0,10<br />
* 4th point: -40,0<br />
* 5th point: 0,40<br />
* 6th point: -10,0<br />
* No 7th point, rather click on the "Close" button to close the profile. You should now have this profile, titled "Wire" in the Project tab:<br />
<br />
[[Image:Tutorial-normand07.jpg|center|frame|Fig. 1.7 The base wire]] <br />
<br />
Hit the zero key on the numpad to set the view to axonometric.<br />
<br />
Activate the [[Part Workbench]].<br />
<br />
Click on the [[Image:Part_Extrude.png|32px]] [[Part_Extrude|Extrude]] tool.<br />
<br />
On the Tasks tab on the left, select the '''Wire''' object. Then enter the desired length, say 750mm. Leave the direction at Z. Click Apply. You should now have an '''Extrude''' object in the Project tab ''(fig. 1.8)''<br />
<br />
[[Image:Tutorial-normand08.jpg|center|frame|Fig. 1.8 The extruded object]]<br />
<br />
This method has a minor caveat compared to the other one: to edit the shape, you need to edit the Wire, it's not as easy to do as the previous method.<br />
<br />
And there are a few other ways to do it too! I hope these two examples get you started. You'll sure hit some snags along the way (I did when I first learned FreeCAD, and I do have 3D CAD experience ;) ), but don't hesitate to ask questions on the [http://sourceforge.net/apps/phpbb/free-cad FreeCAD forum]!<br />
<br />
{{languages | {{es|Basic modeling tutorial/es}} {{fr|Basic modeling tutorial/fr}} {{it|Basic modeling tutorial/it}} }}<br />
<br />
[[Category:Tutorials]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Video_tutorials/it&diff=14580Video tutorials/it2012-11-17T14:08:39Z<p>Htsubota: </p>
<hr />
<div>=Video guide a FreeCAD=<br />
<br />
Una raccolta di guide video realizzate dagli utenti FreeCAD:<br />
<br />
* Tutorial de FreeCAD - Introduzione all'ambiente Schizzo: http://www.youtube.com/watch?v=rT6pJKAzaWw<br />
* FreeCAD - CAD 3D free multipiattaforma: http://www.youtube.com/watch?v=LOAxc1StGW8<br />
* FreeCAD - Disegni 2D da modelli 3D: http://www.youtube.com/watch?v=GFuyF78QLGc<br />
* CAO-Free-Cad-: Il modulo Parte: http://www.youtube.com/watch?v=bHz7y-tH8CU<br />
* FreeCAD (0.11.3520): Creare un "fungo": http://www.youtube.com/watch?v=hyBlOL_MFlY<br />
* FreeCAD: Le potenzialità di Python - creare una matrice : http://www.youtube.com/watch?v=xnlEVKAtFYw<br />
* FreeCAD: Anteprima di Schizzo: http://www.youtube.com/watch?v=hvXupH5bA0E<br />
* openPLM demo : L'interfaccia di FreeCAD: http://www.youtube.com/watch?v=SanPyZhLq6w<br />
* FreeCad- Il modulo Draft: http://www.youtube.com/watch?v=Q7cG-LQK8Ps<br />
* FreeCAD: BSpline modalità di modifica + Estrusione: http://www.youtube.com/watch?v=bD3OWgSC5y0<br />
* FreeCAD Demo di Schizzo e Parte: http://www.youtube.com/watch?v=7ih9Jp3OAwA<br />
* CAO-Qcad-Freecad-Quasiturbine : http://www.youtube.com/watch?v=Wavr1qF309c<br />
<br />
* FreeCAD - [[Tutorial Mouse Interaction/it|Guida alle interazioni del mouse]]<br />
* FreeCAD: modellazione di Parte da esercitazione Autocad 3D: http://www.youtube.com/watch?v=6RxHCR7TLtI<br />
* FreeCAD: Schizzo, Parte, Disegni 2D da modelli 3D: http://www.youtube.com/watch?v=ib72_bT6O5Q<br />
* Guida per principianti parte 1: http://www.youtube.com/watch?v=_VR_XOPcaVw<br />
<br />
{{languages/it | {{en|Video_tutorials}} {{es|Video_tutorials/es}} }}<br />
<br />
[[Category:Tutorials/it]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Installing_on_Mac&diff=14055Installing on Mac2012-11-03T16:27:20Z<p>Htsubota: </p>
<hr />
<div>FreeCAD can be installed on Mac OS X in one step using the Installer. <br><br />
{{DownloadMacStable}}<br><br />
This page describes the usage and features of the FreeCAD installer. It also includes uninstallation instructions.<br />
Once installed, you can [[Getting started |get started]]!<br />
<br />
=== Simple Installation ===<br />
The FreeCAD installer is provided as a Installer package (.mpkg) enclosed in a disk image file.<br />
<br />
You can download the latest installer from the [[Download]] page. After downloading the file, just mount the disk image, then run the '''Install FreeCAD''' package.<br />
<br />
[[File:mac_installer_1.png]]<br />
<br />
The installer will present you with a '''Customize Installation''' screen that lists the packages that will be installed. If you know that you already have any of these packages, you can deselect them using the checkboxes. If you're not sure, just leave all items checked.<br />
<br />
[[File:mac_installer_2.png]]<br />
<br />
=== Uninstallation ===<br />
<br />
There currently isn't an uninstaller for FreeCAD. To completely remove FreeCAD and all installed components, drag the following files and folders to the Trash:<br />
<br />
*In /Applications:<br />
**FreeCAD<br />
<br />
*in /Library/Frameworks/<br />
**SoQt.framework<br />
**Inventor.framework<br />
<br />
Then, from the terminal, run:<br />
<br />
sudo /Developer/Tools/uninstall-qt.py<br />
sudo rm -R /usr/local/lib/OCC<br />
sudo rm -R /usr/local/include/OCC<br />
<br />
That's it. Eventually, FreeCAD will be available as a self-contained application bundle so all this hassle will go away.<br />
<br />
{{docnav|Install on Unix|Getting started}}<br />
<br />
{{Languages | {{cn|Install on Mac/cn}} {{de|Install on Mac/de}} {{es|Install on Mac/es}} {{fr|Install on Mac/fr}} {{it|Install on Mac/it}} {{jp|Install on Mac/jp}} {{pl|Install on Mac/pl}} {{ru|Install on Mac/ru}} {{se|Install on Mac/se}} }}<br />
<br />
[[Category:User Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Installing_on_Windows&diff=14053Installing on Windows2012-11-03T16:24:47Z<p>Htsubota: </p>
<hr />
<div>The easiest way to install FreeCAD on Windows is to download the installer below. <br><br />
{{DownloadWindowsStable}}<br />
<br />
After downloading the .msi (Microsoft Installer) file, just double-click on it to start the installation process.<br />
<br />
Below is more information about technical options. If it looks daunting, don't worry! Most Windows users will not need anything more than the .msi to install FreeCAD and '''[[Getting started | Get started]]'''!<br />
<br />
<br />
=== Simple Microsoft Installer Installation ===<br />
The easiest way to '''install FreeCAD on Windows''' is by using the installer above. This page describes the usage and the features of the ''Microsoft Installer'' for more installation options.<br />
<br />
If you would like to download either a 64 bit or unstable development version, see the [[Download]] page.<br />
<br />
<br />
=== Command Line Installation ===<br />
With the ''msiexec.exe'' command line utility, additional features are available, like non-interactive installation and administrative installation.<br />
<br />
==== Non-interactive Installation ====<br />
With the command line<br />
<br />
msiexec /i FreeCAD<version>.msi<br />
<br />
installation can be initiated programmatically. Additional parameters can be passed at the end of this command line, like<br />
<br />
msiexec /i FreeCAD-2.5.msi TARGETDIR=r:\FreeCAD25<br />
<br />
==== Limited user interface ====<br />
The amount of user interface that installer displays can be controlled with /q options, in particular:<br />
<br />
* /qn - No interface<br />
* /qb - Basic interface - just a small progress dialog<br />
* /qb! - Like /qb, but hide the Cancel button<br />
* /qr - Reduced interface - display all dialogs that don't require user interaction (skip all modal dialogs)<br />
* /qn+ - Like /qn, but display "Completed" dialog at the end<br />
* /qb+ - Like /qb, but display "Completed" dialog at the end <br />
<br />
==== Target directory ====<br />
The property TARGETDIR determines the root directory of the FreeCAD installation. For example, a different installation drive can be specified with<br />
<br />
TARGETDIR=R:\FreeCAD25<br />
<br />
The default TARGETDIR is [WindowsVolume\Programm Files\]FreeCAD<version>.<br />
<br />
==== Installation for All Users ====<br />
Adding<br />
<br />
ALLUSERS=1<br />
<br />
causes an installation for all users. By default, the non-interactive installation install the package just for the current user, and the interactive installation offers a dialog which defaults to "all users" if the user is sufficiently privileged.<br />
<br />
==== Feature Selection ====<br />
A number of properties allow selection of features to be installed, reinstalled, or removed. The set of features for the FreeCAD installer is<br />
<br />
* DefaultFeature - install the software proper, plus the core libraries<br />
* Documentation - install documentation<br />
* Source code - install the sources <br />
* ... ToDo<br />
<br />
In addition, ALL specifies all features. All features depend on DefaultFeature, so installing any feature automatically installs the default feature as well. The following properties control features to be installed or removed<br />
<br />
* ADDLOCAL - list of feature to be installed on the local machine<br />
* REMOVE - list of features to be removed<br />
* ADDDEFAULT - list of features added in their default configuration (which is local for all FreeCAD features)<br />
* REINSTALL - list of features to be reinstalled/repaired<br />
* ADVERTISE - list of feature for which to perform an advertise installation <br />
<br />
There are a few additional properties available; see the MSDN documentation for details.<br />
<br />
With these options, adding<br />
<br />
ADDLOCAL=Extensions<br />
<br />
installs the interpreter itself and registers the extensions, but does not install anything else.<br />
<br />
=== Uninstallation ===<br />
With<br />
<br />
msiexec /x FreeCAD<version>.msi<br />
<br />
FreeCAD can be uninstalled. It is not necessary to have the MSI file available for uninstallation; alternatively, the package or product code can also be specified. You can find the product code by looking at the properties of the Uninstall shortcut that FreeCAD installs in the start menu.<br />
<br />
=== Administrative installation ===<br />
With<br />
<br />
msiexec /a FreeCAD<version>.msi<br />
<br />
an "administrative" (network) installation can be initiated. The files get unpacked into the target directory (which should be a network directory), but no other modification is made to the local system. In addition, another (smaller) msi file is generated in the target directory, which clients can then use to perform a local installation (future versions may also offer to keep some features on the network drive altogether).<br />
<br />
Currently, there is no user interface for administrative installations, so the target directory must be passed on the command line.<br />
<br />
There is no specific uninstall procedure for an administrative install - just delete the target directory if no client uses it anymore.<br />
<br />
=== Advertisement ===<br />
With<br />
<br />
msiexec /jm FreeCAD<version>.msi<br />
<br />
it would be possible, in principle, to "advertise" FreeCAD to a machine (with /ju to a user). This would cause the icons to appear in the start menu, and the extensions to become registered, without the software actually being installed. The first usage of a feature would cause that feature to be installed.<br />
<br />
The FreeCAD installer currently supports just advertisement of start menu entries, but no advertisement of shortcuts.<br />
<br />
=== Automatic Installation on a Group of Machines ===<br />
With Windows Group Policy, it is possible to automatically install FreeCAD an a group of machines. To do so, perform the following steps:<br />
#Log on to the domain controller<br />
#Copy the MSI file into a folder that is shared with access granted to all target machines.<br />
#Open the MMC snapin "Active Directory users and computers"<br />
#Navigate to the group of computers that need FreeCAD<br />
#Open Properties<br />
#Open Group Policies<br />
#Add a new policy, and edit it<br />
#In Computer Configuration/Software Installation, choose New/Package<br />
#Select the MSI file through the network path<br />
#Optionally, select that you want the FreeCAD to be deinstalled if the computer leaves the scope of the policy. <br />
<br />
Group policy propagation typically takes some time - to reliably deploy the package, all machines should be rebooted.<br />
<br />
=== Installation on Linux using Crossover Office ===<br />
<br />
You can install the windows version of FreeCAD on a Linux system using ''CXOffice 5.0.1''. Run ''msiexec'' from the CXOffice command line, assuming that the install package is placed in the "software" directory which is mapped to the drive letter "Y:":<br />
msiexec /i Y:\\software\\FreeCAD<version>.msi<br />
FreeCAD is running, but it has been reported that the OpenGL display does not work, like with other programs running under [[wikipedia:Wine (software)|Wine]] i.e. Google [[wikipedia:SketchUp|SketchUp]].<br />
<br />
{{docnav|Feature list|Install on Unix}}<br />
<br />
{{Languages | {{cn|Install_on_Windows/cn}} {{de|Install_on_Windows/de}} {{es|Install_on_Windows/es}} {{fr|Install_on_Windows/fr}} {{it|Install_on_Windows/it}} {{jp|Install_on_Windows/jp}} {{pl|Install_on_Windows/pl}} {{ru|Install_on_Windows/ru}} {{se|Install_on_Windows/se}} }}<br />
<br />
[[Category:User Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Feature_list&diff=14051Feature list2012-11-03T16:21:59Z<p>Htsubota: </p>
<hr />
<div>This is an extensive, hence not complete, list of features FreeCAD implements. If you want to look into the future see the [[Development roadmap]] for a quick overview the [[Screenshots]] are a nice place to go. <br />
<br />
== Release notes ==<br />
<br />
* [[Release notes 011|Release 0.11]]<br />
<br />
== General features ==<br />
<br />
=== Base application ===<br />
<br />
[[Image:Freecad09-thumbnail.jpg|300px|right]]<br />
<br />
*'''FreeCAD is multi-platform'''. It runs and behaves exactly the same way on Windows Linux and Mac OSX platforms.<br />
<br />
* '''FreeCAD is a full GUI application'''. FreeCAD has a complete Graphical User Interface based on the famous [http://www.qtsoftware.com/ Qt] framework, with a 3D viewer based on [http://en.wikipedia.org/wiki/Open_Inventor Open Inventor], allowing fast rendering of 3D scenes and a very accessible scene graph representation.<br />
<br />
* '''FreeCAD also runs as a command line application''', with low memory footprint. In command line mode, FreeCAD runs without its interface, but with all its geometry tools. It can be, for example, used as server to produce content for other applications.<br />
<br />
* '''FreeCAD can be imported as a [[Embedding FreeCAD|Python module]]''', inside other applications that can run python scripts, or in a python console. Like in console mode, the interface part of FreeCAD is unavailable, but all geometry tools are accessible.<br />
<br />
* '''Plugin/Module framework for late loading of features/data-types'''. FreeCAD is divided into a core application and modules, that are loaded only when needed. Almost all the tools and geometry types are stored in modules. Modules behave like plugins, and can be added or removed to an existing installation of FreeCAD.<br />
<br />
* '''Built-in [[Scripting|scripting]] framework''': FreeCAD features a built-in [http://www.python.org/ Python] interpreter, and an API that covers almost any part of the application, the interface, the geometry and the representation of this geometry in the 3D viewer. The interpreter can run single commands up to complex scripts, in fact entire modules can even be programmed completely in Python.<br />
<br />
* '''a modular MSI installer''' allows flexible installations on Windows systems. Packages for Ubuntu systems are also maintained.<br />
<br />
=== Document structure ===<br />
<br />
[[Image:Freecad-vista01.jpg|300px|right]]<br />
<br />
* '''Undo/Redo framework''': Everything is undo/redoable, with access to the undo stack, so multiple steps can be undone at a time.<br />
<br />
* '''Transaction management''': The undo/redo stack stores document transactions and not single actions, allowing each tool to define exactly what must be undone or redone.<br />
<br />
* '''Parametric associative document objects''': All objects in a FreeCAD document can be defined by parameters. Those parameters can be modified on the fly, and recomputed anytime. The relationship between objects is also stored, so modifying one object also modifies its dependent objects.<br />
<br />
* '''Compound (ZIP based) document save format''': FreeCAD documents saved with .[[fcstd file format|fcstd]] extension can contain many different types of information, such as geometry, scripts or thumbnail icons.<br />
<br />
=== User Interface ===<br />
<br />
* '''Fully customizable/scriptable Graphical User Interface'''. The [http://www.qtsoftware.com Qt]-based interface of FreeCAD is entirely accessible via the python interpreter. Aside from the simple functions that FreeCAD itself provides to workbenches, the whole Qt framework is accessible too, allowing any operation on the GUI, such as creating, adding, docking, modifying or removing widgets and toolbars.<br />
<br />
* '''Workbench concept''': In the FreeCAD interface, tools are grouped by [[workbenches]]. This allows to display only the tools used to accomplish a certain task, keeping the workspace uncluttered and responsive, and the application fast to load.<br />
<br />
* '''Built-in Python console''' with syntax highlighting, autocomplete and class browser: Python commands can be issued directly in FreeCAD and immediately return results, permitting scriptwriters to test functionality on the fly, explore the contents of the modules and easily learn about FreeCAD internals.<br />
<br />
* '''User interaction mirroring on the console''': Everything the user does in the FreeCAD interface executes python code, which can be printed on the console and recorded in macros.<br />
<br />
* '''Full macro recording & editing''': The python commands issued when the user manipulates the interface can then be recorded, edited if needed, and saved to be reproduced later.<br />
<br />
* '''Thumbnailer''' (Linux systems only at the moment): The FreeCAD document icons show the contents of the file in most file manager applications such as gnome's nautilus.<br />
<br />
== Application specific features ==<br />
<br />
The functionality of FreeCAD is separated in modules, each one dealing with special data types and applications:<br />
<br />
===[[Image:Workbench_Mesh.png]] [[Mesh Module|Meshes]] ===<br />
<br />
[[Image:Screenshot_mesh.jpg|300px|right]]<br />
<br />
* The [[Mesh Module]] deals with 3D meshes. It is intented primarily for import, healing and conversion of third-party generated mesh geometry into FreeCAD, and export of FreeCAD geometry into mesh formats. But FreeCAD itself also features much more advanced geometry types than meshes.<br />
<br />
* '''Primitive creation''' (box, sphere, cylinder, etc), '''offset''' (trivial or after Jung/Shin/Choi) or '''boolean operations''' (add, cut, intersect)<br />
<br />
* '''Import''' of the following formats: ASCII or binary [http://en.wikipedia.org/wiki/STL_%28file_format%29 STL (Stereo lithography format)] ('''*.stl, *.ast'''), the [http://en.wikipedia.org/wiki/Obj OBJ format] ('''*.obj'''), limited [http://en.wikipedia.org/wiki/NASTRAN NASTRAN] support ('''*.nas'''), [http://en.wikipedia.org/wiki/Open_Inventor Open Inventor] meshes ('''*.iv'''), and FreeCAD native mesh kernel ('''*.bms''')<br />
<br />
* '''Export''' of the following formats: ASCII or binary [http://en.wikipedia.org/wiki/STL_%28file_format%29 STL (Stereo lithography format)] ('''*.stl, *.ast'''), the [http://en.wikipedia.org/wiki/Obj OBJ format] ('''*.obj'''), limited [http://en.wikipedia.org/wiki/NASTRAN NASTRAN] support ('''*.nas, *.brl'''), [http://en.wikipedia.org/wiki/VRML VRML] meshes ('''*.wrl'''), FreeCAD native mesh kernel ('''*.bms'''), mesh as Python module ('''*.py''')<br />
<br />
* '''Testing and repairing''' tools for meshes: solid test, non-two-manifolds test, self-intersection test, hole filling and uniform orientation.<br />
<br />
* '''Extensive [[Mesh Scripting|Python scripting API]]'''.<br />
<br />
===[[Image:Workbench_Draft.png]] [[Draft Module|2D Drafting]] ===<br />
<br />
* Graphical creation of '''simple planar geometry''' like lines, wires, rectangles, arcs or circles in any plane of the 3D space<br />
<br />
* '''Annotations''' like texts or dimensions<br />
<br />
* Graphical '''modification operations''' like translation, rotation, scaling, mirroring, offset or shape conversion, in any plane of the 3D space<br />
<br />
* '''Import''' and '''Export''' of the following formats: Autodesk's Drawing Exchange Format ('''*.dxf'''), Open Cad Format ('''*.oca, *.gcad''') e SVG ('''*.svg''')<br />
<br />
===[[Image:Workbench_Part.png]] [[Part Module|CAD]] ===<br />
<br />
[[Image:Part_BooleanOperations.png|300px|right|An example of union, intersection and difference]]<br />
<br />
* The [[Part Module]] deals with everything around CAD modeling and the CAD data structures. The CAD functionality is under heavy development (see the [[PartDesign_project]] and [[Assembly_project]] in the [[Development_roadmap]]). The [[Part Module]] works with high-level [http://en.wikipedia.org/wiki/Open_CASCADE Open CASCADE] geometry.<br />
<br />
* '''Parametric primitive shapes''' like box, sphere, cylinder, cone or torus.<br />
<br />
* Topological components like '''vertices, edges, wires''' and '''planes''' (via python scripting).<br />
<br />
* Modeling with straight or revolution '''extrusions''', '''sections''' and '''fillets'''.<br />
<br />
* '''[http://en.wikipedia.org/wiki/Constructive_solid_geometry Boolean operations]''' like '''union''', '''difference''' and '''intersection'''.<br />
<br />
* '''Extensive [[Topological_data_scripting|Python scripting API]]'''.<br />
<br />
* '''Import''' and '''Export''' of the following formats: [http://en.wikipedia.org/wiki/Standard_for_the_Exchange_of_Product_model_data STEP] parts and assemblies ('''*.stp,*.step'''), [http://en.wikipedia.org/wiki/IGES IGES] models ('''*.igs, *.iges''') and BRep ('''*.brp'''), the native format of our [http://en.wikipedia.org/wiki/Open_CASCADE Open CASCADE] CAD kernel.<br />
<br />
=== [[Raytracing Module|Raytracing]] ===<br />
<br />
* The [[Raytracing Module]] permits the export of FreeCAD geometry to '''external renderers''' for generation of high-quality images. Currently, the only supported render engine is [http://en.wikipedia.org/wiki/POV-Ray POV-Ray]. The module currently permits the creation of a render sheet, and adding geometry to that render sheet for export to a POV-Ray file.<br />
<br />
=== [[Drawing Module|Drawing]] ===<br />
<br />
* The [[Drawing Module]] allows to export projected views of your 3D geometry to a '''2D SVG document'''. It allows the creation of a 2D sheet with an existing svg template, and the insertion of projected views of your geometry in that sheet. Then the sheet can be saved as a SVG file.<br />
<br />
=== [[Cam Module|CAM]] ===<br />
<br />
* The [[Cam Module]] is dedicated to mechanical machining like milling. This module is at the very beginning and at the moment mostly dedicated to [http://en.wikipedia.org/wiki/Incremental_sheet_forming Incremental Sheet Forming]. Although there are some algorithms for toolpath planing they are not usable for the end-user at the moment.<br />
<br />
<br />
{{docnav|About FreeCAD|Install on Windows}}<br />
<br />
{{languages | {{cn|Feature list/cn}} {{de|Feature list/de}} {{es|Feature list/es}} {{fr|Feature list/fr}} {{it|Feature list/it}} {{jp|Feature list/jp}} {{pl|Feature list/pl}} {{ru|Feature list/ru}} {{se|Feature list/se}} {{tr|Feature list/tr}} }}<br />
<br />
[[Category:User Documentation]]</div>Htsubotahttps://wiki.freecad.org/index.php?title=Robot_Workbench&diff=14050Robot Workbench2012-11-03T16:16:52Z<p>Htsubota: </p>
<hr />
<div>[[Image:KukaKR16FreeCAD.jpg|right|400px]]<br />
<br />
The robot workbench is a tool to simulate industrial grade [[6-Axis Robot]]s, like e.g. [http://kuka.com/ Kuka].<br />
You can do following tasks:<br />
* set up a simulation environment with a robot and work pieces<br />
* create and fill up trajectories<br />
* decompose features of an CAD part to a trajectory<br />
* simulate the robot movement and reachability <br />
* export the trajectory to a robot program file<br />
<br />
An examples you can find here:<br />
[http://www.freecad-project.de/svn/ExampleData/Examples/RobotSimulation/ Example files] or try <br />
the [[Robot tutorial]].<br />
<br />
== Tools ==<br />
Here the principal commands you can use to create a robot set-up. <br />
=== Robots ===<br />
The tools to create and manage the 6-Axis robots<br />
<br />
* [[Image:Robot_CreateRobot.png|30px]] [[Robot_CreateRobot|Create a robot]]: Insert a new robot into the scene<br />
* [[Image:Robot_Simulate.png|30px]] [[Robot_Simulate|Simulate a trajectory]]: Opens the simulation dialog and let you simulate <br />
* [[Image:Robot_Export.png|30px]] [[Robot_Export|Export a trajectory]]: Export a robot program file<br />
<br />
* [[Image:Robot_SetHomePos.png|30px]] [[Robot_SetHomePos|Set home positon]]: Set the home position of an robot<br />
* [[Image:Robot_RestoreHomePos.png|30px]] [[Robot_RestoreHomePos|Restore home positon]]: move the robot to its home position<br />
<br />
=== Trajectories ===<br />
Tools to creat and manipulate trajectories. There are two kinds, the parametric and non parametric ones.<br />
==== non parametric ====<br />
* [[Image:Robot_CreateTrajectory.png|30px]] [[Robot_CreateTrajectory|Create a trajectory]]: Insert a new robot into the scene<br />
* [[Image:Robot_SetDefaultOrientation.png|30px]] [[Robot_SetDefaultOrientation|Set the default orientation]]: Set the orientation way-points gets created by default<br />
* [[Image:Robot_SetDefaultValues.png|30px]] [[Robot_SetDefaultValues|Set the default speed parameter]]: set the defaults for way-point creation<br />
* [[Image:Robot_InsertWaypoint.png|30px]] [[Robot_InsertWaypoint|Insert a waypoint]]: Insert a way-point from the current robot position into a trajectory<br />
* [[Image:Robot_InsertWaypointPre.png|30px]] [[Robot_InsertWaypointPre|Insert a waypoint]]: Insert a way-point from the current mouse position into a trajectory<br />
<br />
==== parametric ====<br />
* [[Image:Robot_Edge2Trac.png|30px]] [[Robot_Edge2Trac|Create a trajectory out of edges]]: Insert a new object which decompose edges to a trajectory<br />
* [[Image:Robot_TrajectoryDressUp.png|30px]] [[Robot_TrajectoryDressUp|Dress-up a trajectory]]: Let you override one or more properties of a trajectory<br />
* [[Image:Robot_TrajectoryCompound.png|30px]] [[Robot_TrajectoryCompound|Trajectory compound]]: create a compound out of some single trajectories<br />
<br />
== Scripting ==<br />
<br />
This section is generated out of: http://free-cad.svn.sourceforge.net/viewvc/free-cad/trunk/src/Mod/Robot/RobotExample.py?view=markup <br />
You can use this file directly if you want.<br />
<br />
Example how to use the basic robot class Robot6Axis which represents a 6-axis <br />
industrial robot. The Robot module is dependent on Part but not on other modules.<br />
It works mostly with the basic types Placement, Vector and Matrix. So we need <br />
only:<br />
from Robot import *<br />
from Part import *<br />
from FreeCAD import *<br />
<br />
=== Basic robot stuff ===<br />
create the robot. If you do not specify another kinematic it becomes a Puma 560<br />
rob = Robot6Axis()<br />
print rob<br />
<br />
accessing the axis and the Tcp. Axes go from 1-6 and are in degree:<br />
Start = rob.Tcp<br />
print Start<br />
print rob.Axis1<br />
<br />
move the first axis of the robot:<br />
rob.Axis1 = 5.0<br />
the Tcp has changed (forward kinematic)<br />
print rob.Tcp<br />
<br />
move the robot back to start position (reverse kinematic):<br />
rob.Tcp = Start<br />
print rob.Axis1<br />
<br />
the same with axis 2:<br />
rob.Axis2 = 5.0<br />
print rob.Tcp<br />
rob.Tcp = Start<br />
print rob.Axis2<br />
<br />
Waypoints:<br />
w = Waypoint(Placement(),name="Pt",type="LIN")<br />
print w.Name,w.Type,w.Pos,w.Cont,w.Velocity,w.Base,w.Tool<br />
<br />
generate more. The trajectory always finds automatically a unique name for the waypoints<br />
l = [w]<br />
for i in range(5):<br />
l.append(Waypoint(Placement(Vector(0,0,i*100),Vector(1,0,0),0),"LIN","Pt"))<br />
<br />
create a trajectory <br />
t = Trajectory(l)<br />
print t<br />
for i in range(7):<br />
t.insertWaypoints(Waypoint(Placement(Vector(0,0,i*100+500),Vector(1,0,0),0),"LIN","Pt"))<br />
<br />
see a list of all waypoints:<br />
print t.Waypoints<br />
<br />
del rob,Start,t,l,w<br />
<br />
=== working with the document ===<br />
<br />
Working with the robot document objects:<br />
first create a robot in the active document<br />
if(App.activeDocument() == None):App.newDocument()<br />
<br />
App.activeDocument().addObject("Robot::RobotObject","Robot")<br />
Define the visual representation and the kinematic definition (see [[6-Axis Robot]] and [[VRML Preparation for Robot Simulation]] for details about that)<br />
App.activeDocument().Robot.RobotVrmlFile = App.getResourceDir()+"Mod/Robot/Lib/Kuka/kr500_1.wrl"<br />
App.activeDocument().Robot.RobotKinematicFile = App.getResourceDir()+"Mod/Robot/Lib/Kuka/kr500_1.csv"<br />
start positon of the Axis (only that which differ from 0)<br />
App.activeDocument().Robot.Axis2 = -90<br />
App.activeDocument().Robot.Axis3 = 90<br />
<br />
retrieve the Tcp position <br />
pos = FreeCAD.getDocument("Unnamed").getObject("Robot").Tcp<br />
move the robot<br />
pos.move(App.Vector(-10,0,0))<br />
FreeCAD.getDocument("Unnamed").getObject("Robot").Tcp = pos<br />
<br />
create an empty Trajectory object in the active document<br />
App.activeDocument().addObject("Robot::TrajectoryObject","Trajectory")<br />
get the Trajectory<br />
t = App.activeDocument().Trajectory.Trajectory<br />
add the actual TCP position of the robot to the trajectory<br />
StartTcp = App.activeDocument().Robot.Tcp<br />
t.insertWaypoints(StartTcp)<br />
App.activeDocument().Trajectory.Trajectory = t<br />
print App.activeDocument().Trajectory.Trajectory<br />
<br />
insert some more Waypoints and the start point at the end again:<br />
for i in range(7):<br />
t.insertWaypoints(Waypoint(Placement(Vector(0,1000,i*100+500),Vector(1,0,0),i),"LIN","Pt"))<br />
<br />
t.insertWaypoints(StartTcp) # end point of the trajectory<br />
App.activeDocument().Trajectory.Trajectory = t<br />
print App.activeDocument().Trajectory.Trajectory<br />
<br />
=== Simulation ===<br />
To be done..... ;-)<br />
<br />
=== Exporting the trajectory ===<br />
The trajectory is exported by Python. That means for every control cabinet type there is a post-processor<br />
Python module. Here is in detail the Kuka post-processor described<br />
from KukaExporter import ExportCompactSub<br />
<br />
ExportCompactSub(App.activeDocument().Robot,App.activeDocument().Trajectory,'D:/Temp/TestOut.src')<br />
<br />
and that's kind of how it's done:<br />
for w in App.activeDocument().Trajectory.Trajectory.Waypoints:<br />
(A,B,C) = (w.Pos.Rotation.toEuler())<br />
print ("LIN {X %.3f,Y %.3f,Z %.3f,A %.3f,B %.3f,C %.3f} ; %s"%(w.Pos.Base.x,w.Pos.Base.y,w.Pos.Base.z,A,B,C,w.Name))<br />
<br />
{{docnav|Drawing Module|Raytracing Module}}<br />
<br />
{{languages | {{es|Robot Workbench/es}} {{fr|Robot Workbench/fr}} {{it|Robot Module/it}} {{jp|Robot Module/jp}} {{ru|Robot Workbench/ru}} {{se|Robot Workbench/se}} }}</div>Htsubota