Draft: split wire related tools from Draft.py

Line Polyline BezCurve BSpline
.


.


.
This commit is contained in:
carlopav
2020-04-25 16:17:28 +02:00
committed by Yorik van Havre
parent 4eab0bb787
commit f1eaa0b93c
10 changed files with 1185 additions and 572 deletions

View File

@@ -0,0 +1,196 @@
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""This module provides the object code for Draft BezCurve.
"""
## @package bezcurve
# \ingroup DRAFT
# \brief This module provides the object code for Draft BezCurve.
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
from draftutils.utils import get_param
from draftobjects.base import DraftObject
class BezCurve(DraftObject):
"""The BezCurve object"""
def __init__(self, obj):
super(BezCurve, self).__init__(obj, "BezCurve")
_tip = "The points of the Bezier curve"
obj.addProperty("App::PropertyVectorList", "Points",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The degree of the Bezier function"
obj.addProperty("App::PropertyInteger", "Degree",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Continuity"
obj.addProperty("App::PropertyIntegerList", "Continuity",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "If the Bezier curve should be closed or not"
obj.addProperty("App::PropertyBool", "Closed",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Create a face if this curve is closed"
obj.addProperty("App::PropertyBool", "MakeFace",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The length of this object"
obj.addProperty("App::PropertyLength", "Length",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The area of this object"
obj.addProperty("App::PropertyArea", "Area",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
obj.MakeFace = get_param("fillmode", True)
obj.Closed = False
obj.Degree = 3
obj.Continuity = []
#obj.setEditorMode("Degree",2)
obj.setEditorMode("Continuity", 1)
def execute(self, fp):
self.createGeometry(fp)
fp.positionBySupport()
def _segpoleslst(self,fp):
"""Split the points into segments."""
if not fp.Closed and len(fp.Points) >= 2: #allow lower degree segment
poles=fp.Points[1:]
elif fp.Closed and len(fp.Points) >= fp.Degree: #drawable
#poles=fp.Points[1:(fp.Degree*(len(fp.Points)//fp.Degree))]+fp.Points[0:1]
poles=fp.Points[1:]+fp.Points[0:1]
else:
poles=[]
return [poles[x:x+fp.Degree] for x in \
range(0, len(poles), (fp.Degree or 1))]
def resetcontinuity(self,fp):
fp.Continuity = [0]*(len(self._segpoleslst(fp))-1+1*fp.Closed)
#nump= len(fp.Points)-1+fp.Closed*1
#numsegments = (nump // fp.Degree) + 1 * (nump % fp.Degree > 0) -1
#fp.Continuity = [0]*numsegments
def onChanged(self, fp, prop):
if prop == 'Closed':
# if remove the last entry when curve gets opened
oldlen = len(fp.Continuity)
newlen = (len(self._segpoleslst(fp))-1+1*fp.Closed)
if oldlen > newlen:
fp.Continuity = fp.Continuity[:newlen]
if oldlen < newlen:
fp.Continuity = fp.Continuity + [0]*(newlen-oldlen)
if (hasattr(fp,'Closed') and
fp.Closed and
prop in ['Points','Degree','Closed'] and
len(fp.Points) % fp.Degree):
# the curve editing tools can't handle extra points
fp.Points=fp.Points[:(fp.Degree*(len(fp.Points)//fp.Degree))]
#for closed curves
if prop in ["Degree"] and fp.Degree >= 1:
self.resetcontinuity(fp)
if prop in ["Points","Degree","Continuity","Closed"]:
self.createGeometry(fp)
def createGeometry(self,fp):
import Part
plm = fp.Placement
if fp.Points:
startpoint=fp.Points[0]
edges = []
for segpoles in self._segpoleslst(fp):
# if len(segpoles) == fp.Degree # would skip additional poles
c = Part.BezierCurve() #last segment may have lower degree
c.increase(len(segpoles))
c.setPoles([startpoint]+segpoles)
edges.append(Part.Edge(c))
startpoint = segpoles[-1]
w = Part.Wire(edges)
if fp.Closed and w.isClosed():
try:
if hasattr(fp,"MakeFace"):
if fp.MakeFace:
w = Part.Face(w)
else:
w = Part.Face(w)
except Part.OCCError:
pass
fp.Shape = w
if hasattr(fp,"Area") and hasattr(w,"Area"):
fp.Area = w.Area
if hasattr(fp,"Length") and hasattr(w,"Length"):
fp.Length = w.Length
fp.Placement = plm
@classmethod
def symmetricpoles(cls,knot, p1, p2):
"""Make two poles symmetric respective to the knot."""
p1h = App.Vector(p1)
p2h = App.Vector(p2)
p1h.multiply(0.5)
p2h.multiply(0.5)
return ( knot+p1h-p2h , knot+p2h-p1h )
@classmethod
def tangentpoles(cls,knot, p1, p2,allowsameside=False):
"""Make two poles have the same tangent at knot."""
p12n = p2.sub(p1)
p12n.normalize()
p1k = knot-p1
p2k = knot-p2
p1k_= App.Vector(p12n)
kon12=(p1k * p12n)
if allowsameside or not (kon12 < 0 or p2k * p12n > 0):# instead of moving
p1k_.multiply(kon12)
pk_k = knot - p1 - p1k_
return (p1 + pk_k, p2 + pk_k)
else:
return cls.symmetricpoles(knot, p1, p2)
@staticmethod
def modifysymmetricpole(knot,p1):
"""calculate the coordinates of the opposite pole
of a symmetric knot"""
return knot + knot - p1
@staticmethod
def modifytangentpole(knot,p1,oldp2):
"""calculate the coordinates of the opposite pole
of a tangent knot"""
pn = knot - p1
pn.normalize()
pn.multiply((knot - oldp2).Length)
return pn + knot
_BezCurve = BezCurve

View File

@@ -0,0 +1,136 @@
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""This module provides the object code for Draft BSpline.
"""
## @package bspline
# \ingroup DRAFT
# \brief This module provides the object code for Draft BSpline.
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
from draftutils.utils import get_param
from draftobjects.base import DraftObject
class BSpline(DraftObject):
"""The BSpline object"""
def __init__(self, obj):
super(BSpline, self).__init__(obj, "BSpline")
_tip = "The points of the B-spline"
obj.addProperty("App::PropertyVectorList","Points",
"Draft", QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "If the B-spline is closed or not"
obj.addProperty("App::PropertyBool","Closed",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Create a face if this spline is closed"
obj.addProperty("App::PropertyBool","MakeFace",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The area of this object"
obj.addProperty("App::PropertyArea","Area",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
obj.MakeFace = get_param("fillmode",True)
obj.Closed = False
obj.Points = []
self.assureProperties(obj)
def assureProperties(self, obj): # for Compatibility with older versions
if not hasattr(obj, "Parameterization"):
obj.addProperty("App::PropertyFloat","Parameterization","Draft",QT_TRANSLATE_NOOP("App::Property","Parameterization factor"))
obj.Parameterization = 1.0
self.knotSeq = []
def parameterization (self, pts, a, closed):
"""Computes a knot Sequence for a set of points.
fac (0-1) : parameterization factor
fac = 0 -> Uniform / fac=0.5 -> Centripetal / fac=1.0 -> Chord-Length
"""
if closed: # we need to add the first point as the end point
pts.append(pts[0])
params = [0]
for i in range(1,len(pts)):
p = pts[i].sub(pts[i-1])
pl = pow(p.Length,a)
params.append(params[-1] + pl)
return params
def onChanged(self, fp, prop):
if prop == "Parameterization":
if fp.Parameterization < 0.:
fp.Parameterization = 0.
if fp.Parameterization > 1.0:
fp.Parameterization = 1.0
def execute(self, obj):
import Part
self.assureProperties(obj)
if not obj.Points:
obj.positionBySupport()
self.knotSeq = self.parameterization(obj.Points, obj.Parameterization, obj.Closed)
plm = obj.Placement
if obj.Closed and (len(obj.Points) > 2):
if obj.Points[0] == obj.Points[-1]: # should not occur, but OCC will crash
_err = "_BSpline.createGeometry: \
Closed with same first/last Point. Geometry not updated."
App.Console.PrintError(QT_TRANSLATE_NOOP('Draft', _err)+"\n")
return
spline = Part.BSplineCurve()
spline.interpolate(obj.Points, PeriodicFlag = True, Parameters = self.knotSeq)
# DNC: bug fix: convert to face if closed
shape = Part.Wire(spline.toShape())
# Creating a face from a closed spline cannot be expected to always work
# Usually, if the spline is not flat the call of Part.Face() fails
try:
if hasattr(obj,"MakeFace"):
if obj.MakeFace:
shape = Part.Face(shape)
else:
shape = Part.Face(shape)
except Part.OCCError:
pass
obj.Shape = shape
if hasattr(obj,"Area") and hasattr(shape,"Area"):
obj.Area = shape.Area
else:
spline = Part.BSplineCurve()
spline.interpolate(obj.Points, PeriodicFlag = False, Parameters = self.knotSeq)
shape = spline.toShape()
obj.Shape = shape
if hasattr(obj,"Area") and hasattr(shape,"Area"):
obj.Area = shape.Area
obj.Placement = plm
obj.positionBySupport()
_BSpline = BSpline

View File

@@ -0,0 +1,251 @@
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""This module provides the object code for Draft Wire.
"""
## @package wire
# \ingroup DRAFT
# \brief This module provides the object code for Draft Wire.
import math
import FreeCAD as App
import DraftGeomUtils
import DraftVecUtils
from PySide.QtCore import QT_TRANSLATE_NOOP
from draftutils.utils import get_param
from draftobjects.base import DraftObject
class Wire(DraftObject):
"""The Wire object"""
def __init__(self, obj):
super(Wire, self).__init__(obj, "Wire")
_tip = "The vertices of the wire"
obj.addProperty("App::PropertyVectorList","Points",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "If the wire is closed or not"
obj.addProperty("App::PropertyBool","Closed",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The base object is the wire, it's formed from 2 objects"
obj.addProperty("App::PropertyLink","Base",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The tool object is the wire, it's formed from 2 objects"
obj.addProperty("App::PropertyLink","Tool",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The start point of this line"
obj.addProperty("App::PropertyVectorDistance","Start",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The end point of this line"
obj.addProperty("App::PropertyVectorDistance","End",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The length of this line"
obj.addProperty("App::PropertyLength","Length",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Radius to use to fillet the corners"
obj.addProperty("App::PropertyLength","FilletRadius",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Size of the chamfer to give to the corners"
obj.addProperty("App::PropertyLength","ChamferSize",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "Create a face if this object is closed"
obj.addProperty("App::PropertyBool","MakeFace",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The number of subdivisions of each edge"
obj.addProperty("App::PropertyInteger","Subdivisions",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
_tip = "The area of this object"
obj.addProperty("App::PropertyArea","Area",
"Draft",QT_TRANSLATE_NOOP("App::Property", _tip))
obj.MakeFace = get_param("fillmode",True)
obj.Closed = False
def execute(self, obj):
import Part
plm = obj.Placement
if obj.Base and (not obj.Tool):
if obj.Base.isDerivedFrom("Sketcher::SketchObject"):
shape = obj.Base.Shape.copy()
if obj.Base.Shape.isClosed():
if hasattr(obj,"MakeFace"):
if obj.MakeFace:
shape = Part.Face(shape)
else:
shape = Part.Face(shape)
obj.Shape = shape
elif obj.Base and obj.Tool:
if hasattr(obj.Base,'Shape') and hasattr(obj.Tool,'Shape'):
if (not obj.Base.Shape.isNull()) and (not obj.Tool.Shape.isNull()):
sh1 = obj.Base.Shape.copy()
sh2 = obj.Tool.Shape.copy()
shape = sh1.fuse(sh2)
if DraftGeomUtils.isCoplanar(shape.Faces):
shape = DraftGeomUtils.concatenate(shape)
obj.Shape = shape
p = []
for v in shape.Vertexes: p.append(v.Point)
if obj.Points != p: obj.Points = p
elif obj.Points:
if obj.Points[0] == obj.Points[-1]:
if not obj.Closed: obj.Closed = True
obj.Points.pop()
if obj.Closed and (len(obj.Points) > 2):
pts = obj.Points
if hasattr(obj,"Subdivisions"):
if obj.Subdivisions > 0:
npts = []
for i in range(len(pts)):
p1 = pts[i]
npts.append(pts[i])
if i == len(pts)-1:
p2 = pts[0]
else:
p2 = pts[i+1]
v = p2.sub(p1)
v = DraftVecUtils.scaleTo(v,v.Length/(obj.Subdivisions+1))
for j in range(obj.Subdivisions):
npts.append(p1.add(App.Vector(v).multiply(j+1)))
pts = npts
shape = Part.makePolygon(pts+[pts[0]])
if "ChamferSize" in obj.PropertiesList:
if obj.ChamferSize.Value != 0:
w = DraftGeomUtils.filletWire(shape,obj.ChamferSize.Value,chamfer=True)
if w:
shape = w
if "FilletRadius" in obj.PropertiesList:
if obj.FilletRadius.Value != 0:
w = DraftGeomUtils.filletWire(shape,obj.FilletRadius.Value)
if w:
shape = w
try:
if hasattr(obj,"MakeFace"):
if obj.MakeFace:
shape = Part.Face(shape)
else:
shape = Part.Face(shape)
except Part.OCCError:
pass
else:
edges = []
pts = obj.Points[1:]
lp = obj.Points[0]
for p in pts:
if not DraftVecUtils.equals(lp,p):
if hasattr(obj,"Subdivisions"):
if obj.Subdivisions > 0:
npts = []
v = p.sub(lp)
v = DraftVecUtils.scaleTo(v,v.Length/(obj.Subdivisions+1))
edges.append(Part.LineSegment(lp,lp.add(v)).toShape())
lv = lp.add(v)
for j in range(obj.Subdivisions):
edges.append(Part.LineSegment(lv,lv.add(v)).toShape())
lv = lv.add(v)
else:
edges.append(Part.LineSegment(lp,p).toShape())
else:
edges.append(Part.LineSegment(lp,p).toShape())
lp = p
try:
shape = Part.Wire(edges)
except Part.OCCError:
print("Error wiring edges")
shape = None
if "ChamferSize" in obj.PropertiesList:
if obj.ChamferSize.Value != 0:
w = DraftGeomUtils.filletWire(shape,obj.ChamferSize.Value,chamfer=True)
if w:
shape = w
if "FilletRadius" in obj.PropertiesList:
if obj.FilletRadius.Value != 0:
w = DraftGeomUtils.filletWire(shape,obj.FilletRadius.Value)
if w:
shape = w
if shape:
obj.Shape = shape
if hasattr(obj,"Area") and hasattr(shape,"Area"):
obj.Area = shape.Area
if hasattr(obj,"Length"):
obj.Length = shape.Length
obj.Placement = plm
obj.positionBySupport()
self.onChanged(obj,"Placement")
def onChanged(self, obj, prop):
if prop == "Start":
pts = obj.Points
invpl = App.Placement(obj.Placement).inverse()
realfpstart = invpl.multVec(obj.Start)
if pts:
if pts[0] != realfpstart:
pts[0] = realfpstart
obj.Points = pts
elif prop == "End":
pts = obj.Points
invpl = App.Placement(obj.Placement).inverse()
realfpend = invpl.multVec(obj.End)
if len(pts) > 1:
if pts[-1] != realfpend:
pts[-1] = realfpend
obj.Points = pts
elif prop == "Length":
if obj.Shape and not obj.Shape.isNull():
if obj.Length.Value != obj.Shape.Length:
if len(obj.Points) == 2:
v = obj.Points[-1].sub(obj.Points[0])
v = DraftVecUtils.scaleTo(v,obj.Length.Value)
obj.Points = [obj.Points[0],obj.Points[0].add(v)]
elif prop == "Placement":
pl = App.Placement(obj.Placement)
if len(obj.Points) >= 2:
displayfpstart = pl.multVec(obj.Points[0])
displayfpend = pl.multVec(obj.Points[-1])
if obj.Start != displayfpstart:
obj.Start = displayfpstart
if obj.End != displayfpend:
obj.End = displayfpend
_Wire = Wire