There are problems that usually puzzle a coder, and usually they are related to Vector math.
But FreeCAD is clever enough to ease the work, only my knowledge was limited.
So after having banging my head, I have put together some code to sort out a problem and surprisingly the answer is already in FreeCAD without complicated calculations.
Here the code:
And a little extract from complete code.
Code: Select all
"""Sample code.
This code was written as an sample code
Name: 20221116-rotation.py
Author: Carlo Dormeletti
Copyright: 2022
Licence: CC BY-NC-ND 4.0 IT
"""
# See real service code on attachment
# the code here is shortened to save some space
pt1 = Vector(10, 20, 0)
pt2 = Vector(20, 50, 15)
c_length = pt1.distanceToPoint(pt2)
c_axis = pt2.sub(pt1).normalize()
l1 = Part.LineSegment(pt1, pt2)
Part.show(l1.toShape(), "line")
t1 = Part.makeCylinder(0.5, c_length, pt1, c_axis)
Part.show(t1, "tube")
The problem is create a cylinder (but with some abstraction and care every object) between two points.
code is almost clear and use a minimal math, the remaining work is done by FreeCAD.
Let's see what help() says about Part.makeCylinder method:
Code: Select all
help(Part.makeCylinder)
Help on built-in function makeCylinder:
makeCylinder(...) method of builtins.tuple instance
makeCylinder(radius,height,[pnt,dir,angle]) -- Make a cylinder with a given radius and height
By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360
key point are:
- pnt this place the reference point for a cilynder that happens to be the center of the bottom face.
- dir this is prove to be the Axis of the created shape.
https://wiki.freecadweb.org/Placement
To see the "reference points" that sadly are not so easy to guess, as many users have learned.
The concept of pnt, is easy in our example is pt1, not many calculations to do.
The dir could be complicated, but maybe using an implrecise term is the axis of the cylinder, it could be obtained without too much hassle using a little Vector math.
Code: Select all
c_axis = pt2.sub(pt1).normalize()
One other thing is height of the cylinder, that is obtained with another FreeCAD supplied Vector method. .distanceToPoint() quite easy.
Result could be easily checked as submitted code will make a line and cylinder, you could toggle visibility of the cylinder to see that the line, is at ceter of the cylinder, ot better modify the Transparency property to see through.
try maybe to decomment the lines:
Code: Select all
# t2 = Part.makeCone(0.5, 0, c_length, pt1, c_axis)
# Part.show(t2, "cone")
It is not trivial to retrieve the inverse, or at least for now I've not find a way to obtain pnt and dir from the created Solid.
But maybe some other expert will expand this post.
I hope this will be useful for some user.
Regards.
Carlo D.