Difference between revisions of "Line drawing function"

From FreeCAD Documentation
Jump to navigation Jump to search
(Use triple quotes for docstrings)
(Removed Docnav.)
 
(43 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
<languages/>
 
<languages/>
 
<translate>
 
<translate>
<!--T:36-->
+
 
{{docnav|Code snippets|Dialog creation}}
+
</translate>
 +
{{TOCright}}
 +
<translate>
 +
 
 +
==Introduction== <!--T:39-->
  
 
<!--T:1-->
 
<!--T:1-->
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.
+
This page shows how advanced functionality can easily be created in Python. In this exercise, we will build 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 in the interface, like a menu item or a toolbar button.
  
 
==The main script== <!--T:2-->
 
==The main script== <!--T:2-->
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:
+
 
 +
<!--T:40-->
 +
First we will write a script containing all our functionality. Then we will save this in a file and import it in FreeCAD to make all its classes and functions available. Launch your favorite code editor and type the following lines:
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
 
import FreeCADGui, Part
 
import FreeCADGui, Part
 
from pivy.coin import *
 
from pivy.coin import *
+
 
 
class line:
 
class line:
 +
 
     """This class will create a line after the user clicked 2 points on the screen"""
 
     """This class will create a line after the user clicked 2 points on the screen"""
 +
 
     def __init__(self):
 
     def __init__(self):
 
         self.view = FreeCADGui.ActiveDocument.ActiveView
 
         self.view = FreeCADGui.ActiveDocument.ActiveView
 
         self.stack = []
 
         self.stack = []
         self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)
+
         self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)
  
     def getpoint(self,event_cb):
+
     def getpoint(self, event_cb):
 
         event = event_cb.getEvent()
 
         event = event_cb.getEvent()
 
         if event.getState() == SoMouseButtonEvent.DOWN:
 
         if event.getState() == SoMouseButtonEvent.DOWN:
 
             pos = event.getPosition()
 
             pos = event.getPosition()
             point = self.view.getPoint(pos[0],pos[1])
+
             point = self.view.getPoint(pos[0], pos[1])
 
             self.stack.append(point)
 
             self.stack.append(point)
 
             if len(self.stack) == 2:
 
             if len(self.stack) == 2:
                 l = Part.Line(self.stack[0],self.stack[1])
+
                 l = Part.LineSegment(self.stack[0], self.stack[1])
 
                 shape = l.toShape()
 
                 shape = l.toShape()
 
                 Part.show(shape)
 
                 Part.show(shape)
                 self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
+
                 self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)
 
}}
 
}}
 
<translate>
 
<translate>
 +
 +
<!--T:41-->
 +
[[#top|top]]
  
 
==Detailed explanation== <!--T:3-->
 
==Detailed explanation== <!--T:3-->
 +
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 42: Line 55:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:4-->
 
<!--T:4-->
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...
+
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 {{incode|FreeCADGui}}, for accessing the [[3D_view|3D view]]. We also need the complete contents of the Coin library so we can directly use all Coin objects like {{incode|SoMouseButtonEvent}}, etc.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 49: Line 64:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:5-->
 
<!--T:5-->
 
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.
 
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.
 +
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 56: Line 73:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:6-->
 
<!--T:6-->
 
In Python, every class or function can have a documentation string (docstring). This is particularly useful in FreeCAD, because when you call that class in the interpreter, the description string will be displayed as a tooltip.
 
In Python, every class or function can have a documentation string (docstring). This is particularly useful in FreeCAD, because when you call that class in the interpreter, the description string will be displayed as a tooltip.
 +
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 63: Line 82:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:7-->
 
<!--T:7-->
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.
+
Python classes can always contain an {{incode|__init__}} function, which is executed when the class is called to create an object. Here we will put everything we want to happen when our line tool begins.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 70: Line 91:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:8-->
 
<!--T:8-->
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.
+
In a class you usually want to prepend {{incode|self.}} to variable names to make the variables easily accessible to all functions inside and outside the class. Here we will use {{incode|self.view}} to access and manipulate the active 3D view.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 77: Line 100:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:9-->
 
<!--T:9-->
Here we create an empty list that will contain the 3D points sent by the getpoint function.
+
Here we create an empty list that will contain the 3D points sent by the {{incode|getpoint()}} function.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)
+
self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:10-->
 
<!--T:10-->
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.
+
This is the important part. Since we are dealing with a [https://github.com/coin3d/coin/wiki Coin3D] scene, we use a Coin callback mechanism that allows a function to be called every time a certain scene event happens. In our case we are creating a callback for [https://coin3d.github.io/Coin/html/classSoMouseButtonEvent.html SoMouseButtonEvent] events, and we bind it to the {{incode|getpoint()}} function. Now every time a mouse button is pressed or released the {{incode|getpoint()}} function will be executed.
  
 
<!--T:11-->
 
<!--T:11-->
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!
+
Note that there is also an alternative to {{incode|addEventCallbackPivy()}} called {{incode|addEventCallback()}} which does not rely on pivy. But since pivy is a very efficient and natural way to access any part of a Coin scene, it is the better choice.
 +
 
 +
<!--T:42-->
 +
[[#top|top]]
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
def getpoint(self,event_cb):
+
def getpoint(self, event_cb):
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:12-->
 
<!--T:12-->
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]]).
+
Now we define the {{incode|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 {{incode|event_cb}}. From this event callback we can access the event object, which contains several pieces of information (more info [[Code_snippets#Observing_mouse_events_in_the_3D_viewer_via_Python|here]]).
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 101: Line 133:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:13-->
 
<!--T:13-->
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.
+
The {{incode|getpoint()}} function will be called when a mouse button is pressed or released. But we only want to pick a 3D point when a button is pressed, otherwise we would end up with two 3D points very close together. So we must check for that here.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 108: Line 142:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:14-->
 
<!--T:14-->
Here we get the screen coordinates of the mouse cursor
+
Here we get the screen coordinates of the mouse cursor.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
point = self.view.getPoint(pos[0],pos[1])
+
point = self.view.getPoint(pos[0], pos[1])
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:15-->
 
<!--T:15-->
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.
+
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. That is the location of our 3D point. If we are in orthogonal view, the ray is parallel to the view direction.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 122: Line 160:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:16-->
 
<!--T:16-->
We add our new point to the stack
+
We add our new point to the stack.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 129: Line 169:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:17-->
 
<!--T:17-->
 
Do we have enough points already? if yes, then let's draw the line!
 
Do we have enough points already? if yes, then let's draw the line!
 +
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
l = Part.Line(self.stack[0],self.stack[1])
+
l = Part.LineSegment(self.stack[0], self.stack[1])
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:18-->
 
<!--T:18-->
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.
+
Here we use the {{incode|LineSegment()}} function from the [[Part Module]] that creates a line from two FreeCAD vectors. The line is not bound to any object in our active document, so nothing appears on the screen.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 143: Line 187:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:19-->
 
<!--T:19-->
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.
+
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.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 150: Line 196:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:20-->
 
<!--T:20-->
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.
+
The Part module has a very handy {{incode|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 and then bound the shape to it manually.
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
+
self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:21-->
 
<!--T:21-->
Since we are done with our line, let's remove the callback mechanism, that consumes precious CPU cycles.
+
Since we are done with our line we remove the callback mechanism here.
 +
 
 +
<!--T:43-->
 +
[[#top|top]]
 +
 
 +
==Testing the script== <!--T:22-->
  
==Testing & Using the script== <!--T:22-->
+
<!--T:44-->
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".
+
Now let's save our script in a folder where the FreeCAD Python interpreter can find it. When importing modules, the interpreter will look in the following places: the Python installation paths, the FreeCAD {{FileName|bin}} folder, and all FreeCAD {{FileName|Mod}} (module) folders. So the best solution is to create a new folder in one of the {{FileName|Mod}} folders. Let's create a {{FileName|MyScripts}} folder there and save our script in it as {{FileName|exercise.py}}.
  
 
<!--T:23-->
 
<!--T:23-->
Now, everything is ready, let's start FreeCAD, create a new document, and, in the python interpreter, issue:
+
Now everything is ready. Let's start FreeCAD, create a new document, and in the Python interpreter issue:
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 170: Line 225:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:24-->
 
<!--T:24-->
If no error message appear, that means our exercise script has been loaded. We can now check its contents with:
+
If no error message appears our exercise script has been loaded successfully. We can now check its contents with:
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 177: Line 234:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:25-->
 
<!--T:25-->
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:
+
The command {{incode|dir()}} is a built-in Python command that lists the contents of a module. We can check that our {{incode|line()}} class is there with:
 +
 
 +
</translate>
 +
{{Code|code=
 +
'line' in dir(exercise)
 +
}}
 +
<translate>
 +
 
 +
<!--T:45-->
 +
Now let's test it:
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
Line 184: Line 252:
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:26-->
 
<!--T:26-->
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?
+
Click two times in the 3D view and bingo: here is our line! To repeat it just type {{incode|exercise.line()}} again.
 +
 
 +
<!--T:46-->
 +
[[#top|top]]
 +
 
 +
==Registering the script== <!--T:27-->
 +
 
 +
<!--T:47-->
 +
For our new line tool to be really useful, and to avoid having to type all that stuff, it should have a button in the interface. One way to do this is to transform our new {{FileName|MyScripts}} folder into a full FreeCAD workbench. This is easy, all that is needed is to put a file called {{FileName|InitGui.py}} inside the {{FileName|MyScripts}} folder. {{FileName|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 change our exercise code a bit, so the {{incode|line()}} tool is recognized as an official FreeCAD command. Let's start by creating an {{FileName|InitGui.py}} file, and writing the following code in it:
  
==Registering the script in the FreeCAD interface== <!--T:27-->
 
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:
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
class MyWorkbench (Workbench):  
+
class MyWorkbench (Workbench):
  MenuText = "MyScripts"
+
 
  def Initialize(self):
+
    MenuText = "MyScripts"
      import exercise
+
 
      commandslist = ["line"]
+
    def Initialize(self):
      self.appendToolbar("My Scripts",commandslist)
+
        import exercise
 +
        commandslist = ["line"]
 +
        self.appendToolbar("My Scripts", commandslist)
 +
 
 
Gui.addWorkbench(MyWorkbench())
 
Gui.addWorkbench(MyWorkbench())
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:28-->
 
<!--T:28-->
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.
+
By now you probably understand the above script. We create a new class that we call {{incode|MyWorkbench}}, we give it a title {{incode|MenuText}}, and we define an {{incode|Initialize()}} function that will be executed when the workbench is loaded into FreeCAD. In that function, we load 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 command list to it. Currently, of course, we only have one tool, so our command list contains only one element. Then, once our workbench is ready, we add it to the main interface.
  
 
<!--T:29-->
 
<!--T:29-->
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:
+
But this still won't work because a FreeCAD command must be formatted in a certain manner to work, we will need to change our {{incode|line()}} tool. Our new {{FileName|exercise.py}} script should look like this:
 +
 
 
</translate>
 
</translate>
 
{{Code|code=
 
{{Code|code=
 
import FreeCADGui, Part
 
import FreeCADGui, Part
 
from pivy.coin import *
 
from pivy.coin import *
 +
 
class line:
 
class line:
"this class will create a line after the user clicked 2 points on the screen"
+
 
def Activated(self):
+
    """This class will create a line after the user clicked 2 points on the screen"""
  self.view = FreeCADGui.ActiveDocument.ActiveView
+
 
  self.stack = []
+
    def Activated(self):
  self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)  
+
        self.view = FreeCADGui.ActiveDocument.ActiveView
def getpoint(self,event_cb):
+
        self.stack = []
  event = event_cb.getEvent()
+
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)
  if event.getState() == SoMouseButtonEvent.DOWN:
+
 
    pos = event.getPosition()
+
    def getpoint(self, event_cb):
    point = self.view.getPoint(pos[0],pos[1])
+
        event = event_cb.getEvent()
    self.stack.append(point)
+
        if event.getState() == SoMouseButtonEvent.DOWN:
    if len(self.stack) == 2:
+
            pos = event.getPosition()
      l = Part.Line(self.stack[0],self.stack[1])
+
            point = self.view.getPoint(pos[0], pos[1])
      shape = l.toShape()
+
            self.stack.append(point)
      Part.show(shape)
+
            if len(self.stack) == 2:
      self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
+
                l = Part.LineSegment(self.stack[0], self.stack[1])
def GetResources(self):  
+
                shape = l.toShape()
    return {'Pixmap' : 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'}  
+
                Part.show(shape)
 +
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)
 +
 
 +
    def GetResources(self):
 +
        return {'Pixmap': 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'}
 +
 
 
FreeCADGui.addCommand('line', line())
 
FreeCADGui.addCommand('line', line())
 
}}
 
}}
 
<translate>
 
<translate>
 +
 
<!--T:30-->
 
<!--T:30-->
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.
+
What we did here is transform our {{incode|__init__()}} function into an {{incode|Activated()}} function. When FreeCAD commands are run, they automatically execute the {{incode|Activated()}} function. We also added a {{incode|GetResources()}} function, that informs FreeCAD where it can find the icon for the tool, and what will be the name and tooltip of our tool. Any {{FileName|jpg}}, {{FileName|png}} or {{FileName|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.
Then, we add the line() class as an official FreeCAD command with the addCommand() method.
+
Then we add the {{incode|line()}} class as an official FreeCAD command with the {{incode|addCommand()}} method.
  
 
<!--T:31-->
 
<!--T:31-->
That's it, we now just need to restart FreeCAD and we'll have a nice new workbench with our brand new line tool!
+
That's it, now we just need to restart FreeCAD and we'll have a nice new workbench with our brand new line tool!
 +
 
 +
<!--T:48-->
 +
[[#top|top]]
  
 
==So you want more?== <!--T:32-->
 
==So you want more?== <!--T:32-->
  
 
<!--T:33-->
 
<!--T:33-->
If you liked this exercise, why not try to improve this little tool? There are many things that can be done, like for example:
+
If you liked this exercise, why not try to improve this little tool? There are many things that can be done, for example:
* 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
+
* 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 the user what to do next. You could issue messages to the FreeCAD console. Have a look in the {{incode|FreeCAD.Console}} module.
* Add a possibility to type the 3D points coordinates manually. Look at the python input() function, for example
+
* Add a possibility to type the 3D points coordinates manually. Look at the Python {{incode|input()}} function for example.
* Add the possibility to add more than 2 points
+
* Add the possibility to add more than 2 points.
 
* 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?
 
* 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?
* Give a name to the created object
+
* Give a name to the created object.
Don't hesitate to write your questions or ideas on the [http://forum.freecadweb.org/ forum]!
 
 
 
<!--T:34-->
 
{{docnav|Code snippets|Dialog creation}}
 
 
 
<!--T:37-->
 
{{Userdocnavi}}
 
  
<!--T:35-->
+
<!--T:49-->
[[Category:Poweruser Documentation]]
+
Don't hesitate to ask questions or share ideas on the [https://forum.freecadweb.org/ forum]!
  
<!--T:38-->
+
<!--T:50-->
[[Category:Python Code]]
+
[[#top|top]]
  
 
</translate>
 
</translate>
 +
{{Powerdocnavi{{#translation:}}}}
 +
[[Category:Developer Documentation{{#translation:}}]]
 +
[[Category:Python Code{{#translation:}}]]
 
{{clear}}
 
{{clear}}

Latest revision as of 14:35, 20 August 2020

Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Türkçe • ‎español • ‎français • ‎italiano • ‎polski • ‎română • ‎svenska • ‎čeština • ‎русский

Introduction

This page shows how advanced functionality can easily be created in Python. In this exercise, we will build 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 in the interface, like a menu item or a toolbar button.

The main script

First we will write a script containing all our functionality. Then we will save this in a file and import it in FreeCAD to make all its classes and functions available. Launch your favorite code editor and type the following lines:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def __init__(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

top

Detailed explanation

import Part, FreeCADGui
from pivy.coin import *

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 directly use all Coin objects like SoMouseButtonEvent, etc.

class line:

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.

"""This class will create a line after the user clicked 2 points on the screen"""

In Python, every class or function can have a documentation string (docstring). This is particularly useful in FreeCAD, because when you call that class in the interpreter, the description string will be displayed as a tooltip.

def __init__(self):

Python classes can always contain an __init__ function, which is executed when the class is called to create an object. Here we will put everything we want to happen when our line tool begins.

self.view = FreeCADGui.ActiveDocument.ActiveView

In a class you usually want to prepend self. to variable names to make the variables easily accessible to all functions inside and outside the class. Here we will use self.view to access and manipulate the active 3D view.

self.stack = []

Here we create an empty list that will contain the 3D points sent by the getpoint() function.

self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

This is the important part. Since we are dealing with a Coin3D scene, we use a Coin callback mechanism that allows a function to be called every time a certain scene event happens. In our case we are creating a callback for SoMouseButtonEvent events, and we bind it to the getpoint() function. Now every time a mouse button is pressed or released the getpoint() function will be executed.

Note that there is also an alternative to addEventCallbackPivy() called addEventCallback() which does not rely on pivy. But since pivy is a very efficient and natural way to access any part of a Coin scene, it is the better choice.

top

def getpoint(self, event_cb):

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 (more info here).

if event.getState() == SoMouseButtonEvent.DOWN:

The getpoint() function will be called when a mouse button is pressed or released. But we only want to pick a 3D point when a button is pressed, otherwise we would end up with two 3D points very close together. So we must check for that here.

pos = event.getPosition()

Here we get the screen coordinates of the mouse cursor.

point = self.view.getPoint(pos[0], pos[1])

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. That is the location of our 3D point. If we are in orthogonal view, the ray is parallel to the view direction.

self.stack.append(point)

We add our new point to the stack.

if len(self.stack) == 2:

Do we have enough points already? if yes, then let's draw the line!

l = Part.LineSegment(self.stack[0], self.stack[1])

Here we use the LineSegment() function from the Part Module that creates a line from two FreeCAD vectors. The line is not bound to any object in our active document, so nothing appears on the screen.

shape = l.toShape()

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.

Part.show(shape)

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 and then bound the shape to it manually.

self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Since we are done with our line we remove the callback mechanism here.

top

Testing the script

Now let's save our script in a folder where the FreeCAD Python interpreter can find it. When importing modules, the interpreter will look in the following places: the Python installation paths, the FreeCAD bin folder, and all FreeCAD Mod (module) folders. So the best solution is to create a new folder in one of the Mod folders. Let's create a MyScripts folder there and save our script in it as exercise.py.

Now everything is ready. Let's start FreeCAD, create a new document, and in the Python interpreter issue:

import exercise

If no error message appears our exercise script has been loaded successfully. We can now check its contents with:

dir(exercise)

The command dir() is a built-in Python command that lists the contents of a module. We can check that our line() class is there with:

'line' in dir(exercise)

Now let's test it:

exercise.line()

Click two times in the 3D view and bingo: here is our line! To repeat it just type exercise.line() again.

top

Registering the script

For our new line tool to be really useful, and to avoid having to type all that stuff, it should have a button in the interface. One way to do this is to transform our new MyScripts folder into a full FreeCAD workbench. This is easy, all that is needed is to put a file called InitGui.py inside the MyScripts folder. 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 change our exercise code a bit, so the line() tool is recognized as an official FreeCAD command. Let's start by creating an InitGui.py file, and writing the following code in it:

class MyWorkbench (Workbench):

    MenuText = "MyScripts"

    def Initialize(self):
        import exercise
        commandslist = ["line"]
        self.appendToolbar("My Scripts", commandslist)

Gui.addWorkbench(MyWorkbench())

By now you probably understand the above script. 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 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 command list to it. Currently, of course, we only have one tool, so our command list contains only one element. Then, once our workbench is ready, we add it to the main interface.

But this still won't work because a FreeCAD command must be formatted in a certain manner to work, we will need to change our line() tool. Our new exercise.py script should look like this:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def Activated(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

    def GetResources(self):
        return {'Pixmap': 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'}

FreeCADGui.addCommand('line', line())

What we did here is transform our __init__() function into an Activated() function. When FreeCAD commands are run, they automatically execute the Activated() function. We also added a GetResources() function, that informs FreeCAD where it can find the 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. Then we add the line() class as an official FreeCAD command with the addCommand() method.

That's it, now we just need to restart FreeCAD and we'll have a nice new workbench with our brand new line tool!

top

So you want more?

If you liked this exercise, why not try to improve this little tool? There are many things that can be done, for example:

  • 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 the user what to do next. You could issue messages to the FreeCAD console. Have a look in the FreeCAD.Console module.
  • Add a possibility to type the 3D points coordinates manually. Look at the Python input() function for example.
  • Add the possibility to add more than 2 points.
  • 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?
  • Give a name to the created object.

Don't hesitate to ask questions or share ideas on the forum!

top