Pivy/it: Difference between revisions

From FreeCAD Documentation
(Updating to match new version of source page)
Line 1: Line 1:
[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.
== Pivy ==

___TOC___

[http://pivy.coin3d.org/ Pivy] è una libreria che collega Python con [http://www.coin3d.org Coin3d], ed è la libreria di renderizzazione-3D utilizzata da FreeCAD. Quando viene importata in un interprete Python in esecuzione, permette di dialogare direttamente con qualsiasi [[Scenegraph/it|grafo di scena]] (scenegraph) di Coin3d in esecuzione, come ad esempio le viste 3D di FreeCAD, o addirittura di creare nuovi grafi di scena. Pivy è incluso nell'installazione standard di FreeCAD.

La biblioteca Coin è divisa in vari moduli, Coin stessa, per manipolare grafi di scene e associarli a diversi sistemi GUI, come a Windows oppure, come nel nostro caso, a Qt. Tali moduli sono disponibili anche per Pivy, se sono presenti nel sistema. Il modulo Coin è sempre presente, ed è quello che useremo in tutti gli esempi, e non sarà necessario preoccuparsi di associare la nostra visualizzazione 3D ad alcuna interfaccia, perchè questo viene già fatto da FreeCAD stesso. Tutto quello che dobbiamo fare è:


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:
<syntaxhighlight>
from pivy import coin
from pivy import coin
</syntaxhighlight>
==Accessing and modifying the scenegraph==


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.
=== Accesso e modifica del Grafo della scena (Scenegraph) ===

Abbiamo già visto nella pagina [[Scenegraph/it|Grafo della scena]] (Scenegraph) come è organizzata una tipica scena di Coin. Tutto ciò che appare in una vista 3D di FreeCAD è un Scenegraph di Coin, organizzato allo stesso modo. Abbiamo un nodo radice (principale), e tutti gli oggetti sullo schermo sono suoi figli.

FreeCAD dispone di un modo semplice per accedere al nodo radice (root) di una scena grafica in vista 3D:


FreeCAD has an easy way to access the root node of a 3D view scenegraph:
<syntaxhighlight>
sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
print sg
print sg
</syntaxhighlight>

This will return the root node:
Ciò restituisce il nodo principale (root):
<syntaxhighlight>

<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >
<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >
</syntaxhighlight>

We can inspect the immediate children of our scene:
Siamo in grado di ispezionare i figli immediati della nostra scena:
<syntaxhighlight>

for node in sg.getChildren():
for node in sg.getChildren():
print node
print node
</syntaxhighlight>
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].


Let's try to add something to our scenegraph now. We'll add a nice red cube:
Alcuni di questi nodi, ad esempio SoSeparators o SoGroups, possono avere dei propri figli. L'elenco completo degli oggetti Coin disponibili si può trovare nella [http://doc.coin3d.org/Coin/classes.html documentazione ufficiale di Coin].
<syntaxhighlight>

Ora proviamo ad aggiungere qualcosa al nostro Scenegraph. Aggiungiamo un bel cubo rosso:

col = coin.SoBaseColor()
col = coin.SoBaseColor()
col.rgb=(1,0,0)
col.rgb=(1,0,0)
Line 38: Line 34:
myCustomNode.addChild(cub)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)
sg.addChild(myCustomNode)
</syntaxhighlight>

e questo è il nostro (bel) cubo rosso. Ora, proviamo questo:
and here is our (nice) red cube. Now, let's try this:
<syntaxhighlight>

col.rgb=(1,1,0)
col.rgb=(1,1,0)
</syntaxhighlight>
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.


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:
Visto? Tutto è sempre accessibile e modificabile al volo. Non c'è bisogno di ricalcolare o ridisegnare nulla, Coin si prende cura di tutto. È possibile aggiungere elementi al grafo di scena, modificare le proprietà, nascondere delle cose, mostrare oggetti temporanei, qualsiasi cosa. Naturalmente, questo riguarda solo la visualizzazione nella vista 3D. Questa visualizzazione viene determinata da FreeCAD all'apertura del file attivo e quando un oggetto ha bisogno di essere ricalcolato. Quindi, se si modifica l'aspetto di un oggetto di FreeCAD esistente, tali modifiche andranno perse se l'oggetto viene ricalcolato o quando si riapre il file.
<syntaxhighlight>

Per lavorare con i grafi di scena nei nostri script è fondamentale saper accedere a specifiche proprietà dei nodi aggiunti quando questo è necessario. Per esempio, se avessimo voluto spostare il nostro cubo, avremmo aggiunto un nodo SoTranslation al nostro nodo personalizzato, e lo script apparirebbe così:

col = coin.SoBaseColor()
col = coin.SoBaseColor()
col.rgb=(1,0,0)
col.rgb=(1,0,0)
Line 57: Line 53:
myCustomNode.addChild(cub)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)
sg.addChild(myCustomNode)
</syntaxhighlight>

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:
Ricordate che, in un Scenegraph di OpenInventor, l'ordine è importante. Un nodo riguarda ciò che viene dopo, quindi permette di definire qualcosa come: colore rosso, cubo, colore giallo, sfera, e di ottenere un cubo rosso e una sfera gialla. Se aggiungiamo ora la traslazione al nostro nodo personalizzato esistente, essa viene dopo il cubo, e non lo condiziona. Se lo avessimo inserito durante la creazione, come qui sopra, ora si potrebbe fare:
<syntaxhighlight>

trans.translation.setValue([2,0,0])
trans.translation.setValue([2,0,0])
</syntaxhighlight>

And our cube would jump 2 units to the right.
E il nostro cubo si sposterebbe di 2 unità a destra.
Finally, removing something is done with:

<syntaxhighlight>
Infine, la rimozione di qualcosa si fà con:

sg.removeChild(myCustomNode)
sg.removeChild(myCustomNode)
</syntaxhighlight>
==Using callback mechanisms==


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.
=== Utilizzo dei meccanismi di richiamo (callback) ===

Un [http://en.wikipedia.org/wiki/Callback_%28computer_science%29 callback mechanism] (meccanismo di richiamo) è un sistema che permette a una libreria che si sta utilizzando, come la nostra libreria Coin, di richiamare, cioè, di chiamare una determinata funzione dell'oggetto Python attualmente in esecuzione. Ciò è estremamente utile, perché in questo modo Coin può avvisarci se nella scena si verifica qualche evento specifico. Coin può controllare cose molto diverse, come la posizione del mouse, i clic di un pulsante del mouse, i tasti della tastiera che vengono premuti e tante altre cose.

FreeCAD dispone di un modo semplice per utilizzare tali callback:


FreeCAD features an easy way to use such callbacks:
<syntaxhighlight>
class ButtonTest:
class ButtonTest:
def __init__(self):
def __init__(self):
Line 85: Line 80:
ButtonTest()
ButtonTest()
</syntaxhighlight>
The callback has to be initiated from an object, because that object must still be running when the callback will occur.
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].


== Documentation ==
Il richiamo deve essere iniziato da un oggetto, perché questo oggetto deve essere ancora in esecuzione quando il callback si verifica. Vedere anche la [[Code_snippets/it#Observación_de_Eventos_del_ratón_en_el_visor_3D_ a_través_de_Python|lista completa]] degli eventi possibili e dei loro parametri, o la [http://doc.coin3d.org/Coin/classes.html documentazione ufficiale di Coin].

=== Documentazione ===


Purtroppo, Pivy non ha ancora una propria documentazione adeguata, ma dato che è una traduzione esatta di Coin, si può tranquillamente utilizzare la documentazione di Coin come riferimento, e utilizzare lo stile Python al posto dello stile C++; ad esempio SoFile::getClassTypeId() in Pivy si scrive SoFile.getClassId().
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())


{{docnav/it|[[Scenegraph/it|Grafo di scena]]|[[PyQt/it|PyQt]]}}
{{docnav|Scenegraph|PyQt}}


[[Category:Poweruser Documentation]]
{{languages/it | {{en|Pivy}} {{fr|Pivy/fr}} {{es|Pivy/es}} {{ru|Pivy/ru}} {{se|Pivy/se}} }}


{{clear}}
[[Category:Poweruser Documentation/it]]
<languages/>

Revision as of 20:26, 4 October 2014

Pivy is a python binding library for Coin3d, the 3D-rendering library used FreeCAD. When imported in a running python interpreter, it allows to dialog directly with any running Coin3d scenegraphs, such as the FreeCAD 3D views, or even to create new ones. Pivy is bundled in standard FreeCAD installation.

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:

 from pivy import coin

Accessing and modifying the scenegraph

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.

FreeCAD has an easy way to access the root node of a 3D view scenegraph:

 sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
 print sg

This will return the root node:

 <pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >

We can inspect the immediate children of our scene:

 for node in sg.getChildren():
     print node

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 official coin documentation.

Let's try to add something to our scenegraph now. We'll add a nice red cube:

 col = coin.SoBaseColor()
 col.rgb=(1,0,0)
 cub = coin.SoCube()
 myCustomNode = coin.SoSeparator()
 myCustomNode.addChild(col)
 myCustomNode.addChild(cub)
 sg.addChild(myCustomNode)

and here is our (nice) red cube. Now, let's try this:

 col.rgb=(1,1,0)

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.

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:

 col = coin.SoBaseColor()
 col.rgb=(1,0,0)
 trans = coin.SoTranslation()
 trans.translation.setValue([0,0,0])
 cub = coin.SoCube()
 myCustomNode = coin.SoSeparator()
 myCustomNode.addChild(col)
 mtCustomNode.addChild(trans)
 myCustomNode.addChild(cub)
 sg.addChild(myCustomNode)

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:

 trans.translation.setValue([2,0,0])

And our cube would jump 2 units to the right. Finally, removing something is done with:

 sg.removeChild(myCustomNode)

Using callback mechanisms

A 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.

FreeCAD features an easy way to use such callbacks:

 class ButtonTest:
   def __init__(self):
     self.view = FreeCADGui.ActiveDocument.ActiveView
     self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getMouseClick) 
   def getMouseClick(self,event_cb):
     event = event_cb.getEvent()
     if event.getState() == SoMouseButtonEvent.DOWN:
       print "Alert!!! A mouse button has been improperly clicked!!!"
       self.view.removeEventCallbackSWIG(SoMouseButtonEvent.getClassTypeId(),self.callback) 
 
 ButtonTest()

The callback has to be initiated from an object, because that object must still be running when the callback will occur. See also a complete list of possible events and their parameters, or the official coin documentation.

Documentation

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())

Scenegraph
PyQt