def _cut_finger_notch(front, dx, dz): finger_width = 2.0 finger_height = 1.0 front = _cut(front, _box(_pnt(dx / 2. - finger_width / 2., 0, dz - finger_height), finger_width, THICKNESS_0, finger_height)) cyl = BRepPrimAPI_MakeCylinder(finger_width / 2.0, THICKNESS_0).Shape() tr = gp.gp_Trsf() tr.SetRotation(gp.gp_Ax1(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(1, 0, 0)), math.pi / 2.0) tr2 = gp.gp_Trsf() tr2.SetTranslation(gp.gp_Vec(dx / 2., THICKNESS_0, dz - finger_height)) tr2.Multiply(tr) cyl = BRepBuilderAPI_Transform(cyl, tr2, True).Shape() front = _cut(front, cyl) return front
def occ(display): ''' display, start_display, add_menu, add_function_to_menu = init_display() my_box = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() display.DisplayShape(my_box, update=True) #start_display() ''' display.EraseAll() ais_boxshp = build_shape(display) ax1 = gp_Ax1(gp_Pnt(25., 25., 25.), gp_Dir(0., 0., 1.)) aCubeTrsf = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): aCubeTrsf.SetRotation(ax1, angle) aCubeToploc = TopLoc_Location(aCubeTrsf) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2*pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def scale(self, scale): tr = gp_Trsf() #tr.SetScale(gp_Pnt(*point), scale) tr.SetScaleFactor(scale) self.shape = BRepBuilderAPI_Transform(self.shape, tr).Shape() self.__extract_curves() return self
def copyToZ(self, z): "makes a copy of this slice, transformed to the specified z height" theCopy = Slice() theCopy.zLevel = z theCopy.zHeight = self.zHeight theCopy.sliceHeight = self.sliceHeight theCopy.fillWidth = self.fillWidth theCopy.hatchDir = self.hatchDir theCopy.checkSum = self.checkSum #make transformation p1 = gp.gp_Pnt(0, 0, 0) p2 = gp.gp_Pnt(0, 0, z) xform = gp.gp_Trsf() xform.SetTranslation(p1, p2) bt = BRepBuilderAPI.BRepBuilderAPI_Transform(xform) #copy all of the faces for f in hSeqIterator(self.faces): bt.Perform(f, True) theCopy.addFace(Wrappers.cast(bt.Shape())) #copy all of the fillWires for w in hSeqIterator(self.fillWires): bt.Perform(w, True) #TestDisplay.display.showShape(bt.Shape() ); theCopy.fillWires.Append(Wrappers.cast(bt.Shape())) #copy all of the fillEdges for e in hSeqIterator(self.fillEdges): bt.Perform(e, True) #TestDisplay.display.showShape(bt.Shape() ); theCopy.fillEdges.Append(Wrappers.cast(bt.Shape())) return theCopy
def rotate(occtopology, rot_pypt, pyaxis, degree): """ This function rotates an OCCtopology based on the rotation point, an axis and the rotation degree. Parameters ---------- occtopology : OCCtopology The OCCtopology to be rotated. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex rot_pypt : tuple of floats The OCCtopology will rotate in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) pyaxis : tuple of floats The OCCtopology will rotate along this axis. A pyaxis is a tuple that documents the xyz of a direction e.g. (x,y,z) degree : float The degree of rotation. Returns ------- rotated topology : OCCtopology (OCCshape) The rotated OCCtopology. """ from math import radians gp_ax3 = gp_Ax1(gp_Pnt(rot_pypt[0], rot_pypt[1], rot_pypt[2]), gp_Dir(pyaxis[0], pyaxis[1], pyaxis[2])) aTrsf = gp_Trsf() aTrsf.SetRotation(gp_ax3, radians(degree)) rot_brep = BRepBuilderAPI_Transform(aTrsf) rot_brep.Perform(occtopology, True) rot_shape = rot_brep.Shape() return rot_shape
def _rotate(self, direction, angle): new = gp_Trsf() new.SetRotation(direction, angle) self.wrapped = self.wrapped * new
def move(orig_pypt, location_pypt, occtopology): """ This function moves an OCCtopology from the orig_pypt to the location_pypt. Parameters ---------- orig_pypt : tuple of floats The OCCtopology will move in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) location_pypt : tuple of floats The destination of where the OCCtopology will be moved in relation to the orig_pypt. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) occtopology : OCCtopology The OCCtopology to be moved. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex Returns ------- moved topology : OCCtopology (OCCshape) The moved OCCtopology. """ gp_ax31 = gp_Ax3(gp_Pnt(orig_pypt[0], orig_pypt[1], orig_pypt[2]), gp_DZ()) gp_ax32 = gp_Ax3(gp_Pnt(location_pypt[0], location_pypt[1], location_pypt[2]), gp_DZ()) aTrsf = gp_Trsf() aTrsf.SetTransformation(gp_ax32,gp_ax31) trsf_brep = BRepBuilderAPI_Transform(aTrsf) trsf_brep.Perform(occtopology, True) trsf_shp = trsf_brep.Shape() return trsf_shp
def add_labels(product, lr, st): if product.links: for link in product.links: if link.product.doc_id != product.doc_id: if not link.product.label_reference: lr_2 = TDF_LabelSequence() si = StepImporter(link.product.doc_path) shape_tool = si.shape_tool shape_tool.GetFreeShapes(lr_2) add_labels(link.product, lr_2.Value(1), shape_tool) link.product.label_reference = lr_2.Value(1) # FIXME: free memory del si gc.collect() for d in range(link.quantity): transformation = gp_Trsf() loc = link.locations[d] transformation.SetValues(loc.x1, loc.x2, loc.x3, loc.x4, loc.y1, loc.y2, loc.y3, loc.y4, loc.z1, loc.z2, loc.z3, loc.z4, 1, 1) new_label = st.AddComponent( lr, link.product.label_reference, TopLoc_Location(transformation)) set_label_name(new_label, link.names[d])
def get_transform(self): d = self.declaration t = gp_Trsf() #: TODO: Order matters... how to configure it??? if d.mirror: try: p, v = d.mirror except ValueError: raise ValueError("You must specify a tuple containing a " "(point, direction)") t.SetMirror(gp_Ax1(gp_Pnt(*p), gp_Dir(*v))) if d.scale: try: p, s = d.scale except ValueError: raise ValueError("You must specify a tuple containing a " "(point, scale)") t.SetScale(gp_Pnt(*p), s) if d.translate: t.SetTranslation(gp_Vec(*d.translate)) if d.rotate: try: p, v, a = d.rotate except ValueError: raise ValueError("You must specify a tuple containing a " "(point, direction, angle)") t.SetRotation(gp_Ax1(gp_Pnt(*p), gp_Dir(*v)), a) return t
def translate(self, vec): tr = gp_Trsf() tr.SetTranslation(gp_Vec(*vec)) loc = TopLoc_Location(tr) self.shape.Move(loc) self.__extract_curves() return self
def get_transform(self): d = self.declaration t = gp_Trsf() #: TODO: Order matters... how to configure it??? if d.mirror: try: p,v = d.mirror except ValueError: raise ValueError("You must specify a tuple containing a (point,direction)") t.SetMirror(gp_Ax1(gp_Pnt(*p), gp_Dir(*v))) if d.scale: try: p,s = d.scale except ValueError: raise ValueError("You must specify a tuple containing a (point,scale)") t.SetScale(gp_Pnt(*p),s) if d.translate: t.SetTranslation(gp_Vec(*d.translate)) if d.rotate: try: p,v,a = d.rotate except ValueError: raise ValueError("You must specify a tuple containing a (point,direction,angle)") t.SetRotation(gp_Ax1(gp_Pnt(*p), gp_Dir(*v)),a) return t
def copyToZ(self, z): "makes a copy of this slice, transformed to the specified z height" theCopy = Slice() theCopy.zLevel = z theCopy.zHeight = self.zHeight theCopy.sliceHeight = self.sliceHeight theCopy.fillWidth = self.fillWidth theCopy.hatchDir = self.hatchDir theCopy.checkSum = self.checkSum # make transformation p1 = gp.gp_Pnt(0, 0, 0) p2 = gp.gp_Pnt(0, 0, z) xform = gp.gp_Trsf() xform.SetTranslation(p1, p2) bt = BRepBuilderAPI.BRepBuilderAPI_Transform(xform) # copy all of the faces for f in hSeqIterator(self.faces): bt.Perform(f, True) theCopy.addFace(Wrappers.cast(bt.Shape())) # copy all of the fillWires for w in hSeqIterator(self.fillWires): bt.Perform(w, True) # TestDisplay.display.showShape(bt.Shape() ); theCopy.fillWires.Append(Wrappers.cast(bt.Shape())) # copy all of the fillEdges for e in hSeqIterator(self.fillEdges): bt.Perform(e, True) # TestDisplay.display.showShape(bt.Shape() ); theCopy.fillEdges.Append(Wrappers.cast(bt.Shape())) return theCopy
def _add_stuff_changed(self, old, new): for i in xrange(20): brep = BRepPrimAPI_MakeCylinder(random.random()*50, random.random()*50).Shape() trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(random.random()*100, random.random()*100, random.random()*100)) brep.Move(TopLoc_Location(trsf)) self.shapes.append(brep)
def align_planes_byNormal(shp_add, normalDir_base, normalDir_add): """[summary] Arguments: shp_add {topoDS_Shape} -- [description] normalDir_base {gp_Dir} -- [description] normalDir_add {gp_Dir} -- [description] rotateAng [deg]{float} -- [description] """ if not normalDir_base.IsParallel(normalDir_add, radians(0.01)): rotateAxDir = normalDir_base.Crossed(normalDir_add) # determin rotate angle rotRelAng = degrees( normalDir_base.AngleWithRef(normalDir_add, rotateAxDir)) if rotRelAng > 89.99: rotRelAng -= 180 elif rotRelAng < -89.99: rotRelAng += 180 rotateAx1 = gp_Ax1(centerOfMass(shp_add), rotateAxDir) ax3 = gp_Ax3(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) ax3 = ax3.Rotated(rotateAx1, radians(rotRelAng)) shp2Trsf = gp_Trsf() shp2Trsf.SetTransformation(ax3) shp2Toploc = TopLoc_Location(shp2Trsf) shp_add.Move(shp2Toploc) else: logging.debug("Planes are already parallel to each other")
def rotate(brep, axe, degree, copy=False): """Rotates the brep Originally from pythonocc-utils : might add dependency on this? Parameters ---------- brep : shape to rotate axe : axis of rotation degree : Number of degrees to rotate through copy : bool (default=False) Returns ------- BRepBuilderAPI_Transform.Shape : Shape handle The handle to the rotated shape """ trns = gp_Trsf() trns.SetRotation(axe, np.radians(degree)) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) brep_trns.Build() return brep_trns.Shape()
def add_labels(product,lr,st): if product.links: for link in product.links: if link.product.doc_id != product.doc_id: if not link.product.label_reference: lr_2 = TDF_LabelSequence() si = StepImporter(link.product.doc_path) shape_tool = si.shape_tool shape_tool.GetFreeShapes(lr_2) add_labels(link.product, lr_2.Value(1), shape_tool) link.product.label_reference = lr_2.Value(1) # FIXME: free memory del si gc.collect() for d in range(link.quantity): transformation = gp_Trsf() loc = link.locations[d] transformation.SetValues(loc.x1, loc.x2, loc.x3, loc.x4, loc.y1, loc.y2, loc.y3, loc.y4, loc.z1, loc.z2, loc.z3, loc.z4, 1, 1) new_label = st.AddComponent(lr, link.product.label_reference, TopLoc_Location(transformation)) set_label_name(new_label, link.names[d])
def clone_tooth(base_shape): clone = gp_Trsf() grouped_shape = base_shape # Find a divisor, between 1 and 8, for the number_of teeth multiplier = 1 max_multiplier = 1 for i in range(0, 8): if num_teeth % multiplier == 0: max_multiplier = i + 1 multiplier = max_multiplier for i in range(1, multiplier): clone.SetRotation(gp_OZ(), -i * tooth_angle) rotated_shape = BRepBuilderAPI_Transform(base_shape, clone, True).Shape() grouped_shape = BRepAlgoAPI_Fuse(grouped_shape, rotated_shape).Shape() # Rotate the basic tooth and fuse together aggregated_shape = grouped_shape for i in range(1, int(num_teeth / multiplier)): clone.SetRotation(gp_OZ(), - i * multiplier * tooth_angle) rotated_shape = BRepBuilderAPI_Transform(grouped_shape, clone, True).Shape() aggregated_shape = BRepAlgoAPI_Fuse(aggregated_shape, rotated_shape).Shape() cylinder = BRepPrimAPI_MakeCylinder(gp_XOY(), top_radius - roller_diameter, thickness) aggregated_shape = BRepAlgoAPI_Fuse(aggregated_shape, cylinder.Shape()).Shape() return aggregated_shape
def scale(occtopology, scale_factor, ref_pypt): """ This function uniformly scales an OCCtopology based on the reference point and the scale factor. Parameters ---------- occtopology : OCCtopology The OCCtopology to be scaled. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex scale_factor : float The scale factor. ref_pypt : tuple of floats The OCCtopology will scale in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) Returns ------- scaled topology : OCCtopology (OCCshape) The scaled OCCtopology. """ xform = gp_Trsf() gp_pnt = construct.make_gppnt(ref_pypt) xform.SetScale(gp_pnt, scale_factor) brep = BRepBuilderAPI_Transform(xform) brep.Perform(occtopology, True) trsfshape = brep.Shape() return trsfshape
def copyToZ(self, z, layerNo): "makes a copy of this slice, transformed to the specified z height" theCopy = Slice() theCopy.zLevel = z theCopy.fillAngle = self.fillAngle theCopy.layerNo = layerNo theCopy.thickness = self.thickness # make transformation p1 = gp.gp_Pnt(0, 0, 0) p2 = gp.gp_Pnt(0, 0, z) xform = gp.gp_Trsf() xform.SetTranslation(p1, p2) bt = BRepBuilderAPI.BRepBuilderAPI_Transform(xform) # copy all of the faces for f in self.faces: bt.Perform(f.face, True) newFace = Face(OCCUtil.cast(bt.Shape())) # copy shells for shell in f.shellWires: # print shell bt.Perform(shell, True) newFace.shellWires.append(OCCUtil.cast(bt.Shape())) # copy fillWires for fill in f.fillWires: bt.Perform(fill, True) newFace.shellWires.append(OCCUtil.cast(bt.Shape())) theCopy.addFace(newFace) return theCopy
def InitDoc(self): h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool().ShapeTool(doc.Main()) l_Colors = XCAFDoc.XCAFDoc_DocumentTool().ColorTool(doc.Main()) shape_tool = h_shape_tool.GetObject() colors = l_Colors.GetObject() self.shape_tool = shape_tool top_label = shape_tool.NewShape( ) # this is the "root" label for the assembly self.top_label = top_label # Add some shapes box = BRepPrimAPI.BRepPrimAPI_MakeBox(10, 20, 30).Shape() box_label = shape_tool.AddShape(box, False) cyl = BRepPrimAPI.BRepPrimAPI_MakeCylinder(25, 50).Shape() cyl_label = shape_tool.AddShape(cyl, False) # Add components as references to our shape tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(100, 100, 100)) loc = TopLoc.TopLoc_Location(tr) box_comp1 = shape_tool.AddComponent(top_label, box_label, loc) tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(200, 200, 200)) loc = TopLoc.TopLoc_Location(tr) box_comp2 = shape_tool.AddComponent(top_label, box_label, loc) tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(150, 200, 100)) loc = TopLoc.TopLoc_Location(tr) cyl_comp = shape_tool.AddComponent(top_label, cyl_label, loc) # Add some colors red = Quantity.Quantity_Color(Quantity.Quantity_NOC_RED) green = Quantity.Quantity_Color(Quantity.Quantity_NOC_GREEN) colors.SetColor(cyl_comp, red, XCAFDoc.XCAFDoc_ColorGen) colors.SetColor(box_comp2, green, XCAFDoc.XCAFDoc_ColorGen) self.box_label = box_label self.cyl_label = cyl_label self.box_comp1 = box_comp1 self.box_comp2 = box_comp2 self.cyl_comp = cyl_comp
def init_display(backend_str=None, size=(1000, 600)): QtCore, QtGui, QtWidgets, QtOpenGL = get_qt_modules() class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args): QtWidgets.QMainWindow.__init__(self, *args) self.resize(size[0], size[1]) self.Viewer = qtViewer2(self) self.setCentralWidget(self.Viewer) self.centerOnScreen() def centerOnScreen(self): '''Centers the window on the screen.''' resolution = QtWidgets.QDesktopWidget().screenGeometry() self.move((resolution.width() / 2) - (self.frameSize().width() / 2), (resolution.height() / 2) - (self.frameSize().height() / 2)) # following couple of lines is a twek to enable ipython --gui='qt' app = QtWidgets.QApplication.instance() # checks if QApplication already exists if not app: # create QApplication if it doesnt exist app = QtWidgets.QApplication(sys.argv) win = MainWindow() win.show() win.Viewer.InitDriver() display = win.Viewer._display # background gradient display.set_bg_gradient_color(206, 215, 222, 128, 128, 128) # display black trihedron display.display_trihedron() def start_display(): win.raise_() # make the application float to the top app.exec_() win.display = display win.show() win.Viewer.init2() # create and add shapes box = BRepPrimAPI.BRepPrimAPI_MakeBox(60, 30, 10).Shape() cyl = BRepPrimAPI.BRepPrimAPI_MakeCylinder(25, 40).Shape() tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(0, 50, 0)) loc = TopLoc.TopLoc_Location(tr) moved_box = box.Moved(loc) # these shapes can be deleted by selecting them and pressing 'Del': win.Viewer.doc_ctrl.add(box) win.Viewer.doc_ctrl.add(cyl) # this shape cannot be deleted in this implementation: win.Viewer.doc_ctrl.add(moved_box) win.Viewer.repaint(Update=False) display.FitAll() return display, start_display
def translate(self, target): transform = gp.gp_Trsf() transform.SetTranslation(gp.gp_Vec(*target)) for i, needle in enumerate(self.shapes): needle_transform = BRepTransform(needle, transform, False) needle_transform.Build() self.shapes[i] = needle_transform.Shape()
def wavefront_xyz(x, y, z, axs=gp_Ax3()): phas = surf_spl(x, y, z) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) loc_face = TopLoc_Location(trf) phas.Location(loc_face) return phas
def rotate(shape, axis, angle): tr = gp_Trsf() point = axis[0] vec = axis[1] axis = gp.gp_Ax1(gp.gp_Pnt(*point), gp.gp_Dir(*vec)) tr.SetRotation(axis, angle) loc = TopLoc_Location(tr) return shape.Moved(loc)
def InitDoc(self): h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool().ShapeTool(doc.Main()) l_Colors = XCAFDoc.XCAFDoc_DocumentTool().ColorTool(doc.Main()) shape_tool = h_shape_tool.GetObject() colors = l_Colors.GetObject() self.shape_tool = shape_tool top_label = shape_tool.NewShape() #this is the "root" label for the assembly self.top_label = top_label #Add some shapes box = BRepPrimAPI.BRepPrimAPI_MakeBox(10,20,30).Shape() box_label = shape_tool.AddShape(box, False) cyl = BRepPrimAPI.BRepPrimAPI_MakeCylinder(25,50).Shape() cyl_label = shape_tool.AddShape(cyl, False) #Add components as references to our shape tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(100,100,100)) loc = TopLoc.TopLoc_Location(tr) box_comp1 = shape_tool.AddComponent(top_label, box_label, loc) tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(200,200,200)) loc = TopLoc.TopLoc_Location(tr) box_comp2 = shape_tool.AddComponent(top_label, box_label, loc) tr = gp.gp_Trsf() tr.SetTranslation(gp.gp_Vec(150,200,100)) loc = TopLoc.TopLoc_Location(tr) cyl_comp = shape_tool.AddComponent(top_label, cyl_label, loc) #Add some colors red = Quantity.Quantity_Color(Quantity.Quantity_NOC_RED) green = Quantity.Quantity_Color(Quantity.Quantity_NOC_GREEN) colors.SetColor(cyl_comp, red, XCAFDoc.XCAFDoc_ColorGen) colors.SetColor(box_comp2, green, XCAFDoc.XCAFDoc_ColorGen) self.box_label = box_label self.cyl_label = cyl_label self.box_comp1 = box_comp1 self.box_comp2 = box_comp2 self.cyl_comp = cyl_comp
def translate(self, target): transform = gp.gp_Trsf() transform.SetTranslation(gp.gp_Vec(*target)) # FIXME: this needs some explanation... should it be here? needle_transform = BRepTransform(self.needle, transform, False) needle_transform.Build() self.needle = needle_transform.Shape()
def rotate(self, angle, axis): ax = gp_Ax1(gp_Pnt(*axis[:3]), gp_Dir(*axis[3:])) tr = gp_Trsf() tr.SetRotation(ax, angle) loc = TopLoc_Location(tr) self.shape = BRepBuilderAPI_Transform(self.shape, tr).Shape() self.__extract_curves() return self
def _cut_finger_notch(front, dx, dz): finger_width = 2.0 finger_height = 1.0 front = _cut( front, _box(_pnt(dx / 2. - finger_width / 2., 0, dz - finger_height), finger_width, THICKNESS_0, finger_height)) cyl = BRepPrimAPI_MakeCylinder(finger_width / 2.0, THICKNESS_0).Shape() tr = gp.gp_Trsf() tr.SetRotation(gp.gp_Ax1(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(1, 0, 0)), math.pi / 2.0) tr2 = gp.gp_Trsf() tr2.SetTranslation(gp.gp_Vec(dx / 2., THICKNESS_0, dz - finger_height)) tr2.Multiply(tr) cyl = BRepBuilderAPI_Transform(cyl, tr2, True).Shape() front = _cut(front, cyl) return front
def rotating_cube_2_axis(event=None): display.EraseAll() ais_boxshp = build_shape() ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) ax2 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.)) a_cube_trsf = gp_Trsf() a_cube_trsf2 = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): a_cube_trsf.SetRotation(ax1, angle) a_cube_trsf2.SetRotation(ax2, angle) aCubeToploc = TopLoc_Location(a_cube_trsf * a_cube_trsf2) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2*pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def translate(self, vector): if type(vector) == tuple: vector = Vector(vector) T = gp_Trsf() T.SetTranslation(vector.wrapped) return self._apply_transform(T)
def rotating_cube_2_axis(event=None): display.EraseAll() ais_boxshp = build_shape() ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) ax2 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.)) a_cube_trsf = gp_Trsf() a_cube_trsf2 = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): a_cube_trsf.SetRotation(ax1, angle) a_cube_trsf2.SetRotation(ax2, angle) aCubeToploc = TopLoc_Location(a_cube_trsf * a_cube_trsf2) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2 * pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def get_transform(self): d = self.declaration result = gp_Trsf() #: TODO: Order matters... how to configure it??? for op in d.operations: t = gp_Trsf() if isinstance(op, Translate): t.SetTranslation(gp_Vec(op.x, op.y, op.z)) elif isinstance(op, Rotate): t.SetRotation(gp_Ax1(gp_Pnt(*op.point), gp_Dir(*op.direction)), op.angle) elif isinstance(op, Mirror): t.SetMirror(gp_Ax1(gp_Pnt(*op.point), gp_Dir(op.x, op.y, op.z))) elif isinstance(op, Scale): t.SetScale(gp_Pnt(*op.point), op.s) result.Multiply(t) return result
def build(self): # Get the subclass-specific reference shape shape = self.make_reference(**self.parameters) # Transform it as required by our initializing parameters transform = gp.gp_Trsf() transform.SetScale(self.origin, self.radius) shape_transform = BRepTransform(shape, transform, False) shape_transform.Build() shape = shape_transform.Shape() transform = gp.gp_Trsf() transform.SetTranslation(gp.gp_Vec(*self.centre)) shape_transform = BRepTransform(shape, transform, False) shape_transform.Build() self.shape = shape_transform.Shape()
def _add_random_cylinder_fired(self, old, new): brep = BRepPrimAPI_MakeCylinder(random.random() * 50, random.random() * 50).Shape() trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(random.random() * 100, random.random() * 100, random.random() * 100)) brep.Move(TopLoc_Location(trsf)) self.shapes.append(brep)
def move(orig_pt, location_pt, occshape): gp_ax31 = gp_Ax3(gp_Pnt(orig_pt[0], orig_pt[1], orig_pt[2]), gp_DZ()) gp_ax32 = gp_Ax3(gp_Pnt(location_pt[0], location_pt[1], location_pt[2]), gp_DZ()) aTrsf = gp_Trsf() aTrsf.SetTransformation(gp_ax32, gp_ax31) trsf_brep = BRepBuilderAPI_Transform(aTrsf) trsf_brep.Perform(occshape, True) trsf_shp = trsf_brep.Shape() return trsf_shp
def mirror_pnt_dir(brep, pnt, direction, copy=False): ''' @param brep: @param line: ''' trns = gp_Trsf() trns.SetMirror(gp_Ax1(pnt, direction)) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) with assert_isdone(brep_trns, 'could not produce mirror'): brep_trns.Build() return brep_trns.Shape()
def mv2CMass(shp, pnt): # ipdb.set_trace() # ais_shp2 = frame.display.DisplayShape(shp2, update=True) # the point want to be origin express in local # the local Z axis expressed in local system expressed in global coordinates shp2Trsf = gp_Trsf() vec = gp_Vec(pnt, gp_Pnt(0, 0, 0)) shp2Trsf.SetTranslation(vec) shp2Toploc = TopLoc_Location(shp2Trsf) shp.Move(shp2Toploc) return shp
def glue_solids_edges(event=None): display.EraseAll() display.Context.RemoveAll() # With common edges S3 = BRepPrimAPI_MakeBox(500., 400., 300.).Shape() S4 = BRepPrimAPI_MakeBox(gp_Pnt(0., 0., 300.), gp_Pnt(200., 200., 500.)).Shape() faces_S3 = get_faces(S3) faces_S4 = get_faces(S4) # tagging allows to visually find the right faces to glue tag_faces(faces_S3, "BLUE", "s3") tag_faces(faces_S4, "GREEN", "s4") F3, F4 = faces_S3[5], faces_S4[4] glue2 = BRepFeat_Gluer(S4, S3) glue2.Bind(F4, F3) glue2.Build() shape = glue2.Shape() # move the glued shape, such to be able to inspect input and output # of glueing operation trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(750, 0, 0)) shape.Move(TopLoc_Location(trsf)) common_edges = LocOpe_FindEdges(F4, F3) common_edges.InitIterator() n = 0 while common_edges.More(): edge_from = common_edges.EdgeFrom() edge_to = common_edges.EdgeTo() center_pt_edge_to = center_boundingbox(edge_to) center_pt_edge_from = center_boundingbox(edge_from) red = (1, 0, 0) display.DisplayMessage(center_pt_edge_from, "edge_{0}_from".format(n), message_color=red) display.DisplayMessage(center_pt_edge_to, "edge_{0}_to".format(n), message_color=red) glue2.Bind(edge_from, edge_to) common_edges.Next() n += 1 tag_faces(get_faces(shape), "BLACK", "") display.FitAll()
def scale(self, scaling): if scaling is None: scaling = 1.0 transform = gp.gp_Trsf() transform.SetScale(self.origin, REFERENCE_SCALING / scaling) for i, needle in enumerate(self.shapes): needle_transform = BRepTransform(needle, transform, False) needle_transform.Build() self.shapes[i] = needle_transform.Shape()
def mirror_axe2(brep, axe2, copy=False): ''' @param brep: @param line: ''' trns = gp_Trsf() trns.SetMirror(axe2) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) with assert_isdone(brep_trns, 'could not produce mirror'): brep_trns.Build() return brep_trns.Shape()
def make_cylinder_2(start, end, radius): start = numpy.asarray(start) end = numpy.asarray(end) direction = end-start length = numpy.sqrt((direction**2).sum()) cyl = BRepPrimAPI.BRepPrimAPI_MakeCylinder(radius, length) ax = gp.gp_Ax3(gp.gp_Pnt(*start), gp.gp_Dir(*direction)) trans = gp.gp_Trsf() trans.SetTransformation(ax, gp.gp_Ax3()) t_cyl = BRepBuilderAPI.BRepBuilderAPI_Transform(cyl.Shape(), trans) return toshape(t_cyl)
def make_box(position, direction, x_axis, dx, dy, dz): box = BRepPrimAPI.BRepPrimAPI_MakeBox(gp.gp_Pnt(-dx/2., -dy/2., 0.0), dx, dy, -dz) ax = gp.gp_Ax2(gp.gp_Pnt(*position), gp.gp_Dir(*direction), gp.gp_Dir(*x_axis)) ax3 = gp.gp_Ax3() trans = gp.gp_Trsf() trans.SetTransformation(gp.gp_Ax3(ax), ax3) t_box = BRepBuilderAPI.BRepBuilderAPI_Transform(box.Shape(), trans) return toshape(t_box)
def rotate_shp_3_axis(shape, rx, ry, rz, unity="deg"): """ Rotate a shape around (O,x), (O,y) and (O,z). @param rx_degree : rotation around (O,x) @param ry_degree : rotation around (O,y) @param rz_degree : rotation around (O,z) @return : the rotated shape. """ if unity == "deg": # convert angle to radians rx = radians(rx) ry = radians(ry) rz = radians(rz) alpha = gp_Trsf() alpha.SetRotation(gp_OX(), rx) beta = gp_Trsf() beta.SetRotation(gp_OY(), ry) gamma = gp_Trsf() gamma.SetRotation(gp_OZ(), rz) brep_trns = BRepBuilderAPI_Transform(shape, alpha*beta*gamma, False) shp = brep_trns.Shape() return shp
def mirror_axe2(brep, axe2, copy=False): """ @param brep: @param line: """ trns = gp_Trsf() trns.SetMirror(axe2) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) with assert_isdone(brep_trns, 'could not produce mirror'): brep_trns.Build() return brep_trns.Shape()
def translate_topods_from_vector(brep_or_iterable, vec, copy=False): ''' translate a brep over a vector @param brep: the Topo_DS to translate @param vec: the vector defining the translation @param copy: copies to brep if True ''' trns = gp_Trsf() trns.SetTranslation(vec) brep_trns = BRepBuilderAPI_Transform(brep_or_iterable, trns, copy) brep_trns.Build() return brep_trns.Shape()
def rotate(brep, axe, degree, copy=False): """ @param brep: @param axe: @param degree: """ trns = gp_Trsf() trns.SetRotation(axe, radians(degree)) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) with assert_isdone(brep_trns, 'could not produce rotation'): brep_trns.Build() return ST(brep_trns.Shape())
def preview(self, input, direction): if self.step == 0: # object to rotate self.prev_dat['object'] = input return [] elif self.step == 1: # axis to rotate about dirvec = vec(0, 0, 0) dirvec[direction] = 1 axis = gp.gp_Ax1(input, dirvec.to_gp_Dir()) # make a copy (copy.copy does not work) point = gp_.gp_Pnt_(input) point[direction] += 2 input[direction] -= .2 axis_plot = BRepBuilderAPI.BRepBuilderAPI_MakeEdge( GC.GC_MakeSegment(input, point).Value()).Edge() self.prev_dat['point'] = input self.prev_dat['dirvec'] = dirvec self.prev_dat['axis'] = axis self.prev_dat['axis-plot'] = axis_plot return [axis_plot] elif self.step == 2: # start point self.prev_dat['point_start'] = input return [self.prev_dat['axis-plot']] elif self.step == 3: p0 = self.prev_dat['point'] vec0 = self.prev_dat['point_start'] - p0 vec1 = input - p0 dirvec = self.prev_dat['dirvec'] n0 = dirvec.cross(vec0) n1 = dirvec.cross(vec1) try: cos = n0.dot(n1) / (n0.length() * n1.length()) except ZeroDivisionError: raise InvalidInputException angle = math.acos(min(max(cos, -1), 1)) # cos might be (-)1.000001 oriented_dirvec = n0.cross(n1) if oriented_dirvec == vec(0, 0, 0): raise InvalidInputException axis = gp.gp_Ax1(p0, oriented_dirvec.to_gp_Dir()) tr = gp.gp_Trsf() tr.SetRotation(axis, angle) t = self.prev_dat['object'].Moved(TopLoc.TopLoc_Location(tr)) t = copy_geom.copy(t) self._final = [t] self.remove = [self.prev_dat['object']] return [t, self.prev_dat['axis-plot']]
def main2(filename): display.EraseAll() display.Context.RemoveAll() # With common edges S3 = BRepPrimAPI_MakeBox(gp_Pnt(0., 0., 0.), gp_Pnt(100., 100., 50.)).Shape() S4 = BRepPrimAPI_MakeBox(gp_Pnt(0., 0., 50.), gp_Pnt(100., 100., 100.)).Shape() faces_S3 = get_faces(S3) faces_S4 = get_faces(S4) # tagging allows to visually find the right faces to glue tag_faces(faces_S3, "BLUE", "s3") tag_faces(faces_S4, "GREEN", "s4") F3, F4 = faces_S3[5], faces_S4[4] glue2 = BRepFeat_Gluer(S4, S3) glue2.Bind(F4, F3) glue2.Build() shape = glue2.Shape() # move the glued shape, such to be able to inspect input and output # of glueing operation trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(750, 0, 0)) shape.Move(TopLoc_Location(trsf)) common_edges = LocOpe_FindEdges(F4, F3) common_edges.InitIterator() n = 0 while common_edges.More(): edge_from = common_edges.EdgeFrom() edge_to = common_edges.EdgeTo() tag_edge(edge_from, "edge_{0}_from".format(n)) tag_edge(edge_to, "edge_{0}_to".format(n)) glue2.Bind(edge_from, edge_to) common_edges.Next() n += 1 tag_faces(get_faces(shape), "BLACK", "") if filename is not None: breptools_Write(shape, filename) # render glued shape display.DisplayShape(shape) display.FitAll() start_display()
def rotate(brep, axe, degree, copy=False): ''' @param brep: @param axe: @param degree: ''' from math import radians trns = gp_Trsf() trns.SetRotation(axe, radians(degree)) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) with assert_isdone(brep_trns, 'could not produce rotation'): brep_trns.Build() return ST(brep_trns.Shape())
def scale_uniformal(brep, pnt, factor, copy=False): ''' translate a brep over a vector @param brep: the Topo_DS to translate @param pnt: a gp_Pnt @param triple: scaling factor @param copy: copies to brep if True ''' trns = gp_Trsf() trns.SetScale(pnt, factor) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) brep_trns.Build() return brep_trns.Shape()
def makeHexArray(self,bottomLeftCenter, countX, countY ): """ makes an array of hexagons bottomLeftCenter is the center of the top left hex, as a three-element tuple countX is the number of hexes in the x direction countY is the number of hexes in the y direction returns a list of wires representing a hexagon fill pattern """ pattern = self.makePeriodic(bottomLeftCenter); wireBuilder = BRepBuilderAPI.BRepBuilderAPI_MakeWire(pattern); #make horizontal array tsf = gp.gp_Trsf(); pDist = 2.0 * self.cartesianSpacing()[0]; tsf.SetTranslation(gp.gp_Pnt(0,0,0),gp.gp_Pnt(pDist ,0,0)); tx = BRepBuilderAPI.BRepBuilderAPI_Transform(tsf); currentShape = pattern; for i in range(1,int((countX/2)+1)): tx.Perform(currentShape,False); currentShape = tx.Shape(); #display.DisplayShape(currentShape); wireBuilder.Add(Wrappers.cast(currentShape)); #create an array by alternately offsetting one cell right and #moving down topHalf = wireBuilder.Wire(); #topHalf= approximatedWire(topHalf); wires=[]; wires.append(topHalf); dY = self.cartesianSpacing()[1]/2.0; dX = self.cartesianSpacing()[0]; ####TODO// performance note. This method takes about 31ms to compute 1000x1000 hex. # pretty good, except that nearly 50% of the time is spent in makeTransform!!! # a much better method would be to use the same transform object somehow for i in range(1,int(countY*2)): if i % 2 == 0: t = makeTransform(0,dY*i,0); else: t = makeTransform(dX,dY*i,0); t.Perform(topHalf,False); w = Wrappers.cast(t.Shape()); #approximate the wire #wires.append ( approximatedWire(w)); wires.append( w); #display.DisplayShape(wires); return wires;
def make_reference(self, **parameters): l = parameters['length'] w = parameters['width'] h = parameters['height'] box_shape = BRepPrimAPI_MakeBox(l, w, h) transform = gp.gp_Trsf() transform.SetTranslation(gp.gp_Vec(-l / 2, -w / 2, -h / 2)) shape_transform = BRepTransform(box_shape.Shape(), transform, False) shape_transform.Build() shape = shape_transform.Shape() return shape