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 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 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 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 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 add_feature(base): """Add a "feature" to a shape. In this case we drill a hole through it.""" feature_diameter = 0.8 feature_origin = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) feature_maker = BRepFeat_MakeCylindricalHole() feature_maker.Init(base, feature_origin) feature_maker.Build() feature_maker.Perform(feature_diameter / 2.0) shape = feature_maker.Shape() return shape
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 update_shape(self,change): d = self.declaration c = d.shape if d.shape else self.get_shape() #: Build arguments args = [c.shape.Shape(), gp_Ax1(d.position,d.direction)] if d.angle: args.append(d.angle) args.append(d.copy) self.shape = BRepPrimAPI_MakeRevol(*args)
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 edge(event=None): # The blud edge BlueEdge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20), gp_Pnt(-30, -60, -60)) V1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30)) V2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25)) YellowEdge = BRepBuilderAPI_MakeEdge(V1.Vertex(), V2.Vertex()) #The white edge line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0))) WhiteEdge = BRepBuilderAPI_MakeEdge(line, -20, 10) #The red edge Elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30) RedEdge = BRepBuilderAPI_MakeEdge(Elips, 0, math.pi/2) # The green edge and the both extreme vertex P1 = gp_Pnt(-15, 200, 10) P2 = gp_Pnt(5, 204, 0) P3 = gp_Pnt(15, 200, 0) P4 = gp_Pnt(-15, 20, 15) P5 = gp_Pnt(-5, 20, 0) P6 = gp_Pnt(15, 20, 0) P7 = gp_Pnt(24, 120, 0) P8 = gp_Pnt(-24, 120, 12.5) array = TColgp_Array1OfPnt(1, 8) array.SetValue(1, P1) array.SetValue(2, P2) array.SetValue(3, P3) array.SetValue(4, P4) array.SetValue(5, P5) array.SetValue(6, P6) array.SetValue(7, P7) array.SetValue(8, P8) curve = Geom_BezierCurve(array) ME = BRepBuilderAPI_MakeEdge(curve.GetHandle()) GreenEdge = ME V3 = ME.Vertex1() V4 = ME.Vertex2() display.DisplayColoredShape(BlueEdge.Edge(), 'BLUE') display.DisplayShape(V1.Vertex()) display.DisplayShape(V2.Vertex()) display.DisplayColoredShape(WhiteEdge.Edge(), 'WHITE') display.DisplayColoredShape(YellowEdge.Edge(), 'YELLOW') display.DisplayColoredShape(RedEdge.Edge(), 'RED') display.DisplayColoredShape(GreenEdge.Edge(), 'GREEN') display.DisplayShape(V3) display.DisplayShape(V4, update=True)
def reorient(self, z_target_axis): # Note that needles are expected to lie along the z-axis with tip at the # origin. z_axis = [0, 0, 1] rot_axis = N.cross(z_axis, z_target_axis) if N.linalg.norm(rot_axis) > 1e-6: rotation_axis = gp.gp_Ax1(self.origin, gp.gp_Dir(*rot_axis)) rotation_angle = N.arccos(N.dot(z_axis, z_target_axis) / (N.linalg.norm(z_axis) * N.linalg.norm(z_target_axis))) transform = gp.gp_Trsf() transform.SetRotation(rotation_axis, rotation_angle) for i, needle in enumerate(self.shapes): needle_transform = BRepTransform(needle, transform, False) needle_transform.Build() self.shapes[i] = needle_transform.Shape()
def rotate(self, startVector, endVector, angleDegrees): """ Rotates a shape around an axis :param startVector: start point of rotation axis either a 3-tuple or a Vector :param endVector: end point of rotation axis, either a 3-tuple or a Vector :param angleDegrees: angle to rotate, in degrees :return: a copy of the shape, rotated """ if type(startVector) == tuple: startVector = Vector(startVector) if type(endVector) == tuple: endVector = Vector(endVector) T = gp_Trsf() T.SetRotation( gp_Ax1(startVector.toPnt(), (endVector - startVector).toDir()), angleDegrees) return self._apply_transform(T)
def revolved_cut(base): # Define 7 points face_points = TColgp_Array1OfPnt(1, 7) face_inner_radius = 0.6 pts = [ gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius - 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius + 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), ] for n, i in enumerate(pts): face_points.SetValue(n + 1, i) # Use these points to create edges and add these edges to a wire hexwire = BRepBuilderAPI_MakeWire() for i in range(1, 7): hexedge = BRepBuilderAPI_MakeEdge(face_points.Value(i), face_points.Value(i + 1)).Edge() hexwire.Add(hexedge) # Turn the wire into a 6 sided face hexface = BRepBuilderAPI_MakeFace(hexwire.Wire()).Face() # Revolve the face around an axis revolve_axis = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) revolved_shape = BRepPrimAPI_MakeRevol(hexface, revolve_axis).Shape() # Move the generated shape move = gp_Trsf() move.SetTranslation(gp_Pnt(0, 0, 0), gp_Pnt(0, 0, sin(0.5))) moved_shape = BRepBuilderAPI_Transform(revolved_shape, move, False).Shape() # Remove the revolved shape cut = BRepAlgoAPI_Cut(base, moved_shape).Shape() return cut
def make_spherical_lens2(CT1, CT2, diameter, curvature1, curvature2, centre, direction, x_axis): cax = gp.gp_Ax2(gp.gp_Pnt(0,0,CT1-curvature1), gp.gp_Dir(0,sign(curvature1),0), gp.gp_Dir(1,0,0)) circ = Geom.Geom_Circle(cax, abs(curvature1)) h_circ = Geom.Handle_Geom_Circle(circ) cax2 = gp.gp_Ax2(gp.gp_Pnt(0,0,CT2-curvature2), gp.gp_Dir(0,-sign(curvature2),0), gp.gp_Dir(1,0,0)) circ2 = Geom.Geom_Circle(cax2, abs(curvature2)) h_circ2 = Geom.Handle_Geom_Circle(circ2) r = diameter/2. h2 = CT1 - curvature1 + numpy.sqrt(curvature1**2 - r**2)*sign(curvature1) h3 = CT2 - curvature2 + numpy.sqrt(curvature2**2 - r**2)*sign(curvature2) p1 = gp.gp_Pnt(0,0,CT1) p2 = gp.gp_Pnt(r,0,h2) p3 = gp.gp_Pnt(r,0,h3) p4 = gp.gp_Pnt(0,0,CT2) e1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(h_circ, p1, p2) e2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(p2,p3) e3 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(h_circ2, p3,p4) e4 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(p4,p1) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() for e in (e1,e2,e3,e4): print(e) wire.Add(e.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) ax = gp.gp_Ax1(gp.gp_Pnt(0,0,0), gp.gp_Dir(0,0,1)) solid = BRepPrimAPI.BRepPrimAPI_MakeRevol(face.Shape(), ax) return position_shape(toshape(solid), centre, direction, x_axis)
def revolved_shape(): """ demonstrate how to create a revolved shape from an edge adapted from algotopia.com's opencascade_basic tutorial: http://www.algotopia.com/contents/opencascade/opencascade_basic """ face_inner_radius = 0.6 # point to create an edge from edg_points = [ gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius - 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius + 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), ] # aggregate edges in wire hexwire = BRepBuilderAPI_MakeWire() for i in range(6): hexedge = BRepBuilderAPI_MakeEdge(edg_points[i], edg_points[i + 1]).Edge() hexwire.Add(hexedge) hexwire_wire = hexwire.Wire() # face from wire hexface = BRepBuilderAPI_MakeFace(hexwire_wire).Face() revolve_axis = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) # create revolved shape revolved_shape_ = BRepPrimAPI_MakeRevol(hexface, revolve_axis, math.radians(90.)).Shape() # render wire & revolved shape display.DisplayShape([revolved_shape_, hexwire_wire]) display.FitAll() start_display()
def calc_intersection(terrain_intersection_curves, edges_coords, edges_dir): """ This script calculates the intersection of the building edges to the terrain, :param terrain_intersection_curves: :param edges_coords: :param edges_dir: :return: intersecting points, intersecting faces """ building_line = gp_Lin( gp_Ax1(gp_Pnt(edges_coords[0], edges_coords[1], edges_coords[2]), gp_Dir(edges_dir[0], edges_dir[1], edges_dir[2]))) terrain_intersection_curves.PerformNearest(building_line, 0.0, float("+inf")) if terrain_intersection_curves.IsDone(): npts = terrain_intersection_curves.NbPnt() if npts != 0: return terrain_intersection_curves.Pnt( 1), terrain_intersection_curves.Face(1) else: return None, None else: return None, None
def intersect_shape_with_ptdir(occtopology, pypt, pydir): """ This function projects a point in a direction and calculates the at which point does the point intersects the OCCtopology. Parameters ---------- occtopology : OCCtopology The OCCtopology to be projected on. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex pypt : tuple of floats The point to be projected. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) pydir : tuple of floats The direction of the point to be projected. A pydir is a tuple that documents the xyz vector of a dir e.g. (x,y,z) Returns ------- intersection point : pypt The point in which the projected point intersect the OCCtopology. If None means there is no intersection. intersection face : OCCface The OCCface in which the projected point hits. If None means there is no intersection. """ occ_line = gp_Lin( gp_Ax1(gp_Pnt(pypt[0], pypt[1], pypt[2]), gp_Dir(pydir[0], pydir[1], pydir[2]))) shape_inter = IntCurvesFace_ShapeIntersector() shape_inter.Load(occtopology, 1e-6) shape_inter.PerformNearest(occ_line, 0.0, float("+inf")) if shape_inter.IsDone(): npts = shape_inter.NbPnt() if npts != 0: return modify.occpt_2_pypt(shape_inter.Pnt(1)), shape_inter.Face(1) else: return None, None else: return None, None
def revolved_shape(): """ demonstrate how to create a revolved shape from an edge adapted from algotopia.com's opencascade_basic tutorial: http://www.algotopia.com/contents/opencascade/opencascade_basic """ face_inner_radius = 0.6 # point to create an edge from edg_points = [ gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius - 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, 0.025), gp_Pnt(face_inner_radius + 0.10, 0.0, -0.025), gp_Pnt(face_inner_radius + 0.05, 0.0, -0.05), gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05), ] # aggregate edges in wire hexwire = BRepBuilderAPI_MakeWire() for i in range(6): hexedge = BRepBuilderAPI_MakeEdge(edg_points[i], edg_points[i+1]).Edge() hexwire.Add(hexedge) hexwire_wire = hexwire.Wire() # face from wire hexface = BRepBuilderAPI_MakeFace(hexwire_wire).Face() revolve_axis = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) # create revolved shape revolved_shape_ = BRepPrimAPI_MakeRevol(hexface, revolve_axis, math.radians(90.)).Shape() # render wire & revolved shape display.DisplayShape([revolved_shape_, hexwire_wire]) display.FitAll() start_display()
def make_ellipsoid_2(focus1, focus2, major_axis): f1 = numpy.asarray(focus1) f2 = numpy.asarray(focus2) direction = -(f1 - f2) centre = (f1 + f2)/2. sep = numpy.sqrt((direction**2).sum()) minor_axis = numpy.sqrt( major_axis**2 - (sep/2.)**2 ) el = gp.gp_Elips(gp.gp_Ax2(gp.gp_Pnt(0,0,0), gp.gp_Dir(1,0,0)), major_axis, minor_axis) edge1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(el, gp.gp_Pnt(0,0,major_axis), gp.gp_Pnt(0,0,-major_axis)) edge2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(gp.gp_Pnt(0,0,-major_axis), gp.gp_Pnt(0,0,major_axis)) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() wire.Add(edge1.Edge()) wire.Add(edge2.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) el = BRepPrimAPI.BRepPrimAPI_MakeRevol(face.Shape(), gp.gp_Ax1(gp.gp_Pnt(0,0,0), gp.gp_Dir(0,0,1)), numpy.pi*2) loc = gp.gp_Ax3() loc.SetLocation(gp.gp_Pnt(*centre)) loc.SetDirection(gp.gp_Dir(*direction)) tr = gp.gp_Trsf() tr.SetTransformation(loc, gp.gp_Ax3()) trans = BRepBuilderAPI.BRepBuilderAPI_Transform(el.Shape(), tr) shape = toshape(trans) return shape
def intersect_shape_with_ptdir(occtopology, pypt, pydir): """ This function projects a point in a direction and calculates the at which point does the point intersects the OCCtopology. Parameters ---------- occtopology : OCCtopology The OCCtopology to be projected on. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex pypt : tuple of floats The point to be projected. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) pydir : tuple of floats The direction of the point to be projected. A pydir is a tuple that documents the xyz vector of a dir e.g. (x,y,z) Returns ------- intersection point : pypt The point in which the projected point intersect the OCCtopology. If None means there is no intersection. intersection face : OCCface The OCCface in which the projected point hits. If None means there is no intersection. """ occ_line = gp_Lin(gp_Ax1(gp_Pnt(pypt[0], pypt[1], pypt[2]), gp_Dir(pydir[0], pydir[1], pydir[2]))) shape_inter = IntCurvesFace_ShapeIntersector() shape_inter.Load(occtopology, 1e-6) shape_inter.PerformNearest(occ_line, 0.0, float("+inf")) if shape_inter.IsDone(): npts = shape_inter.NbPnt() if npts !=0: return modify.occpt_2_pypt(shape_inter.Pnt(1)), shape_inter.Face(1) else: return None, None else: return None, None
def make_spherical_lens(CT, diameter, curvature, centre, direction, x_axis): cax = gp.gp_Ax2(gp.gp_Pnt(0,0,CT-curvature), gp.gp_Dir(0,1,0), gp.gp_Dir(1,0,0)) circ = Geom.Geom_Circle(cax, curvature) h_circ = Geom.Handle_Geom_Circle(circ) r = diameter/2. h2 = CT - curvature + numpy.sqrt(curvature**2 - r**2) p1 = gp.gp_Pnt(0,0,CT) p2 = gp.gp_Pnt(r,0,h2) p3 = gp.gp_Pnt(r,0,0) p4 = gp.gp_Pnt(0,0,0) #ps = p1,p2,p3,p4 #vs = [BRepBuilderAPI.BRepBuilderAPI_MakeVertex(p) for p in ps] e1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(h_circ, p1, p2) e2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(p2,p3) e3 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(p3,p4) e4 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(p4,p1) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() for e in (e1,e2,e3,e4): print(e) wire.Add(e.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) ax = gp.gp_Ax1(gp.gp_Pnt(0,0,0), gp.gp_Dir(0,0,1)) solid = BRepPrimAPI.BRepPrimAPI_MakeRevol(face.Shape(), ax) return position_shape(toshape(solid), centre, direction, x_axis)
def mirror(self, **kwargs): """ params (one of): point def. mirror about point axis plane """ inValue=None if 'point' in kwargs: inValue = gp_Pnt(kwargs['point']) elif 'axis' in kwargs: inValue = gp_Ax1(gp_Pnt(*kwargs['axis'][:3]), gp_Dir(*kwargs['axis'][3:])) elif 'plane' in kwargs: inValue = gp_Ax2(gp_Pnt(*kwargs['axis'][:3]), gp_Dir(*kwargs['axis'][3:])) else: print "Warning: mirror could not be done becase there was no parameters specified" return self tr = gp_Trsf() tr.SetMirror(inValue) self.shape = BRepBuilderAPI_Transform(self.shape, tr).Shape() self.__extract_curves() return self
def transonic_airliner(display=None, Propulsion=1, EngineDia=2.9, FuselageScaling=[55.902, 55.902, 55.902], NoseLengthRatio=0.182, TailLengthRatio=0.293, WingScaleFactor=44.56, WingChordFactor=1.0, Topology=1, SpanStation1=0.35, SpanStation2=0.675, EngineCtrBelowLE=0.3558, EngineCtrFwdOfLE=0.9837, Scarf_deg=3): """ Parameters ---------- Propulsion - int 1 - twin 2 - quad EngineDia - float Diameter of engine intake highlight FuselageScaling - list, length 3 Fx, Fy, Fz scaling factors of fuselage NoseLengthRatio - scalar Proportion of forward tapering section of the fuselage TailLengthRatio - scalar Proportion of aft tapering section of the fuselage WingScaleFactor - scalar Scale Factor of the main wing WingChordFactor - scalar Chord factor of the main wing Topology - int Topology = 2 should yield a box wing airliner - use with caution SpanStation - float Inboard engine at this span station SpanStation2 - float Outboard engine at this span station (ignored if Propulsion=1) EngineCtrBelowLE - float Engine below leading edge, normalised by the length of the nacelle - range: [0.35,0.5] EngineCtrFwdOfLE - float Engine forward of leading edge, normalised by the length of the nacelle range: [0.85,1.5] Scarf_deg - scalar # Engine scarf angle Returns ------- airliner - 'Aircraft' class instance The collection of aircraft parts See also -------- class Aircraft """ try: Fus = fuselage_oml.Fuselage(NoseLengthRatio, TailLengthRatio, Scaling=FuselageScaling, NoseCoordinates=[0, 0, 0]) except: print "Fuselage fitting failed - stopping." return None FuselageHeight = FuselageScaling[2]*0.105 FuselageLength = FuselageScaling[0] FuselageWidth = FuselageScaling[1]*0.106 if Fus['OML'] is None: print "Failed to fit fuselage surface, stopping." return None # FSurf = rs.CopyObject(FuselageOMLSurf) # Position of the apex of the wing if FuselageHeight < 8.0: #787:[9.77,0,-0.307] WingApex = [0.1748*FuselageLength,0,-0.0523*FuselageHeight] else: WingApex = [0.1748*FuselageLength,0,-0.1*FuselageHeight] #787:[9.77,0,-0.307] # Set up the wing object, including the list of user-defined functions that # describe the spanwise variations of sweep, dihedral, etc. if Topology == 1: NSeg = 10 Wing = liftingsurface.LiftingSurface(WingApex, mySweepAngleFunctionAirliner, myDihedralFunctionAirliner, myTwistFunctionAirliner, myChordFunctionAirliner, myAirfoilFunctionAirliner, SegmentNo=NSeg, ScaleFactor=WingScaleFactor, ChordFactor=WingChordFactor) RootChord = Wing.RootChord elif Topology == 2: NSeg = 101 Wing = liftingsurface.LiftingSurface(WingApex, mySweepAngleFunctionAirliner, bw.myDihedralFunctionBoxWing, myTwistFunctionAirliner, myChordFunctionAirliner, myAirfoilFunctionAirliner, SegmentNo=NSeg, ScaleFactor=WingScaleFactor, ChordFactor=WingChordFactor) RootChord = Wing.RootChord if Topology == 1: # Add wing to body fairing WTBFXCentre = WingApex[0] + RootChord/2.0 + RootChord*0.1297 # 787: 23.8 if FuselageHeight < 8.0: #Note: I made changes to this in OCC Airconics to get a better fit # - Paul WTBFZ = RootChord*0.009 #787: 0.2 WTBFheight = 1.8*0.1212*RootChord #787:2.7 WTBFwidth = 1.08*FuselageWidth else: WTBFZ = WingApex[2] + 0.005*RootChord WTBFheight = 0.09*RootChord WTBFwidth = 1.15*FuselageWidth WTBFlength = 1.167*RootChord #787:26 WBF_shape = act.make_ellipsoid([WTBFXCentre, 0, WTBFZ], WTBFlength, WTBFwidth, WTBFheight) WBF = AirconicsShape(components={'WBF': WBF_shape}) # Trim wing inboard section CutCirc = act.make_circle3pt([0,WTBFwidth/4.,-45], [0,WTBFwidth/4.,45], [90,WTBFwidth/4.,0]) CutCircDisk = act.PlanarSurf(CutCirc) Wing['Surface'] = act.TrimShapebyPlane(Wing['Surface'], CutCircDisk) elif Topology == 2: # Overlapping wing tips CutCirc = act.make_circle3pt((0,0,-45), (0,0,45), (90,0,0)) CutCircDisk = act.PlanarSurf(CutCirc) Wing['Surface'] = act.TrimShapebyPlane(Wing['Surface'], CutCircDisk) # Engine installation (nacelle and pylon) NacelleLength = 1.95*EngineDia if Propulsion == 1: SpanStations = [SpanStation1] elif Propulsion == 2: SpanStations = [SpanStation1, SpanStation2] engines = [] for i, SpanStation in enumerate(SpanStations): EngineSection, Chord = act.CutSect(Wing['Surface'], SpanStation) CEP = Chord.EndPoint() Centreloc = [CEP.X()-EngineCtrFwdOfLE*NacelleLength, CEP.Y(), CEP.Z()-EngineCtrBelowLE*NacelleLength] eng = engine.Engine(Chord, CentreLocation=Centreloc, ScarfAngle=Scarf_deg, HighlightRadius=EngineDia/2.0, MeanNacelleLength = NacelleLength) engines.append(eng) # # Script for generating and positioning the fin # # Position of the apex of the fin P = [0.6524*FuselageLength,0.003,FuselageHeight*0.384] #P = [36.47,0.003,2.254]55.902 if Topology == 1: ScaleFactor = WingScaleFactor/2.032 #787:21.93 elif Topology == 2: ScaleFactor = WingScaleFactor/3.5 SegmentNo = 100 ChordFactor = 1.01#787:1.01 Fin = liftingsurface.LiftingSurface(P, mySweepAngleFunctionFin, myDihedralFunctionFin, myTwistFunctionFin, myChordFunctionFin, myAirfoilFunctionFin, SegmentNo=SegmentNo, ChordFactor=ChordFactor, ScaleFactor=ScaleFactor) # Create the rotation axis centered at the apex point in the x direction RotAxis = gp_Ax1(gp_Pnt(*P), gp_Dir(1, 0, 0)) Fin.RotateComponents(RotAxis, 90) if Topology == 1: # Tailplane P = [0.7692*FuselageLength,0.000,FuselageHeight*0.29] SegmentNo = 100 ChordFactor = 1.01 ScaleFactor = 0.388*WingScaleFactor #787:17.3 TP = liftingsurface.LiftingSurface(P, mySweepAngleFunctionTP, myDihedralFunctionTP, myTwistFunctionTP, myChordFunctionTP, myAirfoilFunctionTP, SegmentNo=SegmentNo, ChordFactor=ChordFactor, ScaleFactor=ScaleFactor) # OCC_AirCONICS Note: Nothing below here implemented in OCC_AirCONICS - See # Rhino version for this functionality (largely for display only) # # rs.DeleteObjects([EngineSection, Chord]) # try: # rs.DeleteObjects([CutCirc]) # except: # pass # # try: # rs.DeleteObjects([CutCircDisk]) # except: # pass # # # Windows # # # Cockpit windows: CockpitWindowTop = 0.305*FuselageHeight print("Making Fuselage Windows...") # solids = Fus.CockpitWindowContours(Height=CockpitWindowTop, Depth=6) # ## Cut the windows out: # for solid in solids: # Fus['OML'] = act.SplitShape(Fus['OML'], solid) # # # print("Cockpit Windows Done.") ## ## (Xmin,Ymin,Zmin,Xmax,Ymax,Zmax) = act.ObjectsExtents([Win1, Win2, Win3, Win4]) CockpitBulkheadX = NoseLengthRatio*FuselageLength*0.9 ## ## CockpitWallPlane = rs.PlaneFromPoints([CockpitBulkheadX, -15,-15], ## [CockpitBulkheadX,15,-15], ## [CockpitBulkheadX,-15,15]) ## ## CockpitWall = rs.AddPlaneSurface(CockpitWallPlane, 30, 30) ## ## if 'WTBF' in locals(): ## rs.TrimBrep(WTBF, CockpitWall) ## ## rs.DeleteObject(CockpitWall) # ## # Window lines WIN = [1] NOWIN = [0] ## ### # A typical window pattern (including emergency exit windows) WinVec = WIN + 2*NOWIN + 9*WIN + 3*NOWIN + WIN + NOWIN + 24*WIN + 2*NOWIN + WIN + NOWIN + 14*WIN + 2*NOWIN + WIN + 20*WIN + 2*NOWIN + WIN + NOWIN + 20*WIN wires = [] if FuselageHeight < 8.0: ### # Single deck WindowLineHeight = 0.3555*FuselageHeight WinX = 0.1157*FuselageLength WindowPitch = 0.609 WinInd = -1 i = 0 while WinX < 0.75*FuselageLength: WinInd = WinInd + 1 if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: i=i+1 print("Generating cabin window {}".format(i)) WinCenter = [WinX, WindowLineHeight] W_wire = Fus.WindowContour(WinCenter) wires.append(W_wire) # display.DisplayShape(W_wire, color='black') # win_port, win_stbd = Fus.MakeWindow(*WinCenter) # print(type(win_port), type(win_stbd)) # # display.DisplayShape(win_port, color='Black') # display.DisplayShape(win_stbd, color='Black') # ### Note: Need to fix makewindow to return windows WinStbd, ## # WinPort, # Fus.MakeWindow(WinX, WindowLineHeight) ### act.AssignMaterial(WinStbd,"Plexiglass") ### act.AssignMaterial(WinPort,"Plexiglass") WinX = WinX + WindowPitch # # print("Cabin windows done") # else: # # TODO: Fuselage big enough to accommodate two decks # # Lower deck # WindowLineHeight = 0.17*FuselageHeight #0.166 # WinX = 0.1*FuselageLength #0.112 # WindowPitch = 0.609 # WinInd = 0 # while WinX < 0.757*FuselageLength: # WinInd = WinInd + 1 # if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: # WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(FuselageOMLSurf, WinX, WindowLineHeight) # act.AssignMaterial(WinStbd,"Plexiglass") # act.AssignMaterial(WinPort,"Plexiglass") # WinX = WinX + WindowPitch # # Upper deck # WindowLineHeight = 0.49*FuselageHeight # WinX = 0.174*FuselageLength #0.184 # WinInd = 0 # while WinX < 0.757*FuselageLength: # WinInd = WinInd + 1 # if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: # WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(FuselageOMLSurf, WinX, WindowLineHeight) # act.AssignMaterial(WinStbd,"Plexiglass") # act.AssignMaterial(WinPort,"Plexiglass") # WinX = WinX + WindowPitch # # # # # # act.AssignMaterial(FuselageOMLSurf,"White_composite_external") # act.AssignMaterial(WingSurf,"White_composite_external") # try: # act.AssignMaterial(TPSurf,"ShinyBARedMetal") # except: # pass # act.AssignMaterial(FinSurf,"ShinyBARedMetal") # act.AssignMaterial(Win1,"Plexiglass") # act.AssignMaterial(Win2,"Plexiglass") # act.AssignMaterial(Win3,"Plexiglass") # act.AssignMaterial(Win4,"Plexiglass") # # # # Mirror the geometry as required Wing2 = Wing.MirrorComponents(plane='xz') try: # this try section allows box wing i.e. no tailplane TP2 = TP.MirrorComponents(plane='xz') except: pass engines_left = [] for eng in engines: engines_left.append(eng.MirrorComponents(plane='xz')) # if Propulsion == 1: # for ObjId in EngineStbd: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd) # elif Propulsion == 2: # raise NotImplementedError # for ObjId in EngineStbd1: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd1) # for ObjId in EngineStbd2: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd2) # Build the return assembly (could change this later based on input 'tree': airliner = AirconicsCollection(parts={'Wing_right': Wing, 'Wing_left': Wing2, 'Fuselage': Fus, 'Fin': Fin, 'Tailplane_right': TP, 'Tailplane_left': TP2, 'WBF': WBF}) # Loop over the engines and write all components: for i, eng in enumerate(engines): name = 'engine_right' + str(i+1) airliner.AddPart(eng, name) for i, eng in enumerate(engines_left): name = 'engine_left' + str(i+1) airliner.AddPart(eng, name) return airliner, wires
pz = -1*(pxy[0]**2/(2*r_z) + pxy[1]**2/(2*r_z)) pln = surf_spl(*pxy, pz, axs) wxy = Geom_Ellipse (ax2, w_z, w_z).Elips() wxy = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge (wxy).Edge()).Wire() print (wxy, pln) api.AddWire(wxy) display.DisplayShape (pnt) display.DisplayShape (pln) display.DisplayShape (wxy) api.Build() surf_wxy = api.Shape() display.DisplayShape(surf_wxy) pnt = gp_Pnt (0, 0, 500) axs = gp_Ax3 (pnt, gp_Dir(0, 0, 1)) axs.Rotate(gp_Ax1(axs.Location(), axs.XDirection()), np.deg2rad(5)) axs.Rotate(gp_Ax1(axs.Location(), axs.YDirection()), np.deg2rad(30)) ax2 = axs.Ax2() px = np.linspace(-1, 1, 100) * 100 py = np.linspace(-1, 1, 100) * 100 mesh = np.meshgrid (px, py) surf = mesh[0]**2/1000 + mesh[1]**2/1000 #pln = make_plane (axs.Location(), dir_to_vec(axs.Direction())) pln = surf_spl(*mesh, surf, axs) display.DisplayShape (pln) #print (TopoDS_Face(pln)) print (surf_wxy, pln) for face in Topo(surf_wxy).faces(): surf_wxy = BRep_Tool.Surface(face).GetObject() for face in Topo(pln).faces():
parser.add_option("--surf", dest="surf", default="surf2") parser.add_option("--pxyz", dest="pxyz", default=(0, 0, 0), type="float", nargs=3) parser.add_option("--rxyz", dest="rxyz", default=(0, 0, 0), type="float", nargs=3) opt, argc = parser.parse_args(argvs) print(argc, opt) filename = opt.dir + opt.refe + ".cor" ax = get_axs(filename) print(dir_to_vec(ax.Direction()), ax.Location()) ax.Translate(gp_Vec(gp_Pnt(), gp_Pnt(*opt.pxyz))) for i, deg in enumerate(opt.rxyz): if i == 0: axs = gp_Ax1(ax.Location(), ax.XDirection()) elif i == 1: axs = gp_Ax1(ax.Location(), ax.YDirection()) elif i == 2: axs = gp_Ax1(ax.Location(), ax.Direction()) else: axs = gp_Ax1(ax.Location(), ax.Direction()) ax.Rotate(axs, np.deg2rad(deg)) print(dir_to_vec(ax.Direction()), ax.Location()) occ_to_grasp_cor(ax, opt.surf, opt.out + opt.surf + ".cor")
def rotate(shape, rot_pt, axis, degree): gp_ax3 = gp_Ax1(gp_Pnt(rot_pt[0], rot_pt[1], rot_pt[2]), gp_Dir(axis[0], axis[1], axis[2])) rot_shape = Construct.rotate(shape, gp_ax3, degree, copy=False) return rot_shape
from OCC.BRepLib import breplib_BuildCurves3d from OCC.GC import GC_MakeArcOfEllipse from OCC.Geom import Geom_BezierCurve, Geom_BSplineCurve from OCC.gp import gp_Dir, gp_Pnt, gp_Circ, gp_Elips, gp_Ax1, gp_Ax2, gp_Trsf from OCC.TColgp import TColgp_Array1OfPnt from OCC.TopoDS import TopoDS_Shape, TopoDS_Compound, topods from .occ_shape import OccShape from ..draw import ProxySvg from declaracad.core.utils import log Z_DIR = gp_Dir(0, 0, 1) NEG_Z_DIR = gp_Dir(0, 0, -1) Z_AXIS = gp_Ax1(gp_Pnt(0, 0, 0), Z_DIR) UNITS = { 'in': 90.0, 'pt': 1.25, 'px': 1, 'mm': 3.5433070866, 'cm': 35.433070866, 'm': 3543.3070866, 'km': 3543307.0866, 'pc': 15.0, 'yd': 3240, 'ft': 1080 } # From simplepath.py's parsePath by Aaron Spike, [email protected] PATHDEFS = { 'M': ['L', 2, [float, float], ['x', 'y']], 'L': ['L', 2, [float, float], ['x', 'y']], 'H': ['H', 1, [float], ['x']], 'V': ['V', 1, [float], ['y']], 'C': ['C', 6, [float, float, float, float, float, float], ['x', 'y', 'x', 'y', 'x', 'y']],
def show_line(self, origin=(0, 0, 0), direction=(0, 0, 1)): line_placement = Geom_Line(gp_Ax1(gp_Pnt(*origin), gp_Dir(*direction))) line = AIS_Line(line_placement.GetHandle()) self._display_ais(line)
if __name__ == '__main__': argvs = sys.argv parser = OptionParser() parser.add_option("--px", dest="px", default=0.0, type="float") parser.add_option("--dx", dest="dx", default=0.0, type="float") parser.add_option("--py", dest="py", default=0.0, type="float") parser.add_option("--dy", dest="dy", default=0.0, type="float") opt, argc = parser.parse_args(argvs) ax, pln = def_ax(0, 0, 0, lx=100, ly=100) m1_ax, m1_pln = def_ax(0, 0, 470, dx=-45) m2_ax, m2_pln = def_ax(0, -250, 470, dx=45, dy=180) wg_ax, wg_pln = def_ax(0, -250, 470 + 360, lx=100, ly=100, dy=0) ax0 = gp_Ax3(gp_Pnt(opt.px, opt.py, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0)) rot_axs(ax0, gp_Ax1(ax0.Location(), ax0.XDirection()), opt.dx) rot_axs(ax0, gp_Ax1(ax0.Location(), ax0.YDirection()), opt.dy) pnt = ax0.Location() vec = dir_to_vec(ax0.Direction()) m1_pnt, m1_vec = reflect(pnt, vec, m1_ax) m2_pnt, m2_vec = reflect(m1_pnt, m1_vec, m2_ax) wg_pnt, wg_vec = reflect(m2_pnt, m2_vec, wg_ax) wg_vec.Reverse() wg_p = wg_ax.Location() print(np.rad2deg(get_angle(wg_ax, wg_vec, dir_to_vec(wg_ax.Direction())))) print(wg_pnt.X() - wg_p.X(), wg_pnt.Y() - wg_p.Y()) """ display, start_display, add_menu, add_function_to_menu = init_display() display.DisplayShape (pnt) display.DisplayShape (pln)
def list_wire_combo(num_cell, ang, offset, radius): ''' input nc: int, number of cells to be combined ang: float, angle between adjaent cells offset: float, offset angle of start position ri: float, radius of this ring output wlist: {TopoDS_Wire: string} combo_name: '' ''' combo_name = '' pos_list = list(range(num_cell)) wlist = {} pos_len_name = {} while len(pos_list) > 0: # 1 choose a random location pos = random.choice(pos_list) # 2 choose a random length len_seq = len_seq_natural(pos, pos_list) len_seq = random.randrange(1, len_seq + 1) # 3 choose a random shape func = random.choice(FLIST) # print(pos_list, pos, l, fname[FLIST.index(func)]) trsf_scale = gp_Trsf() trsf_scale.SetScale(DRAIN_RCS.Location(), DRAIN_S) trsf_trans = gp_Trsf() trans_vec = gp_Vec(DRAIN_RCS.XDirection()) * radius trsf_trans.SetTranslation(trans_vec) trsf_rotate = gp_Trsf() trsf_rotate.SetRotation( gp_Ax1(DRAIN_RCS.Location(), DRAIN_RCS.Direction()), offset + pos * ang) if func == wire_sweep_circle and len_seq > 1: cir1 = DRAIN_RCS.Location() cir2 = DRAIN_RCS.Location() cir1.Translate(trans_vec) cir1.Rotate(gp_Ax1(DRAIN_RCS.Location(), DRAIN_RCS.Direction()), offset + pos * ang) cir2.Translate(trans_vec) cir2.Rotate(gp_Ax1(DRAIN_RCS.Location(), DRAIN_RCS.Direction()), offset + (pos + len_seq - 1) * ang) wire = wire_sweep_circle(cir1, cir2) elif func != wire_sweep_circle and len_seq == 1: wire = func() bresp_trsf = BRepBuilderAPI_Transform(wire, trsf_scale) wire = topods.Wire(bresp_trsf.Shape()) bresp_trsf = BRepBuilderAPI_Transform(wire, trsf_trans) wire = topods.Wire(bresp_trsf.Shape()) bresp_trsf = BRepBuilderAPI_Transform(wire, trsf_rotate) wire = topods.Wire(bresp_trsf.Shape()) else: continue wname = SKETCH_TYPE[FLIST.index(func)] pos_len_name[pos] = (len_seq, wname) wlist[wire] = wname for pos in range(pos, pos + len_seq): pos_list.remove(pos) pos_len_name = sorted(pos_len_name.items(), key=lambda t: t[0]) for pos in pos_len_name: combo_name += str(pos[1][0]) + '[' + pos[1][1] + ']' return wlist, combo_name
def compute_inertia_and_center_of_mass(shapes, io=None): """ Compute inertia from a list of Shapes. """ from OCC.GProp import GProp_GProps from OCC.BRepGProp import brepgprop_VolumeProperties from OCC.gp import gp_Ax1, gp_Dir from siconos.mechanics import occ system = GProp_GProps() for shape in shapes: iprops = GProp_GProps() if shape.data is None: if io is not None: shape.data = io._shape.get(shape.shape_name, new_instance=True) else: warn('cannot get shape {0}'.format(shape.shape_name)) return None iishape = shape.data ishape = occ.OccContactShape(iishape).data() # the shape relative displacement occ.occ_move(ishape, list(shape.translation) + list(shape.orientation)) brepgprop_VolumeProperties(iishape, iprops) density = None if hasattr(shape, 'mass') and shape.mass is not None: density = shape.mass / iprops.Mass() elif shape.parameters is not None and \ hasattr(shape.parameters, 'density'): density = shape.parameters.density #print('shape.parameters.density:', shape.parameters.density) else: density = 1. assert density is not None # print("shape", shape.shape_name) # print('density:', density) # print('iprops.Mass():', iprops.Mass()) system.Add(iprops, density) mass= system.Mass() assert (system.Mass() > 0.) computed_com = system.CentreOfMass() gp_mat= system.MatrixOfInertia() inertia_matrix = np.zeros((3,3)) for i in range(0,3): for j in range(0,3): inertia_matrix[i,j]= gp_mat.Value(i+1,j+1) I1 = system.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(1, 0, 0))) I2 = system.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(0, 1, 0))) I3 = system.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(0, 0, 1))) inertia = [I1, I2, I3] center_of_mass = np.array([computed_com.Coord(1), computed_com.Coord(2), computed_com.Coord(3)]) return mass, center_of_mass, inertia, inertia_matrix
def compute_inertia_and_center_of_mass(shapes, mass, io=None): """ Compute inertia from a list of Shapes. """ from OCC.GProp import GProp_GProps from OCC.BRepGProp import brepgprop_VolumeProperties from OCC.gp import gp_Ax1, gp_Dir from siconos.mechanics import occ props = GProp_GProps() for shape in shapes: iprops = GProp_GProps() if shape.data is None: if io is not None: shape.data = io._shape.get(shape.shape_name, new_instance=True) else: warn('cannot get shape {0}'.format(shape.shape_name)) return None iishape = shape.data ishape = occ.OccContactShape(iishape).data() # the shape relative displacement occ.occ_move(ishape, list(shape.translation) + list(shape.orientation)) brepgprop_VolumeProperties(iishape, iprops) density = None if hasattr(shape, 'mass') and shape.mass is not None: density = shape.mass / iprops.Mass() elif shape.parameters is not None and \ hasattr(shape.parameters, 'density'): density = shape.parameters.density else: density = 1. assert density is not None props.Add(iprops, density) assert (props.Mass() > 0.) global_density = mass / props.Mass() computed_com = props.CentreOfMass() I1 = global_density * props.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(1, 0, 0))) I2 = global_density * props.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(0, 1, 0))) I3 = global_density * props.MomentOfInertia( gp_Ax1(computed_com, gp_Dir(0, 0, 1))) inertia = [I1, I2, I3] center_of_mass = np.array( [computed_com.Coord(1), computed_com.Coord(2), computed_com.Coord(3)]) return inertia, center_of_mass
# original implementation with occ backend import siconos.io.mechanics_io siconos.io.mechanics_io.set_implementation('original') siconos.io.mechanics_io.set_backend('occ') # ball shape ball = BRepPrimAPI_MakeSphere(.15).Shape() ball_props = GProp_GProps() brepgprop_VolumeProperties(ball, ball_props) ball_mass = ball_props.Mass() ball_com = ball_props.CentreOfMass() ball_inertia = ball_props.MatrixOfInertia() ball_I1 = ball_props.MomentOfInertia(gp_Ax1(ball_com, gp_Dir(1, 0, 0))) ball_I2 = ball_props.MomentOfInertia(gp_Ax1(ball_com, gp_Dir(0, 1, 0))) ball_I3 = ball_props.MomentOfInertia(gp_Ax1(ball_com, gp_Dir(0, 0, 1))) print 'ball mass:', ball_mass print 'ball center of mass:', (ball_com.Coord(1), ball_com.Coord(2), ball_com.Coord(3)) print 'ball moment of inertia:', (ball_I1, ball_I2, ball_I3) # the ground ground = BRepPrimAPI_MakeBox(gp_Pnt(-20, -20, 0), 40., 40., .5).Shape() # bowl shape hspherei = BRepPrimAPI_MakeSphere(.9, pi).Shape() hsphereo = BRepPrimAPI_MakeSphere(1., pi).Shape() bowl = BRepAlgoAPI_Cut(hsphereo, hspherei).Shape()
def track_render(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() use_raw_image = True #don't do any processing on the image from the webcam before sending it to the face recog algo #cascPathLeft = '/Applications/opencv-2.4.9/data/haarcascades/haarcascade_lefteye_2splits.xml' #cascPathLeft = '/Applications/opencv-2.4.9/data/haarcascades/haarcascade_frontalface_default.xml' cascPathFace = '/Applications/opencv-2.4.9/data/haarcascades/haarcascade_frontalface_default.xml' cascPathLeft = '/Applications/opencv-2.4.9/data/haarcascades/haarcascade_mcs_lefteye.xml' cascPathRight = '/Applications/opencv-2.4.9/data/haarcascades/haarcascade_mcs_righteye.xml' cascPath = [cascPathFace] cascade =[] for i in xrange(len(cascPath)): cascade += [cv2.CascadeClassifier(cascPath[i])] video_capture = cv2.VideoCapture(0) angle = 0.0 while True: # Capture frame-by-frame if use_raw_image: ret, frame = video_capture.read() gray2 = frame else: ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #gray2 = cv2.equalizeHist(gray) #remove saturated regions from the image... this helps if the subject is underlit #a = np.array(np.random.randint(200,245, (gray.shape[0], gray.shape[1])),dtype=np.uint8) gray = gray*(gray<200) #+ a*(gray>=245) #gray2 = gray*(gray<150) #+ a*(gray>=245) gray2 = cv2.equalizeHist(gray) all_faces = [] for i in xrange(len(cascade)): ''' faces = cascade[i].detectMultiScale( gray2, scaleFactor=4.0, minNeighbors=5, minSize=(20, 20), flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) ''' faces = cascade[i].detectMultiScale( gray2, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) all_faces += list(faces) #print all_faces, len(all_faces) print all_faces size_largest =0 for f in all_faces: if f[2]*f[3] > size_largest: size_largest = f[2]*f[3] face = f ''' # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display the resulting frame cv2.imshow('Video', gray2) ''' aCubeTrsf.SetRotation(ax1, angle) aCubeToploc = TopLoc_Location(aCubeTrsf) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() try: angle -= (face[0] - all_faces_prev[0])/300.0 except: None all_faces_prev = face # Stop video capture # in the opencv window (ie NOT in the terminal) hold down a key - you might have to hold it down a bit. #print 'click in the opencv window and hold down a key to quit' if cv2.waitKey(1) != -1: break # When everything is done, release the capture video_capture.release() cv2.destroyAllWindows() video_capture.release()
def make_line(pypt, pydir): occ_line = gp_Lin( gp_Ax1(gp_Pnt(pypt[0], pypt[1], pypt[2]), gp_Dir(pydir[0], pydir[1], pydir[2]))) return occ_line
def show_axis(self, origin=(0, 0, 0), direction=(0, 0, 1)): ax_placement = Geom_Axis1Placement( gp_Ax1(gp_Pnt(*origin), gp_Dir(*direction))) ax = AIS_Axis(ax_placement.GetHandle()) self._display_ais(ax)
#!/usr/bin/python # coding: utf-8 r"""test_revolve.py" """ from math import pi from OCC import BRepPrimAPI, gp, BRepBuilderAPI from viewer import view el = gp.gp_Elips(gp.gp_Ax2(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(1, 0, 0)), 20.0, 10.0) edge1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(el, gp.gp_Pnt(0, 0, 20), gp.gp_Pnt(0, 0, -20)) edge2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(gp.gp_Pnt(0, 0, -20), gp.gp_Pnt(0, 0, 20)) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() wire.Add(edge1.Edge()) wire.Add(edge2.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) el = BRepPrimAPI.BRepPrimAPI_MakeRevol( face.Shape(), gp.gp_Ax1(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, 1)), pi * 2) # h_curve = Geom.Handle_Geom_Ellipse(curve) # rev = BRepPrimAPI.BRepPrimAPI_MakeRevolution(h_curve, 120.1) # #nurbs = BRepBuilderAPI.BRepBuilderAPI_NurbsConvert(rev.Shape()) view(el.Shape())
def setTranslation(self): """ Creates an axis in x, y or z depending on user preference. gp_Ax1 describes an axis in 3D space. An axis is defined by a point (gp_Pnt) and a direction (gp_Dir) reference @return None """ if self._exceptionCatch(): return rotataxis_index_combo = self.op_viewer.ui_shape_rotataxis_combo.currentIndex( ) if self.op_viewer.ui_shape_rotataxis_combo.currentText() == "Z": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0, 0, 1)) elif self.op_viewer.ui_shape_rotataxis_combo.currentText() == "Y": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0, 1, 0)) elif self.op_viewer.ui_shape_rotataxis_combo.currentText() == "X": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(1, 0, 0)) # Retrieve the displacements set by user x = float(self.op_viewer.ui_shape_xdispl_dspn.value()) y = float(self.op_viewer.ui_shape_ydispl_dspn.value()) z = float(self.op_viewer.ui_shape_zdispl_dspn.value()) teta = float(self.op_viewer.ui_shape_tetarotat_dspn.value()) * pi / 180 # creates objects of shape transformation (Returns the identity transformation), # one for axial and other for x, y, z coordinates transf_teta = gp_Trsf() transf_xyz = gp_Trsf() transf_teta.SetRotation(ax1, teta) transf_xyz.SetTranslation(gp_Vec(x, y, z)) # Calculates the transformation matrix with respect of both transformations. transf_matrix = transf_xyz * transf_teta # Constructs an local coordinate system object. Note: A Location constructed from a default datum is said # to be "empty". # ref: https://www.opencascade.com/doc/occt-6.9.1/refman/html/class_top_loc___location.html cube_toploc = TopLoc_Location(transf_matrix) # Then applies the local coordinate to the current shape for i in range(0, len(self.op_viewer.current_h_ais_shape)): self.op_viewer.display.Context.SetLocation( self.op_viewer.current_h_ais_shape[i], cube_toploc) if self.op_viewer.selectionMode == "surf": # If the selected items is the majority of the list, then the property is set to the whole Case if self.op_viewer.ui_subcase_list.count() / 2 < len( self.op_viewer.ui_subcase_list.selectedIndexes()): self.op_viewer.case_node.setShapeTransformation(x, 0) self.op_viewer.case_node.setShapeTransformation(y, 1) self.op_viewer.case_node.setShapeTransformation(z, 2) self.op_viewer.case_node.setShapeTransformation( teta / pi * 180, 3) self.op_viewer.case_node.setShapeTransformation( rotataxis_index_combo, 4) for i in range( 0, len(self.op_viewer.ui_subcase_list.selectedIndexes())): index = self.op_viewer.ui_subcase_list.selectedIndexes()[i] self.op_viewer.case_node.subshape[index.row()][0] = [ x, y, z, teta / pi * 180, rotataxis_index_combo ] if self.op_viewer.selectionMode == "shape": for i in range(0, len(self.op_viewer.case_node.subshape)): self.op_viewer.case_node.subshape[i][0][0] = x self.op_viewer.case_node.subshape[i][0][1] = y self.op_viewer.case_node.subshape[i][0][2] = z self.op_viewer.case_node.subshape[i][0][3] = teta / pi * 180 self.op_viewer.case_node.subshape[i][0][ 4] = rotataxis_index_combo self.op_viewer.display.Context.UpdateCurrentViewer() return
SegmentNo = 101 ChordFact = 1.01 ScaleFact = 21.93 # # print("Creating Fin...") Fin = liftingsurface.LiftingSurface(P, mySweepAngleFunctionFin, myDihedralFunctionFin, myTwistFunctionFin, myChordFunctionFin, myAirfoilFunctionFin, SegmentNo=SegmentNo, ChordFactor=ChordFact, ScaleFactor=ScaleFact) # print("Fin done") # Create the rotation axis centered at the apex point in the x direction RotAxis = gp_Ax1(gp_Pnt(*P), gp_Dir(1, 0, 0)) # Having some problem with the fin loft: display some airfoils # to figure out what's going on: # for section in Fin._Sections: # curve = section.Curve.GetObject() # curve.Scale(gp_Pnt(0., 0., 0.), ScaleFact) # display.DisplayShape(section.Curve, update=True) Fin.RotateComponents(RotAxis, 90) Fin.Display(display) # Position of the apex of the tailplane P = [43, 0.000, 1.633+0.02] SegmentNo = 101
def compute_inertia_and_center_of_mass(shapes, io=None): """ Compute inertia from a list of Shapes. Returns ------- mass center_of_mass inertia inertia_matrix """ from OCC.GProp import GProp_GProps from OCC.BRepGProp import brepgprop_VolumeProperties from OCC.gp import gp_Ax1, gp_Dir from siconos.mechanics import occ system = GProp_GProps() for shape in shapes: iprops = GProp_GProps() if shape.data is None: if io is not None: shape.data = io._shape.get(shape.shape_name, new_instance=True) else: warn('cannot get shape {0}'.format(shape.shape_name)) return None iishape = shape.data ishape = occ.OccContactShape(iishape).data() # the shape relative displacement occ.occ_move(ishape, list(shape.translation) + list(shape.orientation)) brepgprop_VolumeProperties(iishape, iprops) density = None if hasattr(shape, 'mass') and shape.mass is not None: density = shape.mass / iprops.Mass() elif shape.parameters is not None and hasattr(shape.parameters, 'density'): density = shape.parameters.density #print('shape.parameters.density:', shape.parameters.density) else: density = 1. assert density is not None # print("shape", shape.shape_name) # print('density:', density) # print('iprops.Mass():', iprops.Mass()) system.Add(iprops, density) mass = system.Mass() assert (system.Mass() > 0.) computed_com = system.CentreOfMass() gp_mat = system.MatrixOfInertia() inertia_matrix = np.zeros((3, 3)) for i in range(0, 3): for j in range(0, 3): inertia_matrix[i, j] = gp_mat.Value(i + 1, j + 1) I1 = system.MomentOfInertia(gp_Ax1(computed_com, gp_Dir(1, 0, 0))) I2 = system.MomentOfInertia(gp_Ax1(computed_com, gp_Dir(0, 1, 0))) I3 = system.MomentOfInertia(gp_Ax1(computed_com, gp_Dir(0, 0, 1))) inertia = [I1, I2, I3] center_of_mass = np.array( [computed_com.Coord(1), computed_com.Coord(2), computed_com.Coord(3)]) return mass, center_of_mass, inertia, inertia_matrix
if __name__ == "__main__": argvs = sys.argv parser = OptionParser() parser.add_option("--dir", dest="dir", default="./") parser.add_option("--surf", dest="surf", default="surf1") parser.add_option("--pxyz", dest="pxyz", default=(0, 0, 0), type="float", nargs=3) parser.add_option("--rxyz", dest="rxyz", default=(0, 0, 0), type="float", nargs=3) opt, argc = parser.parse_args(argvs) print(argc, opt) ax = gp_Ax3(gp_Pnt(*opt.pxyz), gp_Dir(0, 0, 1)) for i, deg in enumerate(opt.rxyz): if i == 0: axs = gp_Ax1(ax.Location(), gp_Dir(1, 0, 0)) elif i == 1: axs = gp_Ax1(ax.Location(), gp_Dir(0, 1, 0)) elif i == 2: axs = gp_Ax1(ax.Location(), gp_Dir(0, 0, 1)) else: axs = gp_Ax1(ax.Location(), gp_Dir(1, 0, 0)) ax.Rotate(axs, np.deg2rad(deg)) occ_to_grasp_cor(ax, opt.surf, opt.dir + opt.surf + ".cor")
def transonic_airliner(display=None, Propulsion=1, EngineDia=2.9, FuselageScaling=[55.902, 55.902, 55.902], NoseLengthRatio=0.182, TailLengthRatio=0.293, WingScaleFactor=44.56, WingChordFactor=1.0, Topology=1, SpanStation1=0.35, SpanStation2=0.675, EngineCtrBelowLE=0.3558, EngineCtrFwdOfLE=0.9837, Scarf_deg=3): """ Parameters ---------- Propulsion - int 1 - twin 2 - quad EngineDia - float Diameter of engine intake highlight FuselageScaling - list, length 3 Fx, Fy, Fz scaling factors of fuselage NoseLengthRatio - scalar Proportion of forward tapering section of the fuselage TailLengthRatio - scalar Proportion of aft tapering section of the fuselage WingScaleFactor - scalar Scale Factor of the main wing WingChordFactor - scalar Chord factor of the main wing Topology - int Topology = 2 should yield a box wing airliner - use with caution SpanStation - float Inboard engine at this span station SpanStation2 - float Outboard engine at this span station (ignored if Propulsion=1) EngineCtrBelowLE - float Engine below leading edge, normalised by the length of the nacelle - range: [0.35,0.5] EngineCtrFwdOfLE - float Engine forward of leading edge, normalised by the length of the nacelle range: [0.85,1.5] Scarf_deg - scalar # Engine scarf angle Returns ------- airliner - 'Aircraft' class instance The collection of aircraft parts See also -------- class Aircraft """ try: Fus = fuselage_oml.Fuselage(NoseLengthRatio, TailLengthRatio, Scaling=FuselageScaling, NoseCoordinates=[0, 0, 0]) except: print "Fuselage fitting failed - stopping." return None FuselageHeight = FuselageScaling[2] * 0.105 FuselageLength = FuselageScaling[0] FuselageWidth = FuselageScaling[1] * 0.106 if Fus['OML'] is None: print "Failed to fit fuselage surface, stopping." return None # FSurf = rs.CopyObject(FuselageOMLSurf) # Position of the apex of the wing if FuselageHeight < 8.0: #787:[9.77,0,-0.307] WingApex = [0.1748 * FuselageLength, 0, -0.0523 * FuselageHeight] else: WingApex = [0.1748 * FuselageLength, 0, -0.1 * FuselageHeight] #787:[9.77,0,-0.307] # Set up the wing object, including the list of user-defined functions that # describe the spanwise variations of sweep, dihedral, etc. if Topology == 1: NSeg = 10 Wing = liftingsurface.LiftingSurface(WingApex, mySweepAngleFunctionAirliner, myDihedralFunctionAirliner, myTwistFunctionAirliner, myChordFunctionAirliner, myAirfoilFunctionAirliner, SegmentNo=NSeg, ScaleFactor=WingScaleFactor, ChordFactor=WingChordFactor) RootChord = Wing.RootChord elif Topology == 2: NSeg = 101 Wing = liftingsurface.LiftingSurface(WingApex, mySweepAngleFunctionAirliner, bw.myDihedralFunctionBoxWing, myTwistFunctionAirliner, myChordFunctionAirliner, myAirfoilFunctionAirliner, SegmentNo=NSeg, ScaleFactor=WingScaleFactor, ChordFactor=WingChordFactor) RootChord = Wing.RootChord if Topology == 1: # Add wing to body fairing WTBFXCentre = WingApex[ 0] + RootChord / 2.0 + RootChord * 0.1297 # 787: 23.8 if FuselageHeight < 8.0: #Note: I made changes to this in OCC Airconics to get a better fit # - Paul WTBFZ = RootChord * 0.009 #787: 0.2 WTBFheight = 1.8 * 0.1212 * RootChord #787:2.7 WTBFwidth = 1.08 * FuselageWidth else: WTBFZ = WingApex[2] + 0.005 * RootChord WTBFheight = 0.09 * RootChord WTBFwidth = 1.15 * FuselageWidth WTBFlength = 1.167 * RootChord #787:26 WBF_shape = act.make_ellipsoid([WTBFXCentre, 0, WTBFZ], WTBFlength, WTBFwidth, WTBFheight) WBF = AirconicsShape(components={'WBF': WBF_shape}) # Trim wing inboard section CutCirc = act.make_circle3pt([0, WTBFwidth / 4., -45], [0, WTBFwidth / 4., 45], [90, WTBFwidth / 4., 0]) CutCircDisk = act.PlanarSurf(CutCirc) Wing['Surface'] = act.TrimShapebyPlane(Wing['Surface'], CutCircDisk) elif Topology == 2: # Overlapping wing tips CutCirc = act.make_circle3pt((0, 0, -45), (0, 0, 45), (90, 0, 0)) CutCircDisk = act.PlanarSurf(CutCirc) Wing['Surface'] = act.TrimShapebyPlane(Wing['Surface'], CutCircDisk) # Engine installation (nacelle and pylon) NacelleLength = 1.95 * EngineDia if Propulsion == 1: SpanStations = [SpanStation1] elif Propulsion == 2: SpanStations = [SpanStation1, SpanStation2] engines = [] for i, SpanStation in enumerate(SpanStations): EngineSection, Chord = act.CutSect(Wing['Surface'], SpanStation) CEP = Chord.EndPoint() Centreloc = [ CEP.X() - EngineCtrFwdOfLE * NacelleLength, CEP.Y(), CEP.Z() - EngineCtrBelowLE * NacelleLength ] eng = engine.Engine(Chord, CentreLocation=Centreloc, ScarfAngle=Scarf_deg, HighlightRadius=EngineDia / 2.0, MeanNacelleLength=NacelleLength) engines.append(eng) # # Script for generating and positioning the fin # # Position of the apex of the fin P = [0.6524 * FuselageLength, 0.003, FuselageHeight * 0.384] #P = [36.47,0.003,2.254]55.902 if Topology == 1: ScaleFactor = WingScaleFactor / 2.032 #787:21.93 elif Topology == 2: ScaleFactor = WingScaleFactor / 3.5 SegmentNo = 100 ChordFactor = 1.01 #787:1.01 Fin = liftingsurface.LiftingSurface(P, mySweepAngleFunctionFin, myDihedralFunctionFin, myTwistFunctionFin, myChordFunctionFin, myAirfoilFunctionFin, SegmentNo=SegmentNo, ChordFactor=ChordFactor, ScaleFactor=ScaleFactor) # Create the rotation axis centered at the apex point in the x direction RotAxis = gp_Ax1(gp_Pnt(*P), gp_Dir(1, 0, 0)) Fin.RotateComponents(RotAxis, 90) if Topology == 1: # Tailplane P = [0.7692 * FuselageLength, 0.000, FuselageHeight * 0.29] SegmentNo = 100 ChordFactor = 1.01 ScaleFactor = 0.388 * WingScaleFactor #787:17.3 TP = liftingsurface.LiftingSurface(P, mySweepAngleFunctionTP, myDihedralFunctionTP, myTwistFunctionTP, myChordFunctionTP, myAirfoilFunctionTP, SegmentNo=SegmentNo, ChordFactor=ChordFactor, ScaleFactor=ScaleFactor) # OCC_AirCONICS Note: Nothing below here implemented in OCC_AirCONICS - See # Rhino version for this functionality (largely for display only) # # rs.DeleteObjects([EngineSection, Chord]) # try: # rs.DeleteObjects([CutCirc]) # except: # pass # # try: # rs.DeleteObjects([CutCircDisk]) # except: # pass # # # Windows # # # Cockpit windows: CockpitWindowTop = 0.305 * FuselageHeight print("Making Fuselage Windows...") # solids = Fus.CockpitWindowContours(Height=CockpitWindowTop, Depth=6) # ## Cut the windows out: # for solid in solids: # Fus['OML'] = act.SplitShape(Fus['OML'], solid) # # # print("Cockpit Windows Done.") ## ## (Xmin,Ymin,Zmin,Xmax,Ymax,Zmax) = act.ObjectsExtents([Win1, Win2, Win3, Win4]) CockpitBulkheadX = NoseLengthRatio * FuselageLength * 0.9 ## ## CockpitWallPlane = rs.PlaneFromPoints([CockpitBulkheadX, -15,-15], ## [CockpitBulkheadX,15,-15], ## [CockpitBulkheadX,-15,15]) ## ## CockpitWall = rs.AddPlaneSurface(CockpitWallPlane, 30, 30) ## ## if 'WTBF' in locals(): ## rs.TrimBrep(WTBF, CockpitWall) ## ## rs.DeleteObject(CockpitWall) # ## # Window lines WIN = [1] NOWIN = [0] ## ### # A typical window pattern (including emergency exit windows) WinVec = WIN + 2 * NOWIN + 9 * WIN + 3 * NOWIN + WIN + NOWIN + 24 * WIN + 2 * NOWIN + WIN + NOWIN + 14 * WIN + 2 * NOWIN + WIN + 20 * WIN + 2 * NOWIN + WIN + NOWIN + 20 * WIN wires = [] if FuselageHeight < 8.0: ### # Single deck WindowLineHeight = 0.3555 * FuselageHeight WinX = 0.1157 * FuselageLength WindowPitch = 0.609 WinInd = -1 i = 0 while WinX < 0.75 * FuselageLength: WinInd = WinInd + 1 if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: i = i + 1 print("Generating cabin window {}".format(i)) WinCenter = [WinX, WindowLineHeight] W_wire = Fus.WindowContour(WinCenter) wires.append(W_wire) # display.DisplayShape(W_wire, color='black') # win_port, win_stbd = Fus.MakeWindow(*WinCenter) # print(type(win_port), type(win_stbd)) # # display.DisplayShape(win_port, color='Black') # display.DisplayShape(win_stbd, color='Black') # ### Note: Need to fix makewindow to return windows WinStbd, ## # WinPort, # Fus.MakeWindow(WinX, WindowLineHeight) ### act.AssignMaterial(WinStbd,"Plexiglass") ### act.AssignMaterial(WinPort,"Plexiglass") WinX = WinX + WindowPitch # # print("Cabin windows done") # else: # # TODO: Fuselage big enough to accommodate two decks # # Lower deck # WindowLineHeight = 0.17*FuselageHeight #0.166 # WinX = 0.1*FuselageLength #0.112 # WindowPitch = 0.609 # WinInd = 0 # while WinX < 0.757*FuselageLength: # WinInd = WinInd + 1 # if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: # WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(FuselageOMLSurf, WinX, WindowLineHeight) # act.AssignMaterial(WinStbd,"Plexiglass") # act.AssignMaterial(WinPort,"Plexiglass") # WinX = WinX + WindowPitch # # Upper deck # WindowLineHeight = 0.49*FuselageHeight # WinX = 0.174*FuselageLength #0.184 # WinInd = 0 # while WinX < 0.757*FuselageLength: # WinInd = WinInd + 1 # if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: # WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(FuselageOMLSurf, WinX, WindowLineHeight) # act.AssignMaterial(WinStbd,"Plexiglass") # act.AssignMaterial(WinPort,"Plexiglass") # WinX = WinX + WindowPitch # # # # # # act.AssignMaterial(FuselageOMLSurf,"White_composite_external") # act.AssignMaterial(WingSurf,"White_composite_external") # try: # act.AssignMaterial(TPSurf,"ShinyBARedMetal") # except: # pass # act.AssignMaterial(FinSurf,"ShinyBARedMetal") # act.AssignMaterial(Win1,"Plexiglass") # act.AssignMaterial(Win2,"Plexiglass") # act.AssignMaterial(Win3,"Plexiglass") # act.AssignMaterial(Win4,"Plexiglass") # # # # Mirror the geometry as required Wing2 = Wing.MirrorComponents(plane='xz') try: # this try section allows box wing i.e. no tailplane TP2 = TP.MirrorComponents(plane='xz') except: pass engines_left = [] for eng in engines: engines_left.append(eng.MirrorComponents(plane='xz')) # if Propulsion == 1: # for ObjId in EngineStbd: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd) # elif Propulsion == 2: # raise NotImplementedError # for ObjId in EngineStbd1: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd1) # for ObjId in EngineStbd2: # act.MirrorObjectXZ(ObjId) # act.MirrorObjectXZ(PylonStbd2) # Build the return assembly (could change this later based on input 'tree': airliner = AirconicsCollection( parts={ 'Wing_right': Wing, 'Wing_left': Wing2, 'Fuselage': Fus, 'Fin': Fin, 'Tailplane_right': TP, 'Tailplane_left': TP2, 'WBF': WBF }) # Loop over the engines and write all components: for i, eng in enumerate(engines): name = 'engine_right' + str(i + 1) airliner.AddPart(eng, name) for i, eng in enumerate(engines_left): name = 'engine_left' + str(i + 1) airliner.AddPart(eng, name) return airliner, wires
wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) edge = BRepBuilderAPI_MakeEdge(gp_Pnt(90, xt8, 0), gp_Pnt(100, xt8, 0)) wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) edge = BRepBuilderAPI_MakeEdge(gp_Pnt(100, xt8, 0), gp_Pnt(100, 0, 0)) wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) edge = BRepBuilderAPI_MakeEdge(gp_Pnt(100, 0, 0), gp_Pnt(0, 0, 0)) wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) # делаем из контура фейс face = BRepBuilderAPI_MakeFace(mkWire.Wire()) # поворациваем профель относительно однрй из своих сторон, ось # вращения указана вектором, поворачиваем на 180 градусов solid_of_revol = BRepPrimAPI_MakeRevol(face.Face(), gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(1, 0, 0)), 2 * math.pi) # Создаём вырез # Рисуем профиль и вытягиваем его R = 5 + D / 2 b_max = 20 y = - (b_max * math.tan(gamma)) z = -(R - b_max) mkWire = BRepBuilderAPI_MakeWire() edge = BRepBuilderAPI_MakeEdge(gp_Pnt(0, y, z), gp_Pnt(0, R, z)) wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) edge = BRepBuilderAPI_MakeEdge(gp_Pnt(0, R, z), gp_Pnt(0, R, -R)) wire = BRepBuilderAPI_MakeWire(edge.Edge()) mkWire.Add(wire.Wire()) edge = BRepBuilderAPI_MakeEdge(gp_Pnt(0, R, -R), gp_Pnt(0, 0, -R)) wire = BRepBuilderAPI_MakeWire(edge.Edge())
from OCC import BRepPrimAPI, Geom, gp, BRepBuilderAPI from viewer import view from math import pi el = gp.gp_Elips(gp.gp_Ax2(gp.gp_Pnt(0,0,0), gp.gp_Dir(1,0,0)), 20.0, 10.0) edge1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(el, gp.gp_Pnt(0,0,20), gp.gp_Pnt(0,0,-20)) edge2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(gp.gp_Pnt(0,0,-20), gp.gp_Pnt(0,0,20)) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() wire.Add(edge1.Edge()) wire.Add(edge2.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) el = BRepPrimAPI.BRepPrimAPI_MakeRevol(face.Shape(), gp.gp_Ax1(gp.gp_Pnt(0,0,0), gp.gp_Dir(0,0,1)), pi*2) #h_curve = Geom.Handle_Geom_Ellipse(curve) #rev = BRepPrimAPI.BRepPrimAPI_MakeRevolution(h_curve, 120.1) ##nurbs = BRepBuilderAPI.BRepBuilderAPI_NurbsConvert(rev.Shape()) view(el.Shape())
wp_bottom = topods.Wire(wp_bottom) # wire case_bottom = BRepBuilderAPI_Transform(case_top, mirror).Shape() case_bottom = topods.Wire(case_bottom) # wire # translate outer sections trans = gp_Trsf() trans.SetTranslation(gp_Pnt(loop[0]['p3']['r'], 0, loop[0]['p3']['z']), gp_Pnt(loop[3]['p0']['r'], 0, loop[3]['p0']['z'])) wp_bottom = BRepBuilderAPI_Transform(wp_bottom, trans).Shape() wp_bottom = topods.Wire(wp_bottom) # wire case_bottom = BRepBuilderAPI_Transform(case_bottom, trans).Shape() case_bottom = topods.Wire(case_bottom) # wire # rotate outboard rotate = gp_Trsf() axis = gp_Ax1(gp_Pnt(loop[0]['p3']['r'], 0, loop[0]['p3']['z']), gp_Dir(0, 1, 0)) angle = -loop[2]['p0']['t'] rotate.SetRotation(axis, angle) case_outer = BRepBuilderAPI_Transform(case_top, rotate).Shape() wp_outer = BRepBuilderAPI_Transform(wp_top, rotate).Shape() # translate outboard trans = gp_Trsf() trans.SetTranslation(gp_Pnt(loop[0]['p3']['r'], 0, loop[0]['p3']['z']), gp_Pnt(loop[1]['p3']['r'], 0, loop[1]['p3']['z'])) case_outer = BRepBuilderAPI_Transform(case_outer, trans).Shape() case_outer = topods.Wire(case_outer) # wire wp_outer = BRepBuilderAPI_Transform(wp_outer, trans).Shape() wp_outer = topods.Wire(wp_outer) # wire TFprofile = {}