Skip to content
Draft
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,7 @@ docs/_build/

# PyBuilder
target/

.vscode
.vscode/settings.json

17 changes: 10 additions & 7 deletions OCCUtils/Common.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def color(r, g, b):


def to_string(_string):
from OCC.TCollection import TCollection_ExtendedString
from OCC.Core.TCollection import TCollection_ExtendedString
return TCollection_ExtendedString(_string)


Expand Down Expand Up @@ -360,7 +360,7 @@ def intersection_from_three_planes(planeA, planeB, planeC):
@param planeC:
@param show:
'''
from OCC.IntAna import IntAna_Int3Pln
from OCC.Core.IntAna import IntAna_Int3Pln

planeA = planeA if not hasattr(planeA, 'Pln') else planeA.Pln()
planeB = planeB if not hasattr(planeB, 'Pln') else planeB.Pln()
Expand All @@ -387,7 +387,7 @@ def intersect_shape_by_line(topods_shape, line, low_parameter=0.0, hi_parameter=
and the u,v,w parameters of the intersection point
:raise:
"""
from OCC.IntCurvesFace import IntCurvesFace_ShapeIntersector
from OCC.Core.IntCurvesFace import IntCurvesFace_ShapeIntersector
shape_inter = IntCurvesFace_ShapeIntersector()
shape_inter.Load(topods_shape, TOLERANCE)
shape_inter.PerformNearest(line, low_parameter, hi_parameter)
Expand Down Expand Up @@ -516,13 +516,16 @@ def vertex2pnt(vertex):
return BRep_Tool.Pnt(vertex)


def adapt_edge_to_curve(edg):
def adapt_edge_to_curve(edg, a=0., b=0.):
'''
returns a curve adaptor from an edge
returns a curve adaptor from an edge (GeomAdabtor_Curve)
@param edg: TopoDS_Edge
'''
return BRepAdaptor_Curve(edg)

if a==0 and b==0:
return BRepAdaptor_Curve(edg).Curve()
else:
Curve = BRepAdaptor_Curve(edg).Curve()
return GeomAdabtor_Curve(Curve, a, b)

def adapt_edge_to_hcurve(edg):
c = BRepAdaptor_HCurve()
Expand Down
128 changes: 87 additions & 41 deletions OCCUtils/Construct.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
from OCC.Core.BRep import BRep_Tool
from OCC.Core.BRepAdaptor import BRepAdaptor_HCurve
from OCC.Core.BRepOffset import BRepOffset_Skin
from OCC.Geom import Geom_TrimmedCurve
from OCC.GeomConvert import GeomConvert_ApproxCurve
from OCC.GeomLProp import GeomLProp_SLProps
from OCC.Core.Geom import Geom_TrimmedCurve
from OCC.Core.GeomConvert import GeomConvert_ApproxCurve
from OCC.Core.GeomLProp import GeomLProp_SLProps
from OCC.Core.BRepBuilderAPI import (BRepBuilderAPI_MakeFace,
BRepBuilderAPI_Transform,
BRepBuilderAPI_Sewing,
Expand All @@ -46,14 +46,14 @@
BRepBuilderAPI_FindPlane)
from OCC.Core.BRepPrimAPI import (BRepPrimAPI_MakeBox, BRepPrimAPI_MakePrism)
from OCC.Core.BRepOffsetAPI import BRepOffsetAPI_MakeEvolved
from OCC.GeomAbs import (GeomAbs_Arc, GeomAbs_C2, GeomAbs_C0, GeomAbs_Tangent,
from OCC.Core.GeomAbs import (GeomAbs_Arc, GeomAbs_C2, GeomAbs_C0, GeomAbs_Tangent,
GeomAbs_Intersection, GeomAbs_G1, GeomAbs_G2,
GeomAbs_C1)
from OCC.Core.TopAbs import TopAbs_REVERSED
from OCC.Core.TopoDS import (TopoDS_Wire, TopoDS_Solid, TopoDS_Vertex, TopoDS_Shape,
TopoDS_Builder, TopoDS_Compound)
from OCC.TColgp import TColgp_SequenceOfVec, TColgp_HArray1OfPnt
from OCC.gp import (gp_Vec, gp_Pnt, gp_Dir, gp_Trsf, gp_Ax1, gp_Quaternion,
from OCC.Core.TColgp import TColgp_SequenceOfVec, TColgp_HArray1OfPnt
from OCC.Core.gp import (gp_Vec, gp_Pnt, gp_Dir, gp_Trsf, gp_Ax1, gp_Quaternion,
gp_Circ, gp_Pln)

from OCCUtils.Common import (TOLERANCE, assert_isdone, to_tcol_, to_adaptor_3d,
Expand All @@ -62,6 +62,11 @@
from OCCUtils.types_lut import ShapeToTopology
from OCCUtils.Topology import Topo

from OCC.Core.TopoDS import (topods, TopoDS_Wire, TopoDS_Vertex, TopoDS_Edge,
TopoDS_Face, TopoDS_Shell, TopoDS_Solid,
TopoDS_Compound, TopoDS_CompSolid, topods_Edge,
topods_Vertex, TopoDS_Iterator)


EPSILON = TOLERANCE = 1e-6
ST = ShapeToTopology()
Expand Down Expand Up @@ -200,6 +205,9 @@ def gp_pnt_div(self, other):
# ---TOPOLOGY---
#===========================================================================

def point_from_vertex(vert):
brt = BRep_Tool()
return brt.Pnt(topods_Vertex(vert))

@wraps(BRepBuilderAPI_MakeSolid)
def make_solid(*args):
Expand Down Expand Up @@ -312,6 +320,16 @@ def make_closed_polygon(*args):
#===========================================================================


def make_edge_from_vert(vlist):
"""
expect 2 vertices in vlist, make an edge out of it
"""
brt = BRep_Tool()
pnts = []
for v in vlist:
pnts.append(brt.Pnt(topods_Vertex(v)))
return make_edge(pnts[0], pnts[1])

def make_circle(pnt, radius):
'''
returns an edge
Expand Down Expand Up @@ -472,6 +490,7 @@ def make_oriented_box(v_corner, v_x, v_y, v_z):
bottom = make_face(p)
top = translate_topods_from_vector(bottom, v_z, True)
oriented_bbox = make_solid(sew_shapes([bottom, shp, top]))
#oriented_bbox = make_solid(sew_shapes([bottom, shp, top])[0])
return oriented_bbox


Expand Down Expand Up @@ -518,7 +537,6 @@ def make_n_sided(edges, points, continuity=GeomAbs_C0):
face = n_sided.Face()
return face


def make_n_sections(edges):
from OCC.Core.TopTools import TopTools_SequenceOfShape
from OCC.Core.BRepFill import BRepFill_NSections
Expand All @@ -529,8 +547,15 @@ def make_n_sections(edges):
return n_sec


def flip_edge(edge):
tp = Topo(edge)
vertices = reversed(list(tp.vertices_from_edge(edge)))
return make_edge_from_vert(vertices)



def make_coons(edges):
from OCC.GeomFill import GeomFill_BSplineCurves, GeomFill_StretchStyle
from OCC.Core import GeomFill_BSplineCurves, GeomFill_StretchStyle
if len(edges) == 4:
spl1, spl2, spl3, spl4 = edges
srf = GeomFill_BSplineCurves(spl1, spl2, spl3, spl4, GeomFill_StretchStyle)
Expand All @@ -545,25 +570,26 @@ def make_coons(edges):
return srf.Surface()


def make_constrained_surface_from_edges(edges):
def make_constrained_surface_from_edges(edges): #, w
'''
DOESNT RESPECT BOUNDARIES
'''
from OCC.GeomPlate import GeomPlate_MakeApprox, GeomPlate_BuildPlateSurface
from OCC.Core.GeomPlate import GeomPlate_MakeApprox, GeomPlate_BuildPlateSurface
from OCC.Core.BRepFill import BRepFill_CurveConstraint
bpSrf = GeomPlate_BuildPlateSurface(3, 15, 2)
for edg in edges:
c = BRepAdaptor_HCurve()
c.ChangeCurve().Initialize(edg)
constraint = BRepFill_CurveConstraint(c.GetHandle(), 0)
bpSrf.Add(constraint.GetHandle())
bpSrf.Add(constraint)
bpSrf.Perform()
maxSeg, maxDeg, critOrder = 9, 8, 0
tol = 1e-4
srf = bpSrf.Surface()
plate = GeomPlate_MakeApprox(srf, tol, maxSeg, maxDeg, tol, critOrder)
uMin, uMax, vMin, vMax = srf.GetObject().Bounds()
uMin, uMax, vMin, vMax = srf.Bounds() #srf.GetObject().Bounds()
face = make_face(plate.Surface(), uMin, uMax, vMin, vMax)
#face = make_face(srf, w, False) #plate.Surface(), uMin, uMax, vMin, vMax)
return face


Expand All @@ -584,7 +610,7 @@ def add_wire_to_face(face, wire, reverse=False):
return result


def sew_shapes(shapes, tolerance=0.001):
def sew_shapes(shapes, tolerance=0.001, verbose=True):
sew = BRepBuilderAPI_Sewing(tolerance)
for shp in shapes:
if isinstance(shp, list):
Expand All @@ -593,12 +619,13 @@ def sew_shapes(shapes, tolerance=0.001):
else:
sew.Add(shp)
sew.Perform()
print("n degenerated shapes", sew.NbDegeneratedShapes())
print("n deleted faces:", sew.NbDeletedFaces())
print("n free edges", sew.NbFreeEdges())
print("n multiple edges:", sew.NbMultipleEdges())
if verbose:
print("n degenerated shapes", sew.NbDegeneratedShapes())
print("n deleted faces:", sew.NbDeletedFaces())
print("n free edges", sew.NbFreeEdges())
print("n multiple edges:", sew.NbMultipleEdges())
result = ShapeToTopology()(sew.SewedShape())
return result
return result, sew

#===========================================================================
# ---BOOL---
Expand All @@ -607,10 +634,10 @@ def sew_shapes(shapes, tolerance=0.001):

def boolean_cut(shapeToCutFrom, cuttingShape):
from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Cut
try:
cut = BRepAlgoAPI_Cut(shapeToCutFrom, cuttingShape)
print("Can work?", cut.BuilderCanWork())
_error = {0: '- Ok',
#try:
cut = BRepAlgoAPI_Cut(shapeToCutFrom, cuttingShape)
print("Can work?", cut.BuilderCanWork())
_error = {0: '- Ok',
1: '- The Object is created but Nothing is Done',
2: '- Null source shapes is not allowed',
3: '- Check types of the arguments',
Expand All @@ -619,15 +646,16 @@ def boolean_cut(shapeToCutFrom, cuttingShape):
6: '- Unknown operation is not allowed',
7: '- Can not allocate memory for the Builder',
}
print("Error status:", _error[cut.ErrorStatus()])
cut.RefineEdges()
cut.FuseEdges()
shp = cut.Shape()
cut.Destroy()
return shp
except:
print("Failed to boolean cut")
return shapeToCutFrom
print("Error status:", _error[cut.ErrorStatus()])
cut.RefineEdges()
cut.FuseEdges()
shp = cut.Shape()
print(dir(cut))
#cut.Destroy()
return shp
#except:
# print("Failed to boolean cut")
# return shapeToCutFrom


def boolean_fuse(shapeToCutFrom, joiningShape):
Expand All @@ -636,7 +664,7 @@ def boolean_fuse(shapeToCutFrom, joiningShape):
join.RefineEdges()
join.FuseEdges()
shape = join.Shape()
join.Destroy()
#join.Destroy()
return shape


Expand All @@ -648,7 +676,7 @@ def trim_wire(wire, shapeLimit1, shapeLimit2, periodic=False):
adap = to_adaptor_3d(wire)
bspl = adap.BSpline()
if periodic:
spl = bspl.GetObject()
spl = bspl # .GetObject()
if spl.IsClosed():
spl.SetPeriodic()
else:
Expand All @@ -665,23 +693,41 @@ def trim_wire(wire, shapeLimit1, shapeLimit2, periodic=False):


def fix_shape(shp, tolerance=1e-3):
from OCC.ShapeFix import ShapeFix_Shape
from OCC.Core.ShapeFix import ShapeFix_Shape
fix = ShapeFix_Shape(shp)
fix.SetFixFreeShellMode(True)
sf = fix.FixShellTool().GetObject()
sf = fix.FixShellTool() #.GetObject()
sf.SetFixOrientationMode(True)
fix.LimitTolerance(tolerance)
fix.Perform()
return fix.Shape()


def fix_face(shp, tolerance=1e-3):
from OCC.ShapeFix import ShapeFix_Face
from OCC.Core.ShapeFix import ShapeFix_Face
fix = ShapeFix_Face(shp)
fix.SetMaxTolerance(tolerance)
fix.Perform()
return fix.Face()

def fix_small_faces(shp, prec, tolerance=1e-3):
from OCC.Core.ShapeFix import ShapeFix_FixSmallFace
fix = ShapeFix_FixSmallFace()
fix.Init(shp)
fix.SetPrecision(prec)
fix.SetMaxTolerance(tolerance)
fix.Perform()
return fix.FixShape()

def fix_solid(shp, tolerance=1e-3):
from OCC.Core.ShapeFix import ShapeFix_Solid
fix = ShapeFix_Solid(shp)
fix.SetCreateOpenSolidMode(True)
fix.SetMaxTolerance(tolerance)
fix.Perform()
# print(dir(fix))
return fix.Solid()

#===========================================================================
# --- TRANSFORM ---
#===========================================================================
Expand Down Expand Up @@ -777,7 +823,7 @@ def face_normal(face):


def face_from_plane(_geom_plane, lowerLimit=-1000, upperLimit=1000):
from OCC.Geom import Geom_RectangularTrimmedSurface
from OCC.Core.Geom import Geom_RectangularTrimmedSurface
_trim_plane = make_face(Geom_RectangularTrimmedSurface(_geom_plane.GetHandle(), lowerLimit, upperLimit, lowerLimit, upperLimit).GetHandle())
return _trim_plane

Expand All @@ -786,7 +832,7 @@ def find_plane_from_shape(shape, tolerance=-1):
try:
fpl = BRepBuilderAPI_FindPlane(shape, tolerance)
if fpl.Found():
return fpl.Plane().GetObject()
return fpl.Plane() #.GetObject()
else:
return None
except:
Expand All @@ -798,7 +844,7 @@ def fit_plane_through_face_vertices(_face):
:param _face: OCC.KBE.face.Face instance
:return: Geom_Plane
"""
from OCC.GeomPlate import GeomPlate_BuildAveragePlane
from OCC.Core.GeomPlate import GeomPlate_BuildAveragePlane

uvs_from_vertices = [_face.project_vertex(vertex2pnt(i)) for i in Topo(_face).vertices()]
normals = [gp_Vec(_face.DiffGeom.normal(*uv[0])) for uv in uvs_from_vertices]
Expand All @@ -808,7 +854,7 @@ def fit_plane_through_face_vertices(_face):
[NORMALS.Append(i) for i in normals]
POINTS = to_tcol_(points, TColgp_HArray1OfPnt)

pl = GeomPlate_BuildAveragePlane(NORMALS, POINTS).Plane().GetObject()
pl = GeomPlate_BuildAveragePlane(NORMALS, POINTS).Plane() #.GetObject()
vec = gp_Vec(pl.Location(), _face.GlobalProperties.centre())
pt = (pl.Location().as_vec() + vec).as_pnt()
pl.SetLocation(pt)
Expand All @@ -821,7 +867,7 @@ def project_edge_onto_plane(edg, plane):
:param plane: Geom_Plane
:return: TopoDS_Edge projected on the plane
"""
from OCC.GeomProjLib import geomprojlib_ProjectOnPlane
from OCC.Core.GeomProjLib import geomprojlib_ProjectOnPlane
proj = geomprojlib_ProjectOnPlane(edg.adaptor.Curve().Curve(), plane.GetHandle(), plane.Axis().Direction(), 1)
return make_edge(proj)

Expand Down
Loading