Macro Modello di mezzo scafo

From FreeCAD Documentation
Revision as of 07:52, 16 February 2015 by Renatorivo (talk | contribs) (Created page with "{{Macro/it|Icon=Macro_Half_Hull_Model|Name=Macro Half-Hull Model|Name/it=Half-Hull Model|Description=Questa macro, partendo da una serie di disegni 2D, genera un modello tridi...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

File:Macro Half Hull Model Macro Half-Hull Model

Descrizione
Questa macro, partendo da una serie di disegni 2D, genera un modello tridimensionale sia di "mezzo scafo" half-hull che dello scafo completo.

Autore: Piffpoof
Autore
Piffpoof
Download
None
Link
Versione macro
1.0
Data ultima modifica
None
Versioni di FreeCAD
None
Scorciatoia
Nessuna
Vedere anche
Nessuno

Background

Since antiquity boat builders have had to design boats and then realise them in a three dimensional environment where very few lines are straight, very few surfaces flat and no angles constant over a distance. Hull models were used to make to-scale models which could then be used to review the design or communicate concepts to other persons. The laws of hydrodynamics demand that any vessel passing through a liquid be symmetrical in the cross-section if it is to track (move in a straight line) accurately. Consequently building one side of the hull in the model was all that was necessary - if the half-hull was perfect then its mirror image would also be perfect. In latter years half-hulls became used for symbolic purposes such as plaques, and nautical art.

This code came out of a project to build a model in FreeCAD of a 12.5 metre sailing boat. The builders no longer had drawings and the son of the original owner doubted there ever were full drawings. Consequently the hull dimensions had to be measured and then a model constructed within the software, Modern software packages like FreeCAD offer many beneficial features like symmetry constraints but when the final measurement is a model that is "easy on the eye", much "massaging" of models is required. This code was written to help automate that process.

The initial purpose of this code was to provide a symmetrical hull which was malleable so it could be fitted to the 3D model being constructed. As the software progressed it was generalised so hopefully it would be of some use to persons:

  • boat designers producing boat diagrams which can be built from
  • boat builders who are trying to model what is described on their diagrams
  • model hull builders.

Certainly commercial boat designers have all sorts of high end software to assist their work, this isn't supposed to replace that. Rather this is for hte hobbyist or home builder to tinker around with.

Nautical blueprints have a distinct history with respect to buildings and so are somewhat different in presentation. This is an example of a sailing boat which is more than a century old:

One of the end goals of this software is to use the Draft workbench to generate some of these diagrams using the model to generate the lines.

Note on Units in FreeCAD:

At present there isn't really any units management system within FreeCAD, but obviously a boat builder or modeller will need an accurate dimensioning system. To use this macro, decide to set the FreeCAD grid size to what ever is appropriate for your work (e.g. mm, cm, inch, foot). FreeCAD is consistent, one FreeCAD unit will constantly equal to one FreeCAD unit. And if you have decided to have a FreeCAD unit equal a specific physical length, then your drawings will remain consistently dimensioned. At present there is work on a units system for FreeCAD so this situation may change soon.

Description

For this macro the hull shapes are defined by a minimum of 3 FreeCAD Sketches: one in the YZ plane, one or more in the XZ plane, one in the XY plane. Here is the minimum hull supported by this macro, it has only 3 Sketches:

Note: in the above digram we are looking directly at the stern, the bow is pointing away from the viewpoint.

From front to back (bow to stern) the 3 Sketches are:

stemline
YZ plane
red line in sketch
cross-section
XZ plane
green line in Sketch
transom
XY plane
blue line in Sketch


Perhaps it is easier to see with 7 Sketches (one in YZ plane, one in XY plane and 5 in the XZ plane):

With 5 Sketches in the XZ plane it is becoming easier to perceive the shape of the hull. The next 2 pictures show the Sketch lines superimposed on the model FreeCAD constructs,

the second is the same model rotated 90 degrees so the bow is in the foreground:

Some points to consider:

  • the Sketches are only for:
    • the stemline (or bow line) in the YZ plane (red in the above diagram);
    • the top of the transom in the XY plane (blue in the above diagram);
    • multiple cross-sections of the hull in the XZ plane (green in the above diagram)
  • only the starboard side of the hull is drawn in the Sketches, the port side will be generated as a mirror image
  • each multiple-segment line must be in a separate Sketch
  • each Sketch must have the same number of line segments (which is 3 in the previous examples)
  • the more line segments in each Sketch, the closer the FreeCAD generated model will approximate a curved hull
  • there is no limit to the number of line segment in each Sketch, any number from one up
  • there is no limit to the number of Sketches in the XZ plane (i.e. cross-sections), any number from one up

With enough Sketches the model generated may even approach:

The HalfHull macro generates 4 models:

  • starboard half-hull
  • port half-hull
  • complete hull
  • bulkheads for the complete hull, either with a flush deck or with a coachhouse

These models are all output in the unified location space of FreeCAD so they can be fitted together - for example the bulkheads can be inserted into the complete hull seamlessly. This is a picture of bulkheads in a boat model during construction:

As well as the bulkheads generated by the macro (note that these bulkheads are for a coachhouse rather than a flush deck):

The composite image below shows the main outputs from this software (the port side half-hull is actually not shown but it is the mirror of the starboard half-hull which is shown). The outputs are in clockwise order from the upper left corner:

  • starboard half-hull
  • complete hull
  • bulkheads (for flush deck, the bulkheads in the previous image were for a coachhouse deck)
  • the complete hull with the bulkheads inserted

As novelty features, the macro will also optionally produce plaques for the half-hulls, and even a bottle for the complete hull:

Installation

All the code for halfHullModel.FCMacro is in one macro. So installation is comprised of copying the code to the appropriate Macro directory and invoking the Build Utility from the Macro menu, the Python console or a toolbar button (the preferred method).

Usage

The FreeCAD operations involved in generating the hull model are rather complex and numerous. Things like the direction a line is drawn can cause the FreeCAD construction of the hull to either abort or turn out like:

Consequently the steps below need to be followed closely. The macro does allow for certain data inconsistencies but generally if the data (i.e. the Sketches) are incorrect then the output will look like a cheese grater or the macro fill fail with an error.

The following instructions refer to the quadrants of the XY graph, this refers to the 4 quarters of the XY graph and they are labelled as follows:

Create a New Document

The very first thing is to create a new document in FreeCAD . This document will hold all the Sketches that make up your hull definition.

Create the Stemline

The first step is one of creating data for the hull model to be made from. The data is supplied in the form of Sketches within FreeCAD. After the hull model is generated, if changes are to be made then the Sketches are simply edited, and the second step of running the macro repeated.

  1. create a new sketch , in the YZ-Plane
  2. start at origin (0,0) and draw upwards into Quadrant I
  3. the bottom end of the stemline is at the origin (0,0) - this will be the point from where the placement of all the cross-sections and transom will be made
  4. the number of line segments in this Sketch determines the number which will be required in each other Sketch
  5. save sketch
  6. for ease of identification it is probably worth naming the Sketch something like "stemline sketch"

Create the Cross-section Sketch(es)

  1. create a new sketch , in the XZ-Plane
  2. the following dialog will appear:

    The dialog is asking how far from the origin the Sketch should be placed. This will refer to how far the cross-section is from the bottom of the stemline (which was placed at (0,0)). The cross-sections can be equally spaced but need not be. The forward-most cross-section will be at Y=0 (i.e. the origin where the stemline bottom ends) or at Y<=0. The cross-sections will be at increasingly negative Y values until the transom is at the most negative Y value. In the example above, the cross-section Sketch will be placed 50 FreeCAD units from the origin on the negative Y axis.
  3. start on the Y axis and draw upwards into Quadrant I
    - the first (i.e. foremost) cross-section should start at origin (0,0) (or it will look odd as the stemline ends at 0,0) but other cross-sections need only start on the Y axis.
  4. use the same number of line segments as in the Stemline Sketch
  5. save sketch
  6. repeat as this step necessary, it may be quicker to copy this sketch and then space the copies on the Y-axis, modifications may be made to the individual Sketches as required
  7. for naming, it will make things easier to give some sort of sequence to the cross-sections, starting at the bow (i.e. the stemline) and increasing towards the stern (i.e. the transom)

Create the Transom Sketch in the XY Plane

  1. create a new sketch , in the XY-Plane
  2. start on the Y axis between quadrant III and IV, and draw upwards into Quadrant IV so that the end point is coincident with the rightmost point of the lowest cross-section Sketch in the YZ-plane
  3. use the same number of line segments as in the stemline Sketch
  4. save sketch
  5. for ease of identification it is probably worth naming the Sketch something like "transom sketch"

Save the New Document

Now save the document which contains the Sketches that will define the hull shape, giving it some name that is descriptive

Once the Sketches have all been created and positioned, the document should look like this from the top view :

The principal limitations for constructing the model are:

  • the stemline bottom should end at (0,0)
  • the bottom centremost end of each cross-section should end at the Y axis - note that it can have any Z value

This concludes the first step which is one of creating the data which the macro will use to create both half-hulls and complete-hulls. The second step is described in the following section which is titled User Interface

User Interface

In this step the macro will gather some information from the user and then process the input Sketches to generate the desired hull models. This is the only GUI image for the macro and is primarily configuration details for the production of the hull models from the Sketches:

The choices on the GUI window are:

  • Starboard half-hull
    - checking this will cause the macro to produce a starboard half-hull model
    • Mounting plaque
      - if checked the macro will mount the half-hull on a plaque
      • Allow space for keel
        - if checked will cause the half hull to be mounted higher on the plaque than the centre position, this is so a separately generated keel could be placed below the hull
  • Port half-hull
    - checking this will cause the macro to produce a port half-hull model
    • Mounting plaque
      - if checked the macro will mount the half-hull on a plaque
      • Allow space for keel
        - if checked will cause the half hull to be mounted higher on the plaque than the centre position, this is so a separately generated keel could be placed below the hull
  • Complete hull
    - checking this will cause the macro to produce a complete model
    • Bottle for complete hull
      - if checked the macro will place the complete hull inside a transparent bottle (complete with cork)
      • Allow space for keel
        - if checked will cause the half hull to be positioned higher in the bottle than the centre position, this is so a separately generated keel could be placed below the hull
  • Bulkheads for flush deck
    - checking this will cause the macro to produce bulkheads whose tops are level with the top of the hull, bulkheads will not be generated for the most forward 2 cross-sections or the aft-most 2 cross-sections
  • Bulkheads for coachhouse
    - checking this will cause the macro to produce bulkheads whose tops are possibly above the top of the hull.
    • Bulkheads to skip at bow determines how many cross-sections will be left without a bulkhead at the bow
    • Bulkheads to skip at stern determines how many cross-sections will be left without a bulkhead at the stern
  • The dimensions of the top of the bulkheads will be configured as per the following diagram:
  • Cancel button
    - the execution is halted and the window closes
  • Re-Use Last File button
    - the execution uses the data file AND SETTINGS from the the last run, any changes to settings are ignored
  • Select File button
    - the standard Open File window is opened where the user can either select a file or Cancel and exit

When the macro runs it takes configuring data from the user and then reads Sketcher sketches in the selected input file.

Note: As the macro works through the Sketches it prints out any exceptions as well as some milestones on the Report View. If you get unexpected results or some parts are missing, that is probably the first place to check.

Options

There are various types of bows and sterns for boats, with sterns having much more variety than bows. Here are examples of transoms and bows from the real world alongside the similar macro output:

Sheer Stern

Probably the most common stern, typical of all sizes of vessels from commercial ships through to rowing boats.

  • the XY transom should be as close to the aftmost cross-section as is possible.

Sugar-Scoop Stern

Most likely to be found on a sailing yacht, it is a product of designing to maximise the length of the waterline to benefit from class rules for racing under sail.

  • place the aftmost 2 cross-sections as close as is feasible, then rotate the aftmost of the two through to an angle of 45 degrees (or whatever is called for) around the X-axis

Canoe Stern

Found on all sizes of water craft, power and sail, pleasure and commercial.

  • place the aftmost 2 cross-sections as close as is feasible, then rotate the aftmost of the two through to an angle of 45 degrees around the X-axis

Normal Bow

There is a lot less variety in bow shapes than with transoms:

Trireme Bow

Although not seen very frequently in the last 2 millenia, this was once the definitive bow profile for war-making vessels:

  • in order for the bow to be correct the poly-line for the stemline needs to be drawn from the bottom to the top which will mean right to left in the Sketcher

Sample Files

These files are samples of Sketch data to use with the macro, mainly they are the models for the screen snapshots in the Options section above. The files work with the Macro and so can be downloaded and played with to adapt to your specific requirements. The prefix of 5x3 (for example) means the model has 5 cross-sections and 3 line segments per sketch

FreeCAD presently has no way to offer these sample files for download, hopefully this will be changed soon
  • 3x3 hull with the minimum number of Sketches (stemline, one cross-section, transom) and 3 line segments per Sketch
  • 5x3 with sheer transom
  • 5x3 with sugar scoop transom
  • 5x3 with canoe transom
  • 5x3 with trireme bow
  • 12x3 sailing yacht

Remarks

  • almost all the examples on this page are generated with only 3 line segments defining the side of the hull which gives a very faceted appearance, increasing the number of segments in each Sketch would generate a much smoother surface which would increase the realsism
  • doesn't do keels, skegs or rudders, in other words, it doesn't do any of the wet area
  • doesn't do square bows like push-boats or towed barges
  • doesn't do submarines (although it will do the lower half of a submarine)

Known Problems

The 'Ruled Surface' feature of FreeCAD is used to generate the hull sections from the Sketches. It can sometimes generate the wrong result and display a grater like surface instead of a smooth planar one. This will typically occur when the Sketches are rotated such as when a Sugar Scoop stern is modeled. Also angling a Sheer Transom stern can cause this. If it occurs then typically it will do so in either the half-hull models or the complete hull model - it never seems to occur in all three models for the same hull. Also it usually only happens at the extreme bow or stern. If it happens to section in the middle of the boat then most likely one of the Sketches was drawn in the wrong direction (i.e. either random sequence or top-down where as all lines should be drawn bottom-up)

It can usually be removed by using the following steps:

  • in the Model tab of the Combo View, click on the faulty segment to select it, the faulty segment will show as highlighted on the display
  • select the Data tab on the bottom half of the Combo View, the lower part of the window will have a Label "Ruled Surface" with a single parameter 'Orientation'
  • there is a popup menu to the right which has the values 'Automatic', 'Forward', 'Reversed', it will initially be set to 'Automatic'
  • try one of the other settings (remembering the faulty segment must still be selected in the upper part of the Combo View) which will usually correct the problem

The following screen snapshot shows the relevant portion of the screen:

Future Possibilities

  • replace line segments of cross-sections with curved lines
    - this is just at the idea stage but would give a much smoother surface in the vertical dimension, however the horizontal surface would still be faceted as it is now
  • integrate with Draft workbench to produce drawings from models
    - an initial goal, but the feasibility has not been investigated
  • handle keels, skegs and rudders
    - one work around for keels with the present system is to model the keel as a half-hull on it's own and then assemble it onto the bottom of the main hull; this would still do nothing for rudders and skegs though

Glossary

As with any ancient and practiced trade, a rich and sometimes confusing vocabulary has developed around ships, boats and nautical practices. In describing this macro it is both awkward and inefficient to describe the process without using the correct and accurate terms. The obvious problem is that the average lay person will be unfamiliar with such terminology, hence this vocabulary:

aft the rear aspect of anything on a boat


chine a planar facet of a hull, can be used to approximate a curved surface or as a finished building technique


coachhouse the part of the central deck which is raised above the deck level - usually to accommodate increased headroom in the interior of the boat


flush deck a deck that runs smoothly from the top of one side of the hull to the other, the converse to a coachhouse deck


forward also 'fore'; the front aspect of anything on a boat


port lefthand side looking forward


starboard righthand side looking forward


stemline the sloped vertical edge which is the bow of a hull


transom the curved top edge of the stern face which can be flat or curved

Links

Script

This code is running bug free. But due to the large range of possible inputs it may fail for some inputs. If so please report it.
Temporarily the code is located in User:Renatorivo page. Piffpoff excuse, otherwise the page is too long and can not be translated. You can put the code on a page that will not be translated or in a repository

Feel free to change this

For a rational approach to FreeCAD.

FreeCAD is very intuitive, user-friendly, but also very powerful. At first, it is easy to get lost in its countless commands. 500 commands in the basic version, plus as many complementary!!

What do you want to create or produce?

Depending on what you want to achieve, you should follow a certain workflow, and gradually discover how it works.

I think we can split FreeCAD into four parts: basic, complementary, advanced and professional.

By basic level I mean

  • Create simple 3D models
  • 2D quoted drawings (orthogonal projections), + GD & T
  • 2D prints, on paper, 3D quoted views
  • Mechanical parts
  • Architecture: plants, sections, furnishings
  • Symbolic and realistic electrical schemes
  • Symbolic and realistic electrical schemes
  • Symbolic and realistic hydraulic/gas schemes


As a complement, I mean basic support components, for example

  • Bolts
  • Fasteners
  • Libraries
  • Inspection
  • Curves
  • Plot
  • Spreadsheet
  • Test
  • Gear
  • WEB
  • Rendering
  • Import/export
  • .........


For the advanced level I mean

  • 3D printing
  • Assembly
  • Animation
  • Sheet metal
  • .....


In the professional section that is specific to a given profession, and rarely affects others

  • Architecture, project of structures ......
  • Path
  • Robot
  • FEM
  • Timber
  • PCB
  • 3D guitar
  • Ship
  • Geo data
  • Exploded
  • .....

That said, I think it is possible to propose simple workflows that quickly lead to the goal.

Some parts are already developed in tutorials, and other parts are developed in the Yorik's Manual.

Propose simple examples (the intention is one page each goal) by involving the additional workbenches also. ...........

COPIA DI SICUREZZA DI SCRIPTING

Introduzione allo Scripting

Per Scripting si intende l'uso dell'interprete Python interno di FreeCAD per generare oggetti. FreeCAD può essere usato come "ottimo" sostituto di OpenSCAD, perché possiede un vero e proprio interprete Python, con il pieno supporto per tutti i costrutti di un linguaggio di programmazione, quasi tutto quello che si può realizzare con l'interfaccia grafica è possibile realizzarlo anche attraverso un programma Python.

Le informazioni sullo scripting sono però sparse nella documentazione di FreeCAD, non c'è una uniformità di "scritture" e alcune cose sono spiegate in maniera complicata per chi comincia.


Primo assaggio

Purtroppo non esiste un modo per attivare l'editor di Python interno, però c'è un trucco, FreeCAD apre un file con estensione .py nell'editor interno di Python, niente di più semplice che creare un file con il proprio editor di testo preferito, poi aprirlo con FreeCAD.

Il modo più semplice è quello di battere queste poche righe:

"""script.py

   Primo script per FreeCAD

"""

Salvarlo e caricarlo in FreeCAD.


Il minimo indispensabile per lavorare in modo proficuo con FreeCAD è scrivere queste righe, che potete tranquillamente usare come modello:

"""nome del file.py

   Dare un nome descrittivo di quello che fa lo script

"""


import FreeCAD
from FreeCAD import Base, Vector
import Part
from math import pi, sin, cos

DOC = FreeCAD.activeDocument()
DOC_NAME = "Pippo"

def clear_doc():
    """
    Clear the active document deleting all the objects
    """
    for obj in DOC.Objects:
        DOC.removeObject(obj.Name)

def setview():
    """Rearrange View"""
    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()

else:

    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5



Alcuni trucchi che sono incorporati in questo codice:


  • import FreeCAD Questo serve per importare FreeCAD all'interno dell'interprete Python, può sembrare superfluo, ma non lo è
  • from FreeCAD import Base, Vector Base e Vector sono molto usati, vi risparmiano molto testo da battere, e se non lo fate dovete scrivere ad esempio FreeCAD.Vector ogni volta che usate un Vector


Partiamo con un piccolo script che fa poco, ma illustra la potenza di questo approccio.


def cubo(nome, lung, larg, alt):
    obj_b = DOC.addObject("Part::Box", nome)
    obj_b.Length = lung
    obj_b.Width = larg
    obj_b.Height = alt

    DOC.recompute()

    return obj_b

obj = cubo("cubo_di_prova", 5, 5, 5)

setview()


Mettetelo dopo il primo codice e premete la freccia della Barra di strumenti Macro

e vedrete che si apre un nuovo file chiamato Pippo e si visualizza un cubo nella Vista 3D,

Cubo di prova

Qualcosa in più

Niente di eccezionale, quanto ci si può aspettare da un cubo, la stessa cosa possiamo fare con un cilindro, aggiungete queste linee dopo il metodo che crea il cubo e prima della riga obj = cubo(...

def base_cyl(nome, ang, rad, alt ):
    obj = DOC.addObject("Part::Cylinder", nome)
    obj.Angle = ang
    obj.Radius = rad
    obj.Height = alt
    
    DOC.recompute()

    return obj


Anche qui nulla di eccezionale, notiamo alcune cose nella costruzione del codice:

  • L'assenza dei riferimenti usuali in molta documentazione ad App., è pienamente voluto, in futuro si potrà riusare il codice per accedere a FreeCAD dall'esterno di FreeCAD, e sarà necessario importare FreeCAD come un normale modulo Python, con alcune accortezze. La scelta è voluta anche nel solco degli standard di Python per cui è meglio sapere sempre da dove arrivano le cose, ovviamente App è poco significativo.
  • La definizione all'inizio di una "costante" DOC, per contenere FreeCAD.activeDocument(), ovviamente il nome "costante" è solo considerando dal punto di vista semantico il nostro "documento attivo", da qui l'uso della convenzione del nome "TUTTO MAIUSCOLO" per le "costanti".
  • ogni metodo ritorna un geometria, questo diventerà importante fra poco.
  • la creazione della geometria non comporta la proprietà Placement, se si utilizzano geometrie semplici per creare geometrie più complesse, la gestione della proprietà Placement è una cosa delicata.

Ora dobbiamo pur farci qualcosa con questi oggetti, quindi introduciamo le operazioni booleane. Un esempio di metodo che compie un'operazione di Unione è questo:

def fuse_obj(nome, obj_0, obj_1):
    obj = DOC.addObject("Part::Fuse", nome)
    obj.Base = obj_0
    obj.Tool = obj_1
    obj.Refine = True
    DOC.recompute()

    return obj


anche qui nulla di eccezionale, notate però l'uso di molta uniformità nel codice, aiuta molto quando si vuole fare copia e incolla nella creazioni complesse.

Inseriamo dopo il metodo base_cyl le righe sopra e modifichiamo quelle sotto in modo da leggere:

# definizione oggetti

obj = cubo("cubo_di_prova", 5, 5, 5)

obj1 = base_cyl('primo cilindro', 360,2,10)

fuse_obj("Fusione", obj, obj1)

Lanciamo con il tasto freccia della barra strumenti macro e otteniamo:

cubo e cilindro


Posizionamento

Il concetto è relativamente complesso, vedere il Tutorial aeroplano per una trattazione più sistematica.

Possiamo aver bisogno di posizionare una geometria in una posizione relativa ad un'altra geometria, cosa abbastanza frequente, il modo più comune è usare la proprietà Placement della geometria.

Ovviamente le possibilità su come specificare questa proprietà sono molte, alcune complesse da capire, questa scrittura della proprietà Placement, soprattutto per quanto riguarda la parte Rotation è in linea con quanto spiegato nel Tutorial citato e sembra la più gestibile.

FreeCAD.Placement(Vector(0,0,0), FreeCAD.Rotation(10,20,30), Vector(0,0,0))


Esiste sempre un punto di criticità, che è il punto di riferimento della costruzione, cioè il punto in base al quale è costruito l'oggetto, come descritto in questa tabella, copiata da Posizionamento:


Geometria Riferimento di Costruzione
Part::Box vertice sinistro (minimo x), frontale (minimo y), in basso (minimo z)
Part::Sphere centro della sfera (centro del suo contenitore cubico)
Part::Cylinder centro della faccia di base
Part::Cone centro della faccia di base (o superiore se il raggio della faccia di base vale 0)
Part::Torus centro del toro
Caratteristiche derivate da Sketch la caratteristica eredita la posizione dello schizzo sottostante. Lo schizzo inizia sempre con Position = (0,0,0).


Queste informazioni sono da tenere ben presente quando volete applicare una rotazione.

Facciamo qualche esempio, cancellate tutte le righe dopo il metodo base_cyl ed inserite queste righe:

def sfera(nome, rad):
    obj = DOC.addObject("Part::Sphere", nome)
    obj.Radius = rad
    
    DOC.recompute()

    return obj   


def mfuse_obj(nome, objs):
    obj = DOC.addObject("Part::MultiFuse", nome)
    obj.Shapes = objs
    obj.Refine = True
    DOC.recompute()

    return obj


def aeroplano():

    lung_fus = 30
    diam_fus = 5
    ap_alare = lung_fus * 1.75
    larg_ali = 7.5
    spess_ali = 1.5   
    alt_imp = diam_fus * 3.0  
    pos_ali = (lung_fus*0.70)
    off_ali = (pos_ali - (larg_ali * 0.5))

    obj1 = base_cyl('primo cilindro', 360, diam_fus, lung_fus)

    obj2 = cubo('ali', ap_alare, spess_ali, larg_ali, True, off_ali)

    obj3 = sfera("naso", diam_fus)
    obj3.Placement = FreeCAD.Placement(Vector(0,0,lung_fus), FreeCAD.Rotation(0,0,0), Vector(0,0,0))

    obj4 = cubo('impennaggio', spess_ali, alt_imp, larg_ali, False, 0)
    obj4.Placement = FreeCAD.Placement(Vector(0,alt_imp * -1,0), FreeCAD.Rotation(0,0,0), Vector(0,0,0))

    objs = (obj1, obj2, obj3, obj4)

    obj = mfuse_obj("Forma esempio", objs)
    obj.Placement = FreeCAD.Placement(Vector(0,0,0), FreeCAD.Rotation(0,0,0), Vector(0,0,0))
    obj.Placement = FreeCAD.Placement(Vector(0,0,0), FreeCAD.Rotation(0,0,-90), Vector(0,0,pos_ali))

    DOC.recompute()

    return obj


aeroplano()

setview()


Analizziamo il codice:

  • Abbiamo definito un metodo per creare una sfera, abbiamo usato la definizione più semplice, definendo solo il raggio.
  • Abbiamo introdotto una seconda forma per l'Unione quella multipla, niente di speciale, notate solo che alla proprietà Shapes abbiamo passato una tupla
  • Abbiamo definito una forma complessa, in modo "parametrico", cioè definendo alcuni parametri e mettendo delle formule che calcolano in modo automatico molti dei valori da passare alla geometria finale.
  • Abbiamo usato prima di ritornare l'oggetto un posizionamento usando la poprietà Rotation e il vettore finale del gruppo che definisce il centro di rotazione, secondo la scrittura Yaw-Pitch-Roll


l'aereo di esempio
aereo ruotato
Prop Placement


Potete facilmente notare che l'aereo ruota attorno al suo "baricentro" che ho fissato nel centro delle ali, in modo che la rotazione sia relativamente "naturale".

Notiamo però che se usiamo l'interfaccia grafica e visualizziamo la proprietà Placement abbiamo i dati che abbiamo inserito, questo significa che ogni modifica della proprietà modificherà il posizionamento della geometria, l'osservazione sarà importante nel proseguimento del discorso.


Alla prossima!

Other languages: