Scripted objects/sv

Introduction
Förutom standard objekttyper som annoteringar, nät och delobjekt, så erbjuder FreeCAD också den fantastiska möjligheten att bygga 100% python-skriptade objekt, som kallas för Python Funktioner. dessa objekt kommer att bete sig exakt som alla andra FreeCAD objekt, de kan sparas i ett dokument och öppnas av en annan FreeCAD installation, eftersom den python kod som definierar objektet även sparas i dokumentet.

One particularity must be understood, those objects are saved in FreeCAD FcStd files with python's 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.

Python Funktioner följer samma regler som alla FreeCAD funktioner: de är separerade i App och GUI delar. App delen, Dokumentobjektet, definierar vårt objekts geometri, medan dess gränssnittsdel, Visaobjektet, definierar hur objektet kommer att ritas på skärmen. VisaObjektet, är som alla andra FreeCAD funktioner, endast tillgängligt när du kör FreeCAD i dess eget gränssnitt. Det finns flera egenskaper och metoder tillgängliga för att bygga ditt objekt. Egenskaperna måste vara en av de fördefinierade egenskapstyperna som FreeCAD erbjuder, och kommer att visas i egenskapsfönstret, så de kan redigeras av användaren. på detta sätt så är Python Funktionsobjekt totalt parametrisk. Du kan definiera egenskaper för objektet och dess Visaobjekt separat.

Hint: In former versions we used Python's cPickle module. However, this module executes arbitrary code and thus causes a security problem. Thus, we moved to Python's json module.

Enkelt exempel
Följande exempel kan hittas i src/Mod/TemplatePyMod/FeaturePython.py filen, tillsammans med flera andra exempel:

Things to note
If your object relies on being recomputed as soon as it is created, you must do this manually in the function as it is not called automatically. This example does not require it because the method of the  class has the same effect as the  function, but the examples below rely on being recomputed before anything is displayed in the 3D view. In the examples, this is done manually with but in more complex scenarios you need to decide where to recompute either the whole document or the FeaturePython object.

This example produces a number of exception stack traces in the report view window. This is because the method of the  class is called each time a property is added in. When the first one is added, the Width and Height properties don't exist yet and so the attempt to access them fails.

An explanation of and  is in the forum thread obj.Proxy.Type is a dict, not a string.

Tillgängliga egenskaper
Egenskaper är PythonFunktion objektens sanna byggstenar. Genom dem, så kan användaren interagera och ändra objektet. Efter att ett nytt PythonFunktion objekt har skapats i ditt dokument ( a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), så kan du få en lista på de tillgängliga egenskaperna genom att skriva:

Du kommer att få en lista på tillgängliga egenskaper:

När du adderar egenskaper till dina anpassade objekt, var uppmärksam på detta:
 * Använd inte tecknen "<" eller ">" i egenskapsbeskrivningen (det förstör xml delarna i .fcstd filen)
 * Egenskaper lagras i alfabetisk ordning i en .fcstd fil. Om du har en form i dina egenskaper, så kommer alla egenskaper vars namn kommer efter "Form" i alfabetisk ordning att laddas EFTER formen, vilket kan orsaka ett märkligt beteende.

A complete list of property attributes can be seen in the PropertyStandard C++ header file. For instance, if you want to allow the user to enter only a limited range of values (e.g. using PropertyIntegerConstraint), in Python you will assign a tuple containing not only the property value, but also the lower and upper limit as well as the stepsize, as below:

Property Type
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. The property type can be set using

where mode is a short int that can be set to: 0 -- default mode, read and write 1 -- read-only 2 -- hidden

The EditorModes are not set at FreeCAD file reload. This could to be done by the __setstate__ function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=10#p108072. By using the setEditorMode the properties are only read only in PropertyEditor. They could still be changed from python. To really make them read only the setting has to be passed directly inside the addProperty function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=20#p109709 for an example.

Using the direct setting in the addProperty function, you also have more possibilities. In particular, an interesting one is mark a property as an output property. This way FreeCAD won't mark the feature as touched when changing it (so no need to recompute).

Example of output property (see also https://forum.freecadweb.org/viewtopic.php?t=24928):

The property types that can be set at last parameter of the addProperty function are: 0 -- Prop_None, No special property type 1 -- Prop_ReadOnly, Property is read-only in the editor 2 -- Prop_Transient, Property won't be saved to file 4 -- Prop_Hidden, Property won't appear in the editor 8 -- Prop_Output, Modified property doesn't touch its parent container 16 -- Prop_NoRecompute, Modified property doesn't touch its container for recompute

You can find these different property types defined in the source code C++ header for PropertyContainer

Andra mer komplexa exempel
Detta exempel använder sig av Del Modulen för att skapa en oktahedron, sedan skapas dess coin representation med pivy.

Det första är själva Dokument objektet:

Sedan så har vi visarobjektet, ansvarigt för att visa objektet i 3D scenen:

Slutligen, när vårt objekt och dess visningsobjekt är definierade, så behöver vi bara anropa dem:

Göra objekt valbara
Om du vill göra ditt objekt valbart, eller åtminstone en del av den, genom att klicka på den i vyn, så måste du inkludera dess geometri inuti en SoFCSelection nod. Om ditt objekt har en komplex representation, med widgetar, annoteringar, etc, så kanske du bara vill inkludera en del av den i en SoFCSelection. Allt som är en SoFCSelection skannas konstant av FreeCAD för att detektera val/förval, så det är vettigt att inte försöka överbelasta den med onödig skanning. Detta är vad du skulle göra för att inkludera en self.face från det ovan visade exemplet:

Once the parts of the scenegraph that are to be selectable are inside SoFCSelection nodes, you then need to provide two methods to handle the selection path. The selection path can take the form of a string giving the names of each element in the path, or of an array of scenegraph objects. The two methods you provide are, which converts from a string path to an array of scenegraph objects, and , which takes an element which has been clicked on in the scenegraph and returns its string name (note, not its string path).

Here is the molecule example above, adapted to make the elements of the molecule selectable:

Arbeta med enkla former
Om ditt parametriska objektbara resulterar i en form, så behöver du inte använda ett visarobjekt. Formen kommer att visas med hjälp av FreeCAD's standard form representation:

Same code with use ViewProviderLine

Scenegraph Structure
You may have noticed that the examples above construct their scenegraphs in slightly different ways. Some use while others use.

Each feature in a FreeCAD document is based the following scenegraph structure:

The displays only one of its children, depending on which display mode is selection in FreeCAD.

The examples which use are constructing their scenegraphs solely out of coin3d scenegraph elements. Under the covers, adds a new child to the ; the name of that node will match the display mode it was passed.

The examples which use also construct part of their geometry using functions from the Part workbench, such as. This constructs the different display mode scenegraphs under the ; when we later come to add coin3d elements to the scenegraph, we need to add them to the existing display mode scenegraphs using rather than creating a new child of the.

When using to add geometry to the scenegraph, each display mode should have its own node which is passed to ; don't reuse the same node for this. Doing so will confuse the selection mechanism. It's okay if each display mode's node has the same geometry nodes added below it, just the root of each display mode needs to be distinct.

Here is the above molecule example, adapted to be drawn only with Coin3D scenegraph objects instead of using objects from the Part workbench:

Additional pages:
 * Scripted objects saving attributes
 * Scripted objects migration
 * Scripted objects with attachment
 * Viewproviders

Interesting forum threads about scripted objects:
 * Python object attributes lost at load
 * New FeaturePython is grey
 * Explanation on __getstate__ and __setstate__, official documentation
 * Eigenmode frequency always 0?
 * how to implement python feature's setEdit properly?

In addition to the examples presented here have a look at FreeCAD source code src/Mod/TemplatePyMod/FeaturePython.py for more examples.