def accept(self):
        self.v.removeEventCallback("SoEvent", self.track)

        for obj in FreeCAD.ActiveDocument.Objects:
            if 'Point_d_w_h' == obj.Name:
                FreeCAD.ActiveDocument.removeObject('Point_d_w_h')

        dict_size = {0: 8, 1: 11, 2: 14, 3: 17, 5: 23, 6: 34, 7: 42}
        size = dict_size[self.NemaMotor.Size.currentIndex()]
        base_h = self.NemaMotor.Height.value()
        shaft_l = self.NemaMotor.shaft_h.value()
        shaft_r = self.NemaMotor.shaft_r.value()
        shaft_br = self.NemaMotor.shaft_br.value()
        shaft_hr = self.NemaMotor.shaft_bh.value()
        chmf_r = self.NemaMotor.chmf_r.value()
        bolt_d = self.NemaMotor.bolt_d.value()
        pitch = self.NemaMotor.pulley_pitch.value()
        teeth = self.NemaMotor.pulley_teeth.value()
        top_flan = self.NemaMotor.pulley_top_flan.value()
        bot_flan = self.NemaMotor.pulley_bot_flan.value()
        positions_d = [0, 1, 2, 3, 4]
        positions_w = [0, 1, 2, 3, 4]
        positions_h = [0, 1, 2, 3, 4, 5]
        pos_d = positions_d[self.NemaMotor.pos_d.currentIndex()]
        pos_w = positions_w[self.NemaMotor.pos_w.currentIndex()]
        pos_h = positions_h[self.NemaMotor.pos_h.currentIndex()]
        pos = FreeCAD.Vector(self.NemaMotor.pos_x.value(),
                             self.NemaMotor.pos_y.value(),
                             self.NemaMotor.pos_z.value())
        axis_d = FreeCAD.Vector(self.NemaMotor.axis_d_x.value(),
                                self.NemaMotor.axis_d_y.value(),
                                self.NemaMotor.axis_d_z.value())
        axis_w = FreeCAD.Vector(self.NemaMotor.axis_w_x.value(),
                                self.NemaMotor.axis_w_y.value(),
                                self.NemaMotor.axis_w_z.value())
        axis_h = FreeCAD.Vector(self.NemaMotor.axis_h_x.value(),
                                self.NemaMotor.axis_h_y.value(),
                                self.NemaMotor.axis_h_z.value())

        if ortonormal_axis(axis_d, axis_w, axis_h) is True:
            NemaMotorPulleySet(
                nema_size=size,
                base_l=base_h,
                shaft_l=shaft_l,
                shaft_r=shaft_r,
                circle_r=shaft_br,
                circle_h=shaft_hr,
                chmf_r=chmf_r,
                rear_shaft_l=0,
                bolt_depth=bolt_d,
                # pulley parameters
                pulley_pitch=pitch,
                pulley_n_teeth=teeth,
                pulley_toothed_h=7.5,
                pulley_top_flange_h=top_flan,
                pulley_bot_flange_h=bot_flan,
                pulley_tot_h=16.,
                pulley_flange_d=15.,
                pulley_base_d=15.,
                pulley_tol=0,
                pulley_pos_h=-1,
                # general parameters
                axis_d=axis_d,
                axis_w=axis_w,  # None
                axis_h=axis_h,
                pos_d=pos_d,
                pos_w=pos_w,
                pos_h=pos_h,
                pos=pos,
                group=1,
                name=None)

            FreeCADGui.activeDocument().activeView().viewAxonometric()
            FreeCADGui.Control.closeDialog()  # close the dialog
            FreeCADGui.SendMsgToActiveView("ViewFit")
def setup(doc=None, solvertype="ccxtools"):
    """ Nonlinear material example, plate with hole.

    https://forum.freecadweb.org/viewtopic.php?f=24&t=31997&start=30
    https://forum.freecadweb.org/viewtopic.php?t=33974&start=90
    https://forum.freecadweb.org/viewtopic.php?t=35893

    plate: 400x200x10 mm
    hole: diameter 100 mm (half cross section)
    load: 130 MPa tension
    linear material: Steel, E = 210000 MPa, my = 0.3
    nonlinear material: '240.0, 0.0' to '270.0, 0.025'
    TODO nonlinear material: give more information, use values from harry
    TODO compare results with example from HarryvL

    """

    if doc is None:
        doc = init_doc()

    # geometry objects

    v1 = vec(-200, -100, 0)
    v2 = vec(200, -100, 0)
    v3 = vec(200, 100, 0)
    v4 = vec(-200, 100, 0)
    l1 = ln(v1, v2)
    l2 = ln(v2, v3)
    l3 = ln(v3, v4)
    l4 = ln(v4, v1)
    v5 = vec(0, 0, 0)
    c1 = ci(50, v5)
    face = Part.makeFace([Part.Wire([l1, l2, l3, l4]), c1], "Part::FaceMakerBullseye")
    geom_obj = doc.addObject("Part::Feature", "Hole_Plate")
    geom_obj.Shape = face.extrude(vec(0, 0, 10))
    doc.recompute()

    if FreeCAD.GuiUp:
        import FreeCADGui
        geom_obj.ViewObject.Document.activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

    # analysis
    analysis = ObjectsFem.makeAnalysis(doc, "Analysis")

    # solver
    if solvertype == "calculix":
        solver = analysis.addObject(
            ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX")
        )[0]
    elif solvertype == "ccxtools":
        solver = analysis.addObject(
            ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools")
        )[0]
        solver.WorkingDir = u""
    if solvertype == "calculix" or solvertype == "ccxtools":
        solver.SplitInputWriter = False
        solver.AnalysisType = "static"
        solver.GeometricalNonlinearity = "linear"
        solver.ThermoMechSteadyState = False
        solver.MatrixSolverType = "default"
        solver.IterationsControlParameterTimeUse = False
        solver.GeometricalNonlinearity = 'nonlinear'
        solver.MaterialNonlinearity = 'nonlinear'

    # linear material
    matprop = {}
    matprop["Name"] = "CalculiX-Steel"
    matprop["YoungsModulus"] = "210000 MPa"
    matprop["PoissonRatio"] = "0.30"
    matprop["Density"] = "7900 kg/m^3"
    material = analysis.addObject(
        ObjectsFem.makeMaterialSolid(doc, "Material_lin")
    )[0]
    material.Material = matprop

    # nonlinear material
    nonlinear_material = analysis.addObject(
        ObjectsFem.makeMaterialMechanicalNonlinear(doc, material, "Material_nonlin")
    )[0]
    nonlinear_material.YieldPoint1 = '240.0, 0.0'
    nonlinear_material.YieldPoint2 = '270.0, 0.025'
    # check solver attributes, Nonlinearity needs to be set to nonlinear

    # fixed_constraint
    fixed_constraint = analysis.addObject(
        ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed")
    )[0]
    fixed_constraint.References = [(geom_obj, "Face4")]

    # force constraint
    pressure_constraint = doc.Analysis.addObject(
        ObjectsFem.makeConstraintPressure(doc, "ConstraintPressure")
    )[0]
    pressure_constraint.References = [(geom_obj, "Face2")]
    pressure_constraint.Pressure = 130.0
    pressure_constraint.Reversed = True

    # mesh
    from .meshes.mesh_platewithhole_tetra10 import create_nodes, create_elements
    fem_mesh = Fem.FemMesh()
    control = create_nodes(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating nodes.\n")
    control = create_elements(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating elements.\n")
    femmesh_obj = analysis.addObject(
        doc.addObject("Fem::FemMeshObject", mesh_name)
    )[0]
    femmesh_obj.FemMesh = fem_mesh

    doc.recompute()
    return doc
    def accept(self):

        import Draft
        import Arch
        import Part
        import FreeCADGui
        if self.form.groupNewDocument.isChecked() or (FreeCAD.ActiveDocument is
                                                      None):
            doc = FreeCAD.newDocument()
            if self.form.projectName.text():
                doc.Label = self.form.projectName.text()
            FreeCAD.ActiveDocument = doc
        if not FreeCAD.ActiveDocument:
            FreeCAD.Console.PrintError(
                translate("BIM", "No active document, aborting.") + "\n")
        site = None
        outline = None
        if self.form.groupSite.isChecked():
            site = Arch.makeSite()
            site.Label = self.form.siteName.text()
            site.Address = self.form.siteAddress.text()
            site.Longitude = self.form.siteLongitude.value()
            site.Latitude = self.form.siteLatitude.value()
            if hasattr(site, "NorthDeviation"):
                site.NorthDeviation = self.form.siteDeviation.value()
            elif hasattr(site, "Declination"):
                site.Declination = self.form.siteDeviation.value()
            site.Elevation = FreeCAD.Units.Quantity(
                self.form.siteElevation.text()).Value
        human = None
        if self.form.addHumanFigure.isChecked():
            humanshape = Part.Shape()
            humanpath = os.path.join(os.path.dirname(__file__), "geometry",
                                     "human figure.brep")
            humanshape.importBrep(humanpath)
            human = FreeCAD.ActiveDocument.addObject("Part::Feature", "Human")
            human.Shape = humanshape
            human.Placement.move(FreeCAD.Vector(500, 500, 0))
        if self.form.groupBuilding.isChecked():
            building = Arch.makeBuilding()
            if site:
                site.Group = [building]
            building.Label = self.form.buildingName.text()
            building.BuildingType = self.form.buildingUse.currentText()
            buildingWidth = FreeCAD.Units.Quantity(
                self.form.buildingWidth.text()).Value
            buildingLength = FreeCAD.Units.Quantity(
                self.form.buildingLength.text()).Value
            distVAxes = FreeCAD.Units.Quantity(
                self.form.distVAxes.text()).Value
            distHAxes = FreeCAD.Units.Quantity(
                self.form.distHAxes.text()).Value
            levelHeight = FreeCAD.Units.Quantity(
                self.form.levelHeight.text()).Value
            color = self.form.lineColor.property("color").getRgbF()[:3]
            if buildingWidth and buildingLength:
                outline = Draft.makeRectangle(buildingLength,
                                              buildingWidth,
                                              face=False)
                outline.Label = translate("BIM", "Building Outline")
                outline.ViewObject.DrawStyle = "Dashed"
                outline.ViewObject.LineColor = color
                outline.ViewObject.LineWidth = self.form.lineWidth.value() * 2
                grp = FreeCAD.ActiveDocument.addObject(
                    "App::DocumentObjectGroup")
                grp.Label = translate("BIM", "Building Layout")
                building.addObject(grp)
                grp.addObject(outline)
                if self.form.buildingName.text():
                    outtext = Draft.makeText(
                        [self.form.buildingName.text()],
                        point=FreeCAD.Vector(
                            Draft.getParam("textheight", 0.20) * 0.3,
                            -Draft.getParam("textheight", 0.20) * 1.43, 0))
                    outtext.Label = translate("BIM", "Building Label")
                    outtext.ViewObject.TextColor = color
                    grp.addObject(outtext)
                if human:
                    grp.addObject(human)
            axisV = None
            if self.form.countVAxes.value() and distVAxes:
                axisV = Arch.makeAxis(num=self.form.countVAxes.value(),
                                      size=distVAxes,
                                      name="vaxis")
                axisV.Label = translate("BIM", "Vertical Axes")
                axisV.ViewObject.BubblePosition = "Both"
                axisV.ViewObject.LineWidth = self.form.lineWidth.value()
                axisV.ViewObject.FontSize = Draft.getParam("textheight", 0.20)
                axisV.ViewObject.BubbleSize = Draft.getParam(
                    "textheight", 0.20) * 1.43
                axisV.ViewObject.LineColor = color
                if outline:
                    axisV.setExpression('Length',
                                        outline.Name + '.Height * 1.1')
                    axisV.setExpression(
                        'Placement.Base.y', outline.Name +
                        '.Placement.Base.y - ' + axisV.Name + '.Length * 0.05')
                    axisV.setExpression('Placement.Base.x',
                                        outline.Name + '.Placement.Base.x')
            axisH = None
            if self.form.countHAxes.value() and distHAxes:
                axisH = Arch.makeAxis(num=self.form.countHAxes.value(),
                                      size=distHAxes,
                                      name="haxis")
                axisH.Label = translate("BIM", "Horizontal Axes")
                axisH.ViewObject.BubblePosition = "Both"
                axisH.ViewObject.NumberingStyle = "A,B,C"
                axisH.ViewObject.LineWidth = self.form.lineWidth.value()
                axisH.ViewObject.FontSize = Draft.getParam("textheight", 0.20)
                axisH.ViewObject.BubbleSize = Draft.getParam(
                    "textheight", 0.20) * 1.43
                axisH.Placement.Rotation = FreeCAD.Rotation(
                    FreeCAD.Vector(0, 0, 1), 90)
                axisH.ViewObject.LineColor = color
                if outline:
                    axisH.setExpression('Length',
                                        outline.Name + '.Length * 1.1')
                    axisH.setExpression(
                        'Placement.Base.x',
                        outline.Name + '.Placement.Base.x + ' + axisH.Name +
                        '.Length * 0.945')
                    axisH.setExpression('Placement.Base.y',
                                        outline.Name + '.Placement.Base.y')
            if axisV and axisH:
                axisG = Arch.makeAxisSystem([axisH, axisV])
                axisG.Label = translate("BIM", "Axes")
                grp.addObject(axisG)
            else:
                if axisV:
                    grp.addObject(axisV)
                if axisH:
                    grp.addObject(axisH)
            if self.form.countLevels.value() and levelHeight:
                h = 0
                alabels = []
                for i in range(self.form.countLevels.value()):
                    lev = Arch.makeFloor()
                    lev.Label = translate("BIM", "Level") + " " + str(i)
                    alabels.append(lev.Label)
                    lev.Height = levelHeight
                    lev.Placement.move(FreeCAD.Vector(0, 0, h))
                    h += levelHeight
                    building.addObject(lev)
                    if self.form.levelsWP.isChecked():
                        prx = Draft.makeWorkingPlaneProxy(FreeCAD.Placement())
                        prx.Placement.move(FreeCAD.Vector(0, 0, h))
                        lev.addObject(prx)
                if self.form.levelsAxis.isChecked():
                    axisL = Arch.makeAxis(num=self.form.countLevels.value(),
                                          size=levelHeight,
                                          name="laxis")
                    axisL.Label = translate("BIM", "Level Axes")
                    axisL.ViewObject.BubblePosition = "None"
                    axisL.ViewObject.LineWidth = self.form.lineWidth.value()
                    axisL.ViewObject.FontSize = Draft.getParam(
                        "textheight", 0.20)
                    axisL.Placement.Rotation = FreeCAD.Rotation(
                        FreeCAD.Vector(0.577350269189626, -0.5773502691896257,
                                       0.5773502691896257), 120)
                    axisL.ViewObject.LineColor = color
                    axisL.ViewObject.LabelOffset.Rotation = FreeCAD.Rotation(
                        FreeCAD.Vector(1, 0, 0), 90)
                    axisL.Labels = alabels
                    axisL.ViewObject.ShowLabel = True
                    if outline:
                        axisL.setExpression('Length',
                                            outline.Name + '.Length * 1.1')
                        axisL.setExpression(
                            'Placement.Base.x',
                            outline.Name + '.Placement.Base.x + ' +
                            axisL.Name + '.Length * 0.945')
                        axisL.setExpression('Placement.Base.y',
                                            outline.Name + '.Placement.Base.y')
                        grp.addObject(axisL)
                        axisL.ViewObject.LabelOffset.Base = FreeCAD.Vector(
                            -axisL.Length.Value +
                            Draft.getParam("textheight", 0.20) * 0.43, 0,
                            Draft.getParam("textheight", 0.20) * 0.43)
        self.form.hide()
        FreeCAD.ActiveDocument.recompute()
        if outline:
            FreeCADGui.Selection.clearSelection()
            FreeCADGui.Selection.addSelection(outline)
            FreeCADGui.SendMsgToActiveView("ViewSelection")
            FreeCADGui.Selection.clearSelection()
        if hasattr(FreeCADGui, "Snapper"):
            FreeCADGui.Snapper.show()
        return True
Beispiel #4
0
def setup(doc=None, solvertype="ccxtools"):
    # setup model

    if doc is None:
        doc = init_doc()

    # geometry objects
    # two boxes
    boxlow = doc.addObject("Part::Box", "BoxLower")
    boxupp = doc.addObject("Part::Box", "BoxUpper")
    boxupp.Placement.Base = (0, 0, 10)

    # boolean fragment of the two boxes
    bf = SplitFeatures.makeBooleanFragments(name="BooleanFragments")
    bf.Objects = [boxlow, boxupp]
    bf.Mode = "CompSolid"
    doc.recompute()
    bf.Proxy.execute(bf)
    bf.purgeTouched()
    if FreeCAD.GuiUp:
        for child in bf.ViewObject.Proxy.claimChildren():
            child.ViewObject.hide()
    doc.recompute()

    # extract CompSolid by compound filter tool
    geom_obj = CompoundFilter.makeCompoundFilter(name="MultiMatCompSolid")
    geom_obj.Base = bf
    geom_obj.FilterType = "window-volume"
    geom_obj.Proxy.execute(geom_obj)
    geom_obj.purgeTouched()
    if FreeCAD.GuiUp:
        geom_obj.Base.ViewObject.hide()
    doc.recompute()

    if FreeCAD.GuiUp:
        import FreeCADGui
        geom_obj.ViewObject.Document.activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

    # analysis
    analysis = ObjectsFem.makeAnalysis(doc, "Analysis")

    # solver
    if solvertype == "calculix":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX"))[0]
    elif solvertype == "ccxtools":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools"))[0]
        solver_object.WorkingDir = u""
    if solvertype == "calculix" or solvertype == "ccxtools":
        solver_object.SplitInputWriter = False
        solver_object.AnalysisType = "static"
        solver_object.GeometricalNonlinearity = "linear"
        solver_object.ThermoMechSteadyState = False
        solver_object.MatrixSolverType = "default"
        solver_object.IterationsControlParameterTimeUse = False

    # material
    material_object_low = analysis.addObject(
        ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterialLow"))[0]
    mat = material_object_low.Material
    mat["Name"] = "Aluminium-Generic"
    mat["YoungsModulus"] = "70000 MPa"
    mat["PoissonRatio"] = "0.35"
    mat["Density"] = "2700  kg/m^3"
    material_object_low.Material = mat
    material_object_low.References = [(boxlow, "Solid1")]
    analysis.addObject(material_object_low)

    material_object_upp = analysis.addObject(
        ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterialUpp"))[0]
    mat = material_object_upp.Material
    mat["Name"] = "Steel-Generic"
    mat["YoungsModulus"] = "200000 MPa"
    mat["PoissonRatio"] = "0.30"
    mat["Density"] = "7980 kg/m^3"
    material_object_upp.Material = mat
    material_object_upp.References = [(boxupp, "Solid1")]

    # fixed_constraint
    fixed_constraint = analysis.addObject(
        ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed"))[0]
    fixed_constraint.References = [(geom_obj, "Face5")]

    # pressure_constraint
    pressure_constraint = analysis.addObject(
        ObjectsFem.makeConstraintPressure(doc, "ConstraintPressure"))[0]
    pressure_constraint.References = [(geom_obj, "Face11")]
    pressure_constraint.Pressure = 1000.0
    pressure_constraint.Reversed = False

    # mesh
    from .meshes.mesh_boxes_2_vertikal_tetra10 import create_nodes, create_elements
    fem_mesh = Fem.FemMesh()
    control = create_nodes(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating nodes.\n")
    control = create_elements(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating elements.\n")
    femmesh_obj = analysis.addObject(
        doc.addObject("Fem::FemMeshObject", mesh_name))[0]
    femmesh_obj.FemMesh = fem_mesh

    doc.recompute()
    return doc
def open(filename):
    base_directory = os.path.dirname(filename)
    sub_directory = None
    print('Reading: {}'.format(filename))
    print('Base: {}'.format(base_directory))

    yaml_data = None
    with pythonopen(filename) as f:
        yaml_data = load(f)

    if yaml_data is None:
        raise Exception("Error reading YAML file: {}".format(filename))

    print('YML data: {}'.format(yaml_data))
    if 'settings' in yaml_data:
        if 'subDirectory' in yaml_data['settings']:
            base_directory += '/{}'.format(
                yaml_data['settings']['subDirectory'])
            print('Base: {}'.format(base_directory))

    if 'import' not in yaml_data:
        raise Exception('No \'import\' section in YAML file!!!')

    yaml_data = yaml_data['import']

    for document_name, document_data in yaml_data.items():
        document = App.newDocument(document_name)

        for group_name, group_data in document_data.items():
            document_group = document.addObject("App::DocumentObjectGroup",
                                                group_name)

            if isinstance(group_data, str):
                insertObject(base_directory, group_data, document,
                             document_group)
                continue

            if isinstance(group_data, list):
                for file in group_data:
                    insertObject(base_directory, file, document,
                                 document_group)
                continue

            for file, file_data in group_data.items():
                if file == 'files':
                    for f in file_data:
                        insertObject(base_directory, f, document,
                                     document_group)
                    continue
                if not isinstance(file_data, list):
                    if 'solid' not in file_data:
                        insertObject(base_directory, file, document,
                                     document_group, file_data)
                    else:
                        insertSolid(file, document, document_group, file_data)
                else:
                    for file_data2 in file_data:
                        insertObject(base_directory, file, document,
                                     document_group, file_data2)
        document.recompute()
    Gui.activeDocument().activeView().viewAxonometric()
    Gui.SendMsgToActiveView("ViewFit")
def make_3D_model(models_dir, variant):

    LIST_license = [
        "",
    ]
    modelName = all_params[variant].modelName

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedmodelName)

    case = make_case(all_params[variant])
    casetop = make_case_top(all_params[variant])

    if (all_params[variant].pintype == CASE_THT_TYPE):
        pins = make_pins_tht(all_params[variant])

    if (all_params[variant].pintype == CASE_THT_N_TYPE):
        pins = make_pins_tht_n(all_params[variant])

    if (all_params[variant].pintype == CASE_SMD_TYPE):
        pins = make_pins_smd(all_params[variant])

    show(case)
    show(casetop)
    show(pins)
    #show(pinmark)
    #stop
    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    body_color_key = all_params[variant].body_color_key
    body_top_color_key = all_params[variant].body_top_color_key
    pin_color_key = all_params[variant].pin_color_key

    body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat()
    body_top_color = shaderColors.named_colors[
        body_top_color_key].getDiffuseFloat()
    pin_color = shaderColors.named_colors[pin_color_key].getDiffuseFloat()

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], body_top_color)
    Color_Objects(Gui, objs[2], pin_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_body_top = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]

    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_body_top[:-1]: body_top_color_key,
        col_pin[:-1]: pin_color_key
    }

    expVRML.say(material_substitutions)
    while len(objs) > 1:
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
    doc.Label = CheckedmodelName

    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir = models_dir + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
           STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName, out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
Beispiel #7
0
 def GuiViewFit(self):
     FreeCADGui.SendMsgToActiveView("ViewFit")
     self.timer.stop()
Beispiel #8
0
def make_3D_model(models_dir, model_class, modelName):
    r"""Creates a 3D model and exports it to STEO and VRML.
    :param models_dir: directory name for STEP and VRML 3D model file export
    :type  models_dir: ``string``
    :param model_class: Class containing functions and parameter to generate the 3D model
    :type  model_class: ``class``
    :param modelName: The KiCad file name of the 3D model. 
    :type  modelName: ``string``

    """
    if not model_class.isValidModel ():
        FreeCAD.Console.PrintMessage("Model: " + modelName + ' has invalid parameter and was skipped.\r\n')
        return

    LIST_license = ["",]

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument=Gui.getDocument(CheckedmodelName)
    destination_dir = model_class.get_dest_3D_dir()
    
    material_substitutions = model_class.make_3D_model()
    
    doc = FreeCAD.ActiveDocument
    doc.Label = CheckedmodelName

    objs=GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir=os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir=models_dir+os.sep+destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0]=="":
        LIST_license=Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale=1/2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs=GetListOfObjects(FreeCAD, doc)
    expVRML.say("######################################################################")
    expVRML.say(objs)
    expVRML.say("######################################################################")
    export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
    export_file_name=out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName,out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
Beispiel #9
0
def addtracks():
    global start_time, last_pcb_path, min_drill_size
    global use_LinkGroups, use_AppPart
    import sys

    # cfg_read_all() it doesn't work through different files
    # print (min_drill_size)

    Filter = ""
    pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/kicadStepUp")
    last_pcb_path = pg.GetString("last_pcb_path")
    if len(last_pcb_path) == 0:
        last_pcb_path = ""
    fname, Filter = PySide.QtGui.QFileDialog.getOpenFileName(
        None, "Open File...", make_unicode(last_pcb_path), "*.kicad_pcb")
    path, name = os.path.split(fname)
    #filename=os.path.splitext(name)[0]
    filename = fname
    #importDXF.open(os.path.join(dirname,filename))
    if len(fname) > 0:
        start_time = current_milli_time()
        last_pcb_path = os.path.dirname(fname)
        pg = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/kicadStepUp")
        pg.SetString("last_pcb_path",
                     make_string(last_pcb_path))  # py3 .decode("utf-8")
        prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/kicadStepUpGui")
        pcb_color_pos = prefs.GetInt('pcb_color')
        #pcb_color_values = [light_green,blue,red,purple,darkgreen,darkblue,lightblue,yellow,black,white]
        assign_col = [
            '#41c382', '#2474cf', '#ff4000', '#9a1a85', '#3c7f5d', '#426091',
            '#005fff', '#fff956', '#4d4d4d', '#f0f0f0'
        ]
        #print(pcb_color_pos)
        trk_col = (assign_col[pcb_color_pos])
        if pcb_color_pos == 9:
            slk_col = '#2d2d2d'
        else:
            slk_col = '#f8f8f0'
        mypcb = KicadPCB.load(filename)
        pcbThickness = float(mypcb.general.thickness)
        #print (mypcb.general.thickness)
        #print(mypcb.layers)

        #if version>=4:
        Top_lvl = 0
        Bot_lvl = 31
        #for lynbr in mypcb.layers: #getting layers name
        #    if float(lynbr) == Top_lvl:
        #        LvlTopName=(mypcb.layers['{0}'.format(str(lynbr))][0])
        #    if float(lynbr) == Bot_lvl:
        #        LvlBotName=(mypcb.layers['{0}'.format(str(lynbr))][0])
        #print(LvlTopName,'  ',LvlBotName)
        import kicad_parser
        reload_lib(kicad_parser)
        pcb = kicad_parser.KicadFcad(filename)
        #pcb.setLayer(LvlTopName)
        minSizeDrill = 0.0  #0.8
        #print(pcb.colors)
        # https://www.seeedstudio.com/blog/2017/07/23/why-are-printed-circuit-boards-are-usually-green-in-colour/
        # <span style="color: #105e7d;">deep-sea blue</span></strong>, <strong><span style="color: #ff2f00;">Ferrari red</span></strong>, <strong><span style="color: #ffcc00;">sunshine yellow</span></strong>, <strong>slick black</strong>, <span style="color: #999999;"><strong>pure white</strong></span> and of course <strong><span style="color: #339966;">good</span></strong> <strong><span style="color: #339966;">ol’ green</span>
        # (r/255.0,g/255.0,b/255.0)
        pcb_col = pcb.colors
        #zone_col = pcb_col['zone'][0]
        #track_col = pcb_col['track'][0]
        pcb_col['track'][0] = mkColor(trk_col)
        pcb_col['zone'][0] = mkColor(trk_col)

        #pcb_col['track'][0] = mkColor('#147b9d')
        #pcb_col['zone'][0] = mkColor('#147b9d')
        #pcb.colors = {
        #   'board':mkColor("0x3A6629"),
        #   'pad':{0:mkColor(219,188,126)},
        #   'zone':{0:mkColor('#147b9d')},
        #   'track':{0:mkColor(26,157,204)},
        #   'copper':{0:mkColor(200,117,51)},
        #}
        #pcb.colors={'board':(1.,1.,1.),'pad':{0:(219/255,188/255,126/255)},'zone':{0:(0.,1.,0.)},'track':{0:(0.,1.,1.)},'copper':{0:(0.,1.,1.)},}
        pcb.setLayer(Top_lvl)
        #try:   #doing top tracks layer
        pcb.makeCopper(holes=True, minSize=minSizeDrill)
        doc = FreeCAD.ActiveDocument
        docG = FreeCADGui.ActiveDocument
        deltaz = 0.01  #10 micron
        composed = doc.ActiveObject
        s = composed.Shape
        doc.addObject('Part::Feature', 'topTracks').Shape = composed.Shape
        topTracks = doc.ActiveObject
        #print (doc.ActiveObject.Label)
        #print (topTracks.Label)
        docG.ActiveObject.ShapeColor = docG.getObject(composed.Name).ShapeColor
        docG.ActiveObject.LineColor = docG.getObject(composed.Name).LineColor
        docG.ActiveObject.PointColor = docG.getObject(composed.Name).PointColor
        docG.ActiveObject.DiffuseColor = docG.getObject(
            composed.Name).DiffuseColor
        #doc.recompute()
        #doc.addObject('Part::Feature',"topTraks").Shape=s
        topTracks.Label = "topTracks"
        topTracks.Placement = FreeCAD.Placement(
            FreeCAD.Vector(0, 0, deltaz),
            FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0))
        #if hasattr(doc.Pcb, 'Shape'):
        if len(doc.getObjectsByLabel('Pcb')) > 0:
            topTracks.Placement = doc.getObjectsByLabel('Pcb')[0].Placement
            topTracks.Placement.Base.z += deltaz
            if len(doc.getObjectsByLabel('Board_Geoms')) > 0:
                if use_AppPart and not use_LinkGroups:
                    doc.getObject('Board_Geoms').addObject(topTracks)
                elif use_LinkGroups:
                    doc.getObject('Board_Geoms').ViewObject.dropObject(
                        topTracks, None, '', [])
        #topTracks.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0.05),FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0))
        ##docG.getObject(topTracks.Name).Transparency=40
        if 0:
            docG.getObject(topTracks.Name).ShapeColor = (0.78, 0.46, 0.20)
        FreeCADGui.Selection.clearSelection()
        FreeCADGui.Selection.addSelection(doc.getObject(composed.Name))
        #stop
        removesubtree(FreeCADGui.Selection.getSelection())
        say_time()
        #except Exception as e:
        #    exc_type, exc_obj, exc_tb = sys.exc_info()
        #    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        #    FreeCAD.Console.PrintError('error class: '+str(exc_type)+'\nfile name: '+str(fname)+'\nerror @line: '+str(exc_tb.tb_lineno)+'\nerror value: '+str(e.args[0])+'\n')

        #try:    #doing bot tracks layer
        #pcb.setLayer(LvlBotName)
        pcb.setLayer(Bot_lvl)
        pcb.makeCopper(holes=True, minSize=minSizeDrill)
        composed = doc.ActiveObject
        s = composed.Shape
        doc.addObject('Part::Feature', 'botTracks').Shape = composed.Shape
        botTracks = doc.ActiveObject
        #print (doc.ActiveObject.Label)
        #print (topTracks.Label)
        docG.ActiveObject.ShapeColor = docG.getObject(composed.Name).ShapeColor
        docG.ActiveObject.LineColor = docG.getObject(composed.Name).LineColor
        docG.ActiveObject.PointColor = docG.getObject(composed.Name).PointColor
        docG.ActiveObject.DiffuseColor = docG.getObject(
            composed.Name).DiffuseColor
        #doc.recompute()
        #doc.addObject('Part::Feature',"topTraks").Shape=s
        botTracks.Label = "botTracks"
        botTracks.Placement = FreeCAD.Placement(
            FreeCAD.Vector(0, 0, -1.6 - deltaz),
            FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0))
        #if hasattr(doc.Pcb, 'Shape'):
        ##docG.getObject(botTracks.Name).Transparency=40
        if 0:
            docG.getObject(botTracks.Name).ShapeColor = (0.78, 0.46, 0.20)
        FreeCADGui.Selection.clearSelection()
        FreeCADGui.Selection.addSelection(doc.getObject(composed.Name))

        removesubtree(FreeCADGui.Selection.getSelection())
        #if hasattr(doc.Pcb, 'Shape'):
        if len(doc.getObjectsByLabel('Pcb')) > 0:
            botTracks.Placement = doc.getObjectsByLabel('Pcb')[0].Placement
            #botTracks.Placement = doc.Pcb.Placement
            botTracks.Placement.Base.z -= pcbThickness + deltaz
            if len(doc.getObjectsByLabel('Board_Geoms')) > 0:
                if use_AppPart and not use_LinkGroups:
                    doc.getObject('Board_Geoms').addObject(botTracks)
                elif use_LinkGroups:
                    doc.getObject('Board_Geoms').ViewObject.dropObject(
                        botTracks, None, '', [])
        #botTracks = FreeCAD.ActiveDocument.ActiveObject
        #botTracks.Label="botTracks"
        #botTracks.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,-1.6),FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0))
        #docG.ActiveObject.Transparency=40
        #except Exception as e:
        #    exc_type, exc_obj, exc_tb = sys.exc_info()
        #    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        #    FreeCAD.Console.PrintError('error class: '+str(exc_type)+'\nfile name: '+str(fname)+'\nerror @line: '+str(exc_tb.tb_lineno)+'\nerror value: '+str(e.args[0])+'\n')
        say_time()

        FreeCADGui.SendMsgToActiveView("ViewFit")
        docG.activeView().viewAxonometric()
Beispiel #10
0
def export_one_part(modul, variant, with_plug=False):
    if not variant in modul.all_params:
        FreeCAD.Console.PrintMessage("Parameters for %s doesn't exist in 'M.all_params', skipping." % variant)
        return

    destination_dir="Connectors_Phoenix.3dshapes"
    if with_plug:
        destination_dir="Connectors_Phoenix__with_plug.3dshapes"
    ModelName = variant
    ModelName = ModelName.replace(".","_")
    FileName = modul.all_params[variant].file_name
    Newdoc = FreeCAD.newDocument(ModelName)
    App.setActiveDocument(ModelName)
    App.ActiveDocument=App.getDocument(ModelName)
    Gui.ActiveDocument=Gui.getDocument(ModelName)
    #App.setActiveDocument(ModelName)
    #Gui.ActiveDocument=Gui.getDocument(ModelName)
    (pins, body, insert, mount_screw, plug, plug_screws) = modul.generate_part(variant, with_plug)

    color_attr = body_color + (0,)
    show(body, color_attr)

    color_attr = pins_color + (0,)
    show(pins, color_attr)

    if insert is not None:
        color_attr = insert_color + (0,)
        show(insert, color_attr)
    if mount_screw is not None:
        color_attr = screw_color + (0,)
        show(mount_screw, color_attr)
    if plug is not None:
        color_attr = body_color + (0,)
        show(plug, color_attr)

        color_attr = screw_color + (0,)
        show(plug_screws, color_attr)

    doc = FreeCAD.ActiveDocument
    doc.Label=ModelName
    objs=FreeCAD.ActiveDocument.Objects
    FreeCAD.Console.PrintMessage(objs)

    i=0
    objs[i].Label = ModelName + "__body"
    i+=1
    objs[i].Label = ModelName + "__pins"
    i+=1
    if insert is not None:
        objs[i].Label = ModelName + "__thread_insert"
        i+=1
    if mount_screw is not None:
        objs[i].Label = ModelName + "__mount_screw"
        i+=1
    if plug is not None:
        objs[i].Label = ModelName + "__plug"
        i+=1
        objs[i].Label = ModelName + "__plug_screws"
    restore_Main_Tools()

    out_dir=destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    used_color_keys = [body_color_key, pins_color_key]
    export_file_name=destination_dir+os.sep+FileName+'.wrl'

    export_objects = []
    i=0
    export_objects.append(expVRML.exportObject(freecad_object = objs[i],
            shape_color=body_color_key,
            face_colors=None))
    i+=1
    export_objects.append(expVRML.exportObject(freecad_object = objs[i],
            shape_color=pins_color_key,
            face_colors=None))
    i+=1
    if insert is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=insert_color_key,
                face_colors=None))
        used_color_keys.append(insert_color_key)
        i+=1
    if mount_screw is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=screw_color_key,
                face_colors=None))
        used_color_keys.append(screw_color_key)
        i+=1
    if plug is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=body_color_key,
                face_colors=None))
        i+=1
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=screw_color_key,
                face_colors=None))
    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)

    fusion = multiFuseObjs_wColors(FreeCAD, FreeCADGui,
                     ModelName, objs, keepOriginals=True)

    exportSTEP(doc,FileName,out_dir,fusion)
    L.addLicenseToStep(out_dir+'/', FileName+".step", LIST_license,\
        STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licPreProc)

    saveFCdoc(App, Gui, doc, FileName,out_dir)

    FreeCAD.activeDocument().recompute()
    # FreeCADGui.activateWorkbench("PartWorkbench")
    FreeCADGui.SendMsgToActiveView("ViewFit")
    FreeCADGui.activeDocument().activeView().viewAxometric()
Beispiel #11
0
"""
        return {"vertices": vertices, "edges": edges, "faces": faces}


if __name__ == "__main__":
    mesh_values = read_geom(
        "/home/cyril/git/pythoncvc.net/IfcOpenShellSamples/Wall.ifc")

    # Create a FreeCAD geometry. A FreeCAD can take vertices and faces as input
    mesh = Mesh.Mesh((mesh_values["vertices"], mesh_values["faces"]))
    # Ifc lenght internal unit : meter. FreeCAD internal unit : mm.
    scale_factor = 1000
    matrix = FreeCAD.Matrix()
    matrix.scale(scale_factor, scale_factor, scale_factor)
    mesh.transform(matrix)

    # Allow you to embed FreeCAD in python https://www.freecadweb.org/wiki/Embedding_FreeCAD
    FreeCADGui.showMainWindow()
    doc = FreeCAD.newDocument()

    # Add geometry to FreeCAD scenegraph (Coin)
    fc_mesh = doc.addObject("Mesh::Feature", "IfcMesh")
    fc_mesh.Mesh = mesh

    # Set Draw Style to display mesh edges. Orient view and fit to wall
    FreeCADGui.runCommand("Std_DrawStyle", 1)
    FreeCADGui.Selection.addSelection(fc_mesh)
    FreeCADGui.activeView().viewIsometric()
    FreeCADGui.SendMsgToActiveView("ViewSelection")

    FreeCADGui.exec_loop()
    def Activated(self):
        import ObjectsFem
        isMystran = 1

        ininame = "Mod/hfcMystran/hfcMystran.ini"

        inifile = FreeCAD.getHomePath() + ininame
        if os.path.exists(inifile):
            iniF = open(inifile, "r")
            path = iniF.readline()
            iniF.close()
        else:
            path = FreeCAD.getHomePath()

        try:
            fName = QFileDialog.getOpenFileName(
                None, QString.fromLocal8Bit("Read a Mystarn's Dat/bdf file"),
                path, "*.Dat *.bdf")  # PyQt4
        except Exception:
            fName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(
                None, "Read a Mystran's Dat/bdf file", path,
                "*.Dat *.bdf")  #PySide

        print("src: " + fName)
        DesName = FreeCAD.getHomePath() + "bin/hfcMystran.Dat"
        print("Des: " + DesName)
        shutil.copyfile(fName, DesName)

        data = fName.split("/")
        n = len(data)
        path = ""
        for i in range(n - 1):
            path = path + data[i] + "/"

        inifileOut = FreeCAD.getHomePath() + ininame
        iniFout = open(inifileOut, "w")
        iniFout.writelines(path)
        iniFout.close()

        #print (path)
        iHfc = FreeCAD.ActiveDocument.getObject('hfc')
        if iHfc == None:
            iHfc = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                    'hfc')
            hfc(iHfc)
            #iHfc.ViewObject.Proxy=0
            #ViewProviderCFG(iHfc.ViewObject)

        iHfc.DatPath = path
        iHfc.DatFile = fName

        numNode = 0
        numMember = 0

        nodes_x = []
        nodes_y = []
        nodes_z = []

        NodeList = {}
        MemberList = {}

        DisplacementList = {}

        NodeEndList = {}
        MemberEndList = {}

        ProjectDescription = ''

        nodes = {}
        results = []
        mode_results = {}
        mode_disp = {}
        iFilled = []

        mode_disp_x = []
        mode_disp_y = []
        mode_disp_z = []

        nDisp = 0
        mDisp = 0
        isDebug = 1

        #factor = 25.42
        factor = 1

        factorZoom = 100

        #000000000000000000000000000000000000000000000000000000000000000000

        fpDat = open(fName)
        tline = []
        for line in fpDat:
            aline = line.strip()
            if len(aline) == 0 or aline[0] == '$':
                continue
            else:
                tline.append(line.strip())
        fpDat.close()

        for id in range(len(tline)):

            aline = tline[id].strip()
            data = aline.split()
            data1 = aline.split(",")
            #print (data)

            # Node 22222222222222222222222222222222222222222222222222222222222222222222
            if data[0] == 'GRID':
                #           gid         cp  x1
                #GRID       10101       0   0.000   0.000   0.000       0
                gid = aline[8:16].strip()
                #cid1=aline[16:24].strip()
                x = aline[24:32].strip()
                y = aline[32:40].strip()
                z = aline[40:48].strip()

                NodeList[gid] = Node(gid, float(x), float(y), float(z))
                numNode = numNode + 1

            if data[0] == 'GRID*':
                #GRID*    1                               0.00000E+00     0.00000E+00
                gid = aline[8:24].strip()
                #cid1=aline[24:40].strip()
                x = aline[40:56].strip()
                y = aline[56:72].strip()
                bline = tline[id + 1].strip()
                z = bline[8:24].strip()
                NodeList[gid] = Node(gid, float(x), float(y), float(z))
                numNode = numNode + 1

            # Member 33333333333333333333333333333333333333333333333333333333333333333333333333333333333333
            #CBAR    201     2       11      21      0.0     0.0     1.0
            if data[0] == 'CBAR':
                MemberList[data[1].strip()] = MemberCBAR(
                    data[1].strip(), data[3], data[4], data[0].strip())
                numMember += 1

#CBEAM   9400    9401    9401    9402    0.      0.      1.
            if data[0] == 'CBEAM':
                MemberList[data[1].strip()] = MemberCBEAM(
                    data[1].strip(), data[3], data[4], data[0].strip())
                numMember += 1

#CROD, 418,418,8,3
            if data[0] == 'CROD':
                MemberList[data[1].strip()] = MemberCROD(
                    data[1].strip(), data[3], data[4], data[0].strip())
                numMember += 1

#CROD, 418,418,8,3
            if data1[0] == 'CROD':
                MemberList[data1[1].strip()] = MemberCROD(
                    data1[1].strip(), data1[3], data1[4], data1[0].strip())
                numMember += 1

#CTRIA3  24      91      1033    1032    1023
            if data[0] == 'CTRIA3':
                MemberList[data[1].strip()] = MemberCTRIA3(
                    data[1].strip(), data[3], data[4], data[5],
                    data[0].strip())
                numMember += 1

            #CQUAD4      1001       1    1001    1002    2002    2001
            if data[0] == 'CQUAD4':
                MemberList[data[1].strip()] = MemberCQUAD4(
                    data[1].strip(), data[3], data[4], data[5], data[6],
                    data[0].strip())
                numMember += 1

            #CQUAD8     16004       1   16007   16009   18009   18007   16008   17009
            #18008   17007
            if data[0] == 'CQUAD8':
                MemberList[data[1].strip()] = MemberCQUAD8(
                    data[1].strip(), data[3], data[4], data[5], data[6],
                    data[0].strip())
                numMember += 1

            #CTETRA   1       1       8       13      67      33
            if data[0] == 'CTETRA':
                MemberList[data[1].strip()] = MemberCQUAD4(
                    data[1].strip(), data[3], data[4], data[5], data[6],
                    data[0].strip())
                numMember += 1

            #
            #CHEXA      10101     100   10101   10103   10303   10301   30101   30103+E     1
            #+E     1   30303   30301
            if data[0] == 'CHEXA':
                bline = tline[id + 1].strip()
                if len(aline) == 80:
                    eid = aline[9:16].strip()
                    pid = aline[17:24].strip()
                    g1 = aline[25:32].strip()
                    g2 = aline[33:40].strip()
                    g3 = aline[41:48].strip()
                    g4 = aline[49:56].strip()
                    g5 = aline[57:64].strip()
                    g6 = aline[65:72].strip()
                if aline[73:80] == bline[1:8]:
                    g7 = bline[9:16].strip()
                    g8 = bline[17:24].strip()

                #print (eid+" "+g1+" "+g2+" "+g3+" "+g4+" "+g5+" "+g6+" "+g7+" "+g8)
                MemberList[eid] = MemberCHEXA(eid, g1, g2, g3, g4, g5, g6, g7,
                                              g8, data[0].strip())
                numMember += 1

        #print (NodeList)
        #print (MemberList)

        print('numNode = ' + str(numNode))
        print('numMember = ' + str(numMember))

        #for id in NodeList:
        #	print (NodeList[id].id+" "+str(NodeList[id].x)+" "+str(NodeList[id].y)+" "+str(NodeList[id].z))

        femmesh = Fem.FemMesh()
        # nodes
        #print ("Add nodes")
        for id in NodeList:  # node
            #femmesh.addNode(NodeList[id].x,NodeList[id].y,NodeList[id].z, int(id)+1 )
            femmesh.addNode(NodeList[id].x, NodeList[id].y, NodeList[id].z,
                            int(id))

        for id in MemberList:

            mtype = MemberList[id].mtype

            if mtype == 'CROD':

                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                femmesh.addEdge([n1, n2])

            elif mtype == 'CBAR':

                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                femmesh.addEdge([n1, n2])

            elif mtype == 'CBEAM':

                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                femmesh.addEdge([n1, n2])

            elif mtype == 'CTRIA3':
                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                n3 = int(MemberList[id].n3)

                femmesh.addEdge([n1, n2])
                femmesh.addEdge([n2, n3])
                femmesh.addEdge([n3, n1])

                #femmesh.addFace([n1,n2,n3])

            elif mtype == 'CQUAD4':
                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                n3 = int(MemberList[id].n3)
                n4 = int(MemberList[id].n4)

                #print (str(n1)+" "+str(n2)+" "+str(n3)+" "+str(n4))

                femmesh.addEdge([n1, n2])
                femmesh.addEdge([n2, n3])
                femmesh.addEdge([n3, n4])
                femmesh.addEdge([n4, n1])

                #femmesh.addFace([n1,n2,n3,n4])

            elif mtype == 'CQUAD8':
                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                n3 = int(MemberList[id].n3)
                n4 = int(MemberList[id].n4)

                femmesh.addEdge([n1, n2])
                femmesh.addEdge([n2, n3])
                femmesh.addEdge([n3, n4])
                femmesh.addEdge([n4, n1])

                #femmesh.addFace([n1,n2,n3,n4])

            elif mtype == 'CTETRA':
                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                n3 = int(MemberList[id].n3)
                n4 = int(MemberList[id].n4)

                femmesh.addEdge([n1, n2])
                femmesh.addEdge([n2, n3])
                femmesh.addEdge([n3, n4])
                femmesh.addEdge([n4, n1])

                #femmesh.addVolume([n1,n2,n3,n4])

            elif mtype == 'CHEXA':
                n1 = int(MemberList[id].n1)
                n2 = int(MemberList[id].n2)
                n3 = int(MemberList[id].n3)
                n4 = int(MemberList[id].n4)

                n5 = int(MemberList[id].n5)
                n6 = int(MemberList[id].n6)
                n7 = int(MemberList[id].n7)
                n8 = int(MemberList[id].n8)

                femmesh.addEdge([n1, n2])
                femmesh.addEdge([n2, n3])
                femmesh.addEdge([n3, n4])
                femmesh.addEdge([n4, n1])

                femmesh.addEdge([n5, n6])
                femmesh.addEdge([n6, n7])
                femmesh.addEdge([n7, n8])
                femmesh.addEdge([n8, n5])

                femmesh.addEdge([n1, n5])
                femmesh.addEdge([n2, n6])
                femmesh.addEdge([n3, n7])
                femmesh.addEdge([n4, n8])

                #femmesh.addVolume([n1,n2,n3,n4,n5,n6,n7,n8])

            else:
                print(mtype + ' Not supported yet')

        result_mesh_object = None
        result_mesh_object = ObjectsFem.makeMeshResult(FreeCAD.ActiveDocument,
                                                       "hfcMesh")
        result_mesh_object.FemMesh = femmesh

        FreeCAD.ActiveDocument.recompute()
        FreeCADGui.activeDocument().activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

        print('Input done.')
        print('')
def generateOneModel(params, log):
    ModelName = params.modelName
    FreeCAD.Console.PrintMessage('\n\n##############  ' +
                                 part_params['code_metric'] +
                                 '  ###############\n')
    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)
    #body, base, mark, pins = make_tantalum_th(params)
    body, pins, pinmark = make_tantalum_th(
        params)  #body, base, mark, pins, top

    show(body)
    show(pins)
    show(pinmark)

    doc = FreeCAD.ActiveDocument
    print(GetListOfObjects(FreeCAD, doc))
    objs = GetListOfObjects(FreeCAD, doc)

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], pins_color)
    Color_Objects(Gui, objs[2], marking_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    col_mark = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]

    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_pin[:-1]: pins_color_key,
        col_mark[:-1]: marking_color_key
    }
    expVRML.say(material_substitutions)
    del objs

    objs = GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
    objs = GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
    #stop
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()
    #rotate if required
    objs = GetListOfObjects(FreeCAD, doc)
    FreeCAD.getDocument(doc.Name).getObject(
        objs[0].Name).Placement = FreeCAD.Placement(
            FreeCAD.Vector(params.F / 2, 0, 0),
            FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), params.rotation))
    #out_dir=destination_dir+params.dest_dir_prefix+'/'
    script_dir = os.path.dirname(os.path.realpath(__file__))

    expVRML.say(script_dir)
    #out_dir=script_dir+os.sep+destination_dir+os.sep+params.dest_dir_prefix

    out_dir = models_dir + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    #out_dir="./generated_qfp/"
    # export STEP model

    exportSTEP(doc, ModelName, out_dir)

    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)

    if save_memory == False:
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()

    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, ModelName, out_dir)
    if save_memory == True:
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
Beispiel #14
0
def make_3D_model(models_dir, variant):

    LIST_license = [
        "",
    ]
    modelName = all_params[variant].modelName

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedmodelName)

    case = make_case(all_params[variant])
    casetop = make_case_top(all_params[variant])
    pins = make_pins(all_params[variant])

    show(case)
    show(casetop)
    show(pins)
    #show(pinmark)
    #stop
    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    body_color_key = all_params[variant].body_color_key
    body_top_color_key = all_params[variant].body_top_color_key
    pin_color_key = all_params[variant].pin_color_key

    body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat()
    body_top_color = shaderColors.named_colors[
        body_top_color_key].getDiffuseFloat()
    pin_color = shaderColors.named_colors[pin_color_key].getDiffuseFloat()

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], body_top_color)
    Color_Objects(Gui, objs[2], pin_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_body_top = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]

    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_body_top[:-1]: body_top_color_key,
        col_pin[:-1]: pin_color_key
    }

    expVRML.say(material_substitutions)
    while len(objs) > 1:
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
    doc.Label = CheckedmodelName

    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir = models_dir + os.sep + all_params[variant].dest_dir_prefix

    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    step_path = '{dir:s}/{name:s}.step'.format(dir=out_dir, name=modelName)
    exportSTEP(doc, modelName, out_dir)

    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")

    Lic.addLicenseToStep(out_dir, '{:s}.step'.format(modelName), LIST_license,
                         cq_parameters.LICENCE_Info.STR_licAuthor,
                         cq_parameters.LICENCE_Info.STR_licEmail,
                         cq_parameters.LICENCE_Info.STR_licOrgSys,
                         cq_parameters.LICENCE_Info.STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    # expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)

    # Save the doc in Native FC format
    doc.recompute()
    saveFCdoc(App, Gui, doc, modelName, out_dir)

    #FreeCADGui.activateWorkbench("PartWorkbench")
    if save_memory == False and check_Model == False:
        FreeCADGui.SendMsgToActiveView("ViewFit")
        FreeCADGui.activeDocument().activeView().viewAxometric()

    if save_memory == True or check_Model == True:
        FreeCAD.closeDocument(doc.Name)
        os.remove(out_dir + os.sep + modelName + '.FCStd')

    if check_Model == True:
        with open(out_dir + os.sep + check_log_file, 'a+') as log:
            log.write('# Check report for Molex 3d model genration\n')
            runGeometryCheck(App,
                             Gui,
                             step_path,
                             log,
                             modelName,
                             save_memory=save_memory)
            log.close()
Beispiel #15
0
def draw_S800():
    sweep_offset = 210
    wing_span = 820
    midWidth = 150
    midLength = 200

    WingInside_height_top = 25
    WingInside_height_bot = 5
    WingInside_length = 260

    WingOutside_height_top = 20
    WingOutside_height_bot = 3
    WingOutside_length = 165

    Middle_height_top = 40
    Middle_height_bot = 20
    Middle_length = WingInside_length

    WingletTop_height_top = 3
    WingletTop_height_bot = 3
    Winglet_angle_y = 10
    WingletBottom_height_top = WingletTop_height_top
    WingletBottom_height_bot = WingletTop_height_bot
    WingletBottom_length = WingOutside_length

    ElevonThickness = 1
    ElevonLeftAngle = 20
    ElevonRightAngle = -20

    if FreeCAD.ActiveDocument is not None and FreeCAD.ActiveDocument.Name == "S800":
        FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name)
        FreeCAD.setActiveDocument("")
        FreeCAD.ActiveDocument = None

    doc = FreeCAD.newDocument('S800')

    SplineFoilWingInside = doc.addObject('Sketcher::SketchObject',
                                         'SplineFoilWingInside')
    makeSplineFoilSketch(SplineFoilWingInside, WingInside_length,
                         WingInside_height_top, WingInside_height_bot,
                         ElevonThickness)
    SplineFoilWingInside.ViewObject.Visibility = False
    SplineFoilWingInside.Placement = Placement(Vector(midWidth / 2, 0.0, 1.0),
                                               Rotation(0.5, 0.5, 0.5, 0.5))
    SplineFoilWingInside.ViewObject.Visibility = False

    SplineFoilWingOutside = doc.addObject('Sketcher::SketchObject',
                                          'SplineFoilWingOutside')
    makeSplineFoilSketch(SplineFoilWingOutside, WingOutside_length,
                         WingOutside_height_top, WingOutside_height_bot,
                         ElevonThickness)
    SplineFoilWingOutside.ViewObject.Visibility = False
    SplineFoilWingOutside.Placement = Placement(
        Vector(wing_span / 2, sweep_offset, 1.0), Rotation(0.5, 0.5, 0.5, 0.5))
    SplineFoilWingOutside.ViewObject.Visibility = False

    SplineFoilWingletBottom = doc.addObject('Sketcher::SketchObject',
                                            'SplineFoilWingletBottom')
    makeSplineFoilSketch(SplineFoilWingletBottom, WingletBottom_length,
                         WingletBottom_height_top, WingletBottom_height_bot,
                         0.5)
    SplineFoilWingletBottom.ViewObject.Visibility = False
    SplineFoilWingletBottom.Placement.Rotation.Axis = Vector(0.0, 0.0, 0.1)
    SplineFoilWingletBottom.Placement.Rotation.Angle = math.radians(90)
    SplineFoilWingletBottom.Placement.Base.y = sweep_offset
    SplineFoilWingletBottom.Placement.Base.x = wing_span / 2 + WingletTop_height_bot * 1.5
    SplineFoilWingletBottom.Placement.Base.z = WingOutside_height_top
    SplineFoilWingletBottom.ViewObject.Visibility = False

    doc.recompute()
    Draft.rotate([SplineFoilWingletBottom],
                 Winglet_angle_y,
                 SplineFoilWingletBottom.Placement.Base,
                 Vector(0, 1, 0),
                 copy=False)
    doc.recompute()

    SplineFoilMiddle = doc.addObject('Sketcher::SketchObject',
                                     'SplineFoilMiddle')
    makeSplineFoilSketch(SplineFoilMiddle, Middle_length, Middle_height_top,
                         Middle_height_bot, ElevonThickness)
    SplineFoilMiddle.Placement = Placement(Vector(0.0, 0.0, 0.0),
                                           Rotation(0.5, 0.5, 0.5, 0.5))
    SplineFoilMiddle.ViewObject.Visibility = False

    MiddleProfile = createSketch_MiddleProfile(doc)
    MiddleProfile.ViewObject.Visibility = False

    MiddlePart1 = CurvedShapes.makeCurvedSegment(SplineFoilMiddle,
                                                 SplineFoilWingInside,
                                                 [MiddleProfile],
                                                 Items=4,
                                                 Surface=True,
                                                 Solid=True,
                                                 Distribution='elliptic',
                                                 DistributionReverse=True)
    MiddlePart1.Label = "MiddlePart1"
    MiddlePart1.ViewObject.Visibility = False

    MainWing = doc.addObject('Part::Loft', 'MainWing')
    MainWing.Sections = [SplineFoilWingInside, SplineFoilWingOutside]
    MainWing.Solid = True

    WingToWinglet = CurvedShapes.makeInterpolatedMiddle(
        SplineFoilWingOutside,
        SplineFoilWingletBottom,
        Surface=True,
        Solid=True)
    WingToWinglet.Label = "WingToWinglet"

    WingletProfile = makeWingletProfile(doc)
    WingletProfile.ViewObject.Visibility = False

    doc.recompute()
    Winglet = CurvedShapes.makeCurvedArray(SplineFoilWingletBottom,
                                           [WingletProfile],
                                           Items=8,
                                           OffsetStart=0.01,
                                           OffsetEnd=0.01,
                                           Surface=True,
                                           Solid=True)
    Winglet.Label = "Winget"

    doc.recompute()
    Draft.rotate([Winglet],
                 Winglet_angle_y,
                 SplineFoilWingletBottom.Placement.Base,
                 Vector(0, 1, 0),
                 copy=False)
    doc.recompute()

    sketchCutout = doc.addObject('Sketcher::SketchObject', 'sketchCutout')
    sketchCutout.addGeometry(
        Part.LineSegment(Vector(0.0, 400.0, 0.0),
                         Vector(274.99999999950205, 400.0, 0.0)), False)
    sketchCutout.addGeometry(
        Part.LineSegment(Vector(274.99999999950205, 400.0, 0.0),
                         Vector(75.0, 200.0, 0.0)), False)
    sketchCutout.addGeometry(
        Part.LineSegment(Vector(75.0, 200.0, 0.0), Vector(0.0, 200.0, 0.0)),
        False)
    sketchCutout.addGeometry(
        Part.LineSegment(Vector(0.0, 200.0, 0.0), Vector(0.0, 400.0, 0.0)),
        False)
    sketchCutout.addConstraint(Sketcher.Constraint('PointOnObject', 0, 1, -2))
    sketchCutout.addConstraint(Sketcher.Constraint('Horizontal', 0))
    sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 0, 2, 1, 1))
    sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 1, 2, 2, 1))
    sketchCutout.addConstraint(Sketcher.Constraint('PointOnObject', 2, 2, -2))
    sketchCutout.addConstraint(Sketcher.Constraint('Horizontal', 2))
    sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 2, 2, 3, 1))
    sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 3, 2, 0, 1))
    sketchCutout.addConstraint(
        Sketcher.Constraint('Angle', 1, 2, 2, 1, 2.356194))
    sketchCutout.addConstraint(
        Sketcher.Constraint('DistanceX', 2, 2, 2, 1, midWidth / 2))
    sketchCutout.addConstraint(
        Sketcher.Constraint('DistanceY', 2, 2, midLength))
    sketchCutout.addConstraint(
        Sketcher.Constraint('DistanceY', 3, 1, 3, 2, midLength))
    sketchCutout.ViewObject.Visibility = False

    cutout = doc.addObject('Part::Extrusion', 'cutout')
    cutout.Base = sketchCutout
    cutout.DirMode = "Normal"
    cutout.LengthFwd = 100.0
    cutout.LengthRev = 100.0
    cutout.Solid = True
    cutout.Symmetric = True
    cutout.ViewObject.Visibility = False

    MiddlePart = doc.addObject('Part::Cut', 'MiddlePart')
    MiddlePart.Base = MiddlePart1
    MiddlePart.Tool = cutout

    cutpathPoints = [Vector(midWidth / 2, midLength, -WingInside_height_bot)]
    cutpathPoints.append(
        Vector(
            wing_span / 2,
            midLength + sweep_offset - WingInside_length + WingOutside_length,
            -WingOutside_height_bot))
    cutpath = Draft.makeWire(cutpathPoints)
    cutpath.ViewObject.Visibility = False
    cutExtrude = doc.addObject('Part::Extrusion', 'cutExtrude')
    cutExtrude.Base = cutpath
    cutExtrude.DirMode = "Normal"
    cutExtrude.LengthFwd = WingInside_height_bot + WingInside_height_top

    doc.recompute()

    Wing = doc.addObject('Part::Cut', 'Wing')
    Wing.Base = MainWing
    Wing.Tool = cutout

    doc.recompute()

    WingSlice = BOPTools.SplitFeatures.makeSlice(name='WingSlice')
    WingSlice.Base = [Wing, cutExtrude][0]
    WingSlice.Tools = [Wing, cutExtrude][1:]
    WingSlice.Mode = 'Split'
    WingSlice.Proxy.execute(WingSlice)
    WingSlice.purgeTouched()
    WingSlice.ViewObject.Visibility = False
    for obj in WingSlice.ViewObject.Proxy.claimChildren():
        obj.ViewObject.hide()

    WingAndElevon = CompoundTools.Explode.explodeCompound(WingSlice)
    Wing1 = WingAndElevon[0].Group[0]
    Wing1.Label = "Wing1"
    ElevonLeft = WingAndElevon[0].Group[1]
    ElevonLeft.Label = "ElevonLeft"

    HalfWing = doc.addObject('Part::Compound', 'HalfWing')
    HalfWing.Links = [MiddlePart, Wing1, WingToWinglet, Winglet]

    FullWing = doc.addObject('Part::Mirroring', 'FullWing')
    FullWing.Normal = Vector(1.0, 0.0, 0.0)
    FullWing.Source = HalfWing

    ElevonRight1 = Draft.clone(ElevonLeft)
    ElevonRight1.ViewObject.Visibility = False

    ElevonRight = doc.addObject('Part::Mirroring', 'ElevonRight')
    ElevonRight.Normal = Vector(1.0, 0.0, 0.0)
    ElevonRight.Source = ElevonRight1

    doc.recompute()
    axis = cutpathPoints[1].sub(cutpathPoints[0])
    center = ElevonLeft.Placement.Base.add(
        Vector(midWidth / 2, midLength, ElevonLeft.Shape.BoundBox.ZMax))
    Draft.rotate([ElevonLeft], ElevonLeftAngle, center, axis=axis, copy=False)
    Draft.rotate([ElevonRight1],
                 ElevonRightAngle,
                 center,
                 axis=axis,
                 copy=False)

    FreeCADGui.activeDocument().activeView().viewIsometric()
    FreeCADGui.SendMsgToActiveView("ViewFit")
    return
Beispiel #16
0
def draw_HortenHIX():
    rib_material_height = 33.0

    length = 500
    scaleFactor = 1  #length / 85

    if FreeCAD.ActiveDocument is not None and FreeCAD.ActiveDocument.Name == "Horten_HIX":
        FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name)
        FreeCAD.setActiveDocument("")
        ActiveDocument = None
        FreeCAD.ActiveDocument = None

    doc = FreeCAD.newDocument('Horten_HIX')

    wing_sweep = 32.2
    twist = 3
    wing_ribs = 10
    front_part_fraction = 0.97

    WingTop_parts = []
    line = Draft.makeWire([
        Vector(0.0, 73.39, 0.0) * scaleFactor,
        Vector(72.64, 27.65, 0.0) * scaleFactor
    ])
    WingTop_parts.append(line)
    line = Draft.makeWire([
        Vector(75.22, 11.01, 0.0) * scaleFactor,
        Vector(35.0, 22.43, 0.0) * scaleFactor
    ])
    WingTop_parts.append(line)
    poles = []
    poles.append(Vector(72.64, 27.65, 0.0) * scaleFactor)
    poles.append(Vector(86.21, 19.11, 0.0) * scaleFactor)
    poles.append(Vector(86.21, 7.88, 0.0) * scaleFactor)
    poles.append(Vector(75.22, 11.01, 0.0) * scaleFactor)
    weights = [1.0, 1.0, 1.0, 1.0]
    knots = [0.0, 1.0]
    mults = [4, 4]
    bspline = Part.BSplineCurve()
    bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights,
                                     False)
    bezier = doc.addObject('Part::Spline', 'BSplineCurve')
    bezier.Shape = bspline.toShape()
    WingTop_parts.append(bezier)
    poles = []
    poles.append(Vector(0.0, 0.0, 0.0) * scaleFactor)
    poles.append(Vector(15.13, 28.07, 0.0) * scaleFactor)
    poles.append(Vector(35.0, 22.43, 0.0) * scaleFactor)
    weights = [1.0, 1.0, 1.0]
    knots = [0.0, 1.0]
    mults = [3, 3]
    bspline = Part.BSplineCurve()
    bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 2, weights,
                                     False)
    bezier = doc.addObject('Part::Spline', 'BSplineCurve')
    bezier.Shape = bspline.toShape()
    WingTop_parts.append(bezier)
    WingTop = doc.addObject('Part::Compound', 'WingTop')
    WingTop.Links = WingTop_parts
    WingTop.Placement.Base = Vector(0.0, 0.0, 0.0) * scaleFactor
    WingTop.Placement.Rotation = Rotation(0.0, 0.0, 0.0, 1.0)
    WingTop.ViewObject.LineColor = (1.0, 0.0, 0.0, 0.0)
    WingTop.ViewObject.LineColorArray = [(1.0, 0.0, 0.0, 0.0)]

    WingFront_parts = []
    line = Draft.makeWire([
        Vector(0.0, -4.31, 0.0) * scaleFactor,
        Vector(77.02, 2.59, 0.0) * scaleFactor
    ])
    WingFront_parts.append(line)
    poles = []
    poles.append(Vector(0.0, 7.35, 0.0) * scaleFactor)
    poles.append(Vector(5.43, 4.71, 0.0) * scaleFactor)
    poles.append(Vector(16.41, 2.6, 0.0) * scaleFactor)
    poles.append(Vector(41.55, 2.77, 0.0) * scaleFactor)
    poles.append(Vector(76.91, 3.93, 0.0) * scaleFactor)
    poles.append(Vector(83.72, 4.28, 0.0) * scaleFactor)
    poles.append(Vector(83.72, 3.38, 0.0) * scaleFactor)
    poles.append(Vector(77.02, 2.59, 0.0) * scaleFactor)
    weights = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    knots = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
    mults = [4, 1, 1, 1, 1, 4]
    bspline = Part.BSplineCurve()
    bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights,
                                     False)
    bezier = doc.addObject('Part::Spline', 'BSplineCurve')
    bezier.Shape = bspline.toShape()
    WingFront_parts.append(bezier)
    WingFront = doc.addObject('Part::Compound', 'WingFront')
    WingFront.Links = WingFront_parts
    WingFront.Placement.Base = Vector(0.0, 0.0, 0.0) * scaleFactor
    WingFront.Placement.Rotation = Rotation(0.7071067811865475, -0.0, -0.0,
                                            0.7071067811865476)
    WingFront.ViewObject.LineColor = (1.0, 0.0, 0.5, 0.0)
    WingFront.ViewObject.LineColorArray = [(1.0, 0.0, 0.5, 0.0)]

    WingProfile_parts = []
    poles = []
    poles.append(Vector(65.04, 0.0, 0.0) * scaleFactor)
    poles.append(Vector(24.39, -4.45, 0.0) * scaleFactor)
    poles.append(Vector(10.95, -2.98, 0.0) * scaleFactor)
    poles.append(Vector(2.58, -2.28, 0.0) * scaleFactor)
    poles.append(Vector(3.23, 0.0, 0.0) * scaleFactor)
    poles.append(Vector(3.89, 2.3, 0.0) * scaleFactor)
    poles.append(Vector(13.51, 5.94, 0.0) * scaleFactor)
    poles.append(Vector(27.26, 5.54, 0.0) * scaleFactor)
    poles.append(Vector(65.04, 0.0, 0.0) * scaleFactor)
    weights = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    knots = [
        0.0, 0.1666666666666667, 0.3333333333333333, 0.5, 0.6666666666666666,
        0.8333333333333334, 1.0
    ]
    mults = [4, 1, 1, 1, 1, 1, 4]
    bspline = Part.BSplineCurve()
    bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights,
                                     False)
    bezier = doc.addObject('Part::Spline', 'BSplineCurve')
    bezier.Shape = bspline.toShape()
    WingProfile_parts.append(bezier)
    WingProfile = doc.addObject('Part::Compound', 'WingProfile')
    WingProfile.Links = WingProfile_parts
    WingProfile.Placement.Base = Vector(5.0, 73.0, 0.0) * scaleFactor
    WingProfile.Placement.Rotation = Rotation(0.5, -0.5, -0.5, 0.5)
    WingProfile.ViewObject.LineColor = (1.0, 0.33, 0.0, 0.0)
    WingProfile.ViewObject.LineColorArray = [(1.0, 0.33, 0.0, 0.0)]
    # Profiles ^^^

    doc.recompute()

    WingArray = CurvedShapes.makeCurvedArray(Base=WingProfile,
                                             Hullcurves=[WingTop, WingFront],
                                             Axis=Vector(1, 0, 0),
                                             Items=16,
                                             OffsetStart=0,
                                             OffsetEnd=0,
                                             Twist=twist,
                                             Surface=False,
                                             Solid=False,
                                             Distribution='parabolic',
                                             DistributionReverse=True,
                                             extract=False)

    WingTopLeft = doc.addObject('Part::Mirroring', 'WingTopLeft')
    WingTopLeft.Normal = Vector(1.0, 0.0, 0.0)
    WingTopLeft.Source = WingTop
    WingTopLeft.ViewObject.hide()

    WingFrontLeft = doc.addObject('Part::Mirroring', 'WingFrontLeft')
    WingFrontLeft.Normal = Vector(1.0, 0.0, 0.0)
    WingFrontLeft.Source = WingFront
    WingFrontLeft.ViewObject.hide()
    doc.recompute()

    winglength = WingFrontLeft.Shape.BoundBox.XLength
    WingSurface = CurvedShapes.makeCurvedArray(
        Base=WingProfile,
        Hullcurves=[WingTopLeft, WingFrontLeft],
        Axis=Vector(-1, 0, 0),
        Items=32,
        OffsetStart=0,
        OffsetEnd=0,
        Twist=-twist,
        Surface=True,
        Solid=True,
        Distribution='sinusoidal')

    WingSurface.Label = "WingSurface"

    Cockpit = drawCockpit(doc, scaleFactor, WingSurface)

    Turbine = makeTurbine(doc, scaleFactor)
    TurbineCut = makeTurbineCut(doc, scaleFactor)
    doc.recompute()
    Draft.rotate([Turbine, TurbineCut],
                 -6,
                 Vector(0.0, length, 0.0),
                 axis=Vector(1.0, 0.0, 0.0),
                 copy=False)
    Turbine.Placement.Base = Vector(0.0, 0.0, 6.5) * scaleFactor
    TurbineCut.Placement.Base = Vector(0.0, 0.0, 6.5) * scaleFactor
    Wing = doc.addObject('Part::Cut', 'Wing')
    Wing.Base = WingSurface
    Wing.Tool = TurbineCut
    doc.recompute()

    ymax = WingSurface.Shape.BoundBox.YMin + WingSurface.Shape.BoundBox.YLength
    rota = FreeCAD.Rotation(Vector(0, 0, 1), 28)
    vecToWingEnd28 = rota.multVec(Vector(0, 1, 0))
    WingCutFront = CurvedShapes.cutSurfaces([Wing],
                                            Normal=vecToWingEnd28,
                                            Position=Vector(0, ymax * 0.85, 0),
                                            Face=False,
                                            Simplify=0)
    WingCutFront.Label = "WingCutFront"

    rota = FreeCAD.Rotation(Vector(0, 0, 1), 18)
    vecToWingEnd18 = rota.multVec(Vector(0, 1, 0))
    WingCutBack = CurvedShapes.cutSurfaces([Wing],
                                           Normal=vecToWingEnd18,
                                           Position=Vector(0, ymax * 0.55, 0),
                                           Face=False,
                                           Simplify=0)
    WingCutBack.Label = "WingCutBack"

    doc.recompute()
    FreeCADGui.activeDocument().activeView().viewIsometric()
    FreeCADGui.SendMsgToActiveView("ViewFit")
    def toggleMesh(self, checked=False):

        "turns mesh display on/off"

        import FreeCADGui
        import Mesh
        import ifcopenshell
        from ifcopenshell import geom
        if not FreeCAD.ActiveDocument:
            doc = FreeCAD.newDocument()
            FreeCAD.setActiveDocument(doc.Name)
        if FreeCAD.ActiveDocument:
            if checked:
                if self.mesh:
                    self.mesh.ViewObject.show()
                else:
                    try:
                        import importIFCHelper
                        s = importIFCHelper.getScaling(self.ifc)
                    except:
                        import importIFC
                        s = importIFC.getScaling(self.ifc)
                    s *= 1000  # ifcopenshell outputs its meshes in metres
                    trf = None
                    if s != 1:
                        trf = FreeCAD.Matrix()
                        trf.scale(s, s, s)
                    basemesh = Mesh.Mesh()
                    s = geom.settings()
                    s.set(s.USE_WORLD_COORDS, True)
                    for product in self.products:
                        try:
                            m = geom.create_shape(s, product)
                            g = m.geometry
                            v = g.verts
                            f = g.faces
                            verts = [
                                FreeCAD.Vector(v[i:i + 3])
                                for i in range(0, len(v), 3)
                            ]
                            faces = [
                                tuple(f[i:i + 3]) for i in range(0, len(f), 3)
                            ]
                            omesh = Mesh.Mesh((verts, faces))
                            if trf:
                                omesh.transform(trf)
                            self.omeshes[product.id()] = omesh
                            basemesh.addMesh(omesh)
                        except:
                            pass
                    self.mesh = FreeCAD.ActiveDocument.addObject(
                        "Mesh::Feature", "IFCMesh")
                    self.mesh.Mesh = basemesh
                    self.mesh.ViewObject.Transparency = 85
                    FreeCAD.ActiveDocument.recompute()
                    FreeCADGui.Selection.clearSelection()
                    FreeCADGui.Selection.addSelection(self.mesh)
                    FreeCADGui.SendMsgToActiveView("ViewSelection")
            else:
                if self.mesh:
                    self.mesh.ViewObject.hide()
                if self.currentmesh:
                    self.currentmesh.ViewObject.hide()
def MakeHeader(n, model, all_params):
    global formerDOC
    global LIST_license
    ModelName = model.replace('yy', "{n:02}".format(n=n))

    full_path = os.path.realpath(__file__)
    expVRML.say(full_path)
    scriptdir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(scriptdir)
    sub_path = full_path.split(scriptdir)
    expVRML.say(sub_path)
    sub_dir_name = full_path.split(os.sep)[-2]
    expVRML.say(sub_dir_name)
    sub_path = full_path.split(sub_dir_name)[0]
    expVRML.say(sub_path)
    models_dir = sub_path + "_3Dmodels"
    script_dir = os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    expVRML.say(models_dir)
    out_dir = models_dir + all_params[model]['output_directory']
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')

    newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    App.ActiveDocument = App.getDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)

    header_type = all_params[model]['type']
    pitch = all_params[model]['pitch']
    rows = all_params[model]['rows']
    base_width = all_params[model]['base_width']
    base_height = all_params[model]['base_height']
    base_chamfer = all_params[model]['base_chamfer']
    pin_width = all_params[model]['pin_width']
    pin_length_above_base = all_params[model]['pin_length_above_base']

    pin_end_chamfer = all_params[model]['pin_end_chamfer']
    rotation = all_params[model]['rotation']

    if base_chamfer == 'auto':
        base_chamfer = pitch / 10.

    if pin_end_chamfer == 'auto':
        pin_end_chamfer = pin_width / 4.

    if header_type == 'Vertical_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base = make_Vertical_THT_base(n, pitch, rows, base_width, base_height,
                                      base_chamfer)
        pins = make_Vertical_THT_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_below_board, base_height,
                                      pin_width, pin_end_chamfer)
    elif header_type == 'Horizontal_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base_x_offset = all_params[model]['base_x_offset']
        base = make_Horizontal_THT_base(n, pitch, rows, base_width,
                                        base_height, base_x_offset,
                                        base_chamfer)
        pins = make_Horizontal_THT_pins(n, pitch, rows, pin_length_above_base,
                                        pin_length_below_board, base_height,
                                        base_width, pin_width, pin_end_chamfer,
                                        base_x_offset)
    elif header_type == 'Vertical_SMD':
        pin_length_horizontal = all_params[model]['pin_length_horizontal']
        base_z_offset = all_params[model]['base_z_offset']
        if rows == 1:
            pin_1_start = all_params[model]['pin_1_start']
        else:
            pin_1_start = None
        pins = make_Vertical_SMD_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_horizontal, base_height,
                                      base_width, pin_width, pin_end_chamfer,
                                      base_z_offset, pin_1_start)
        base = make_Vertical_SMD_base(n, pitch, base_width, base_height,
                                      base_chamfer, base_z_offset)
    else:
        print 'Header type: '
        print header_type
        print ' is not recognized, please check parameters'
        stop

    show(base)
    show(pins)

    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], pins_color)
    #Color_Objects(Gui,objs[2],marking_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    #col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_pin[:-1]: pins_color_key,
        #col_mark[:-1]:marking_color_key
    }
    expVRML.say(material_substitutions)

    #objs=GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()

    if (rotation != 0):
        z_RotateObject(doc, rotation)

    #out_dir = models_dir+"/generated_pinheaders"

    doc.Label = CheckedModelName

    #save the STEP file
    exportSTEP(doc, ModelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)

    #save the VRML file
    #scale=0.3937001
    #exportVRML(doc,name,scale,out_dir)

    if save_memory == False:
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()

    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, ModelName, out_dir, False)

    check_Model = True
    if save_memory == True or check_Model == True:
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
    step_path = os.path.join(out_dir, ModelName + u'.step')
    if check_Model == True:
        #ImportGui.insert(step_path,ModelName)
        ImportGui.open(step_path)
        docu = FreeCAD.ActiveDocument
        if cq_cad_tools.checkUnion(docu) == True:
            FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        else:
            FreeCAD.Console.PrintError('step file is NOT Unioned\n')
            stop
        FC_majorV = int(FreeCAD.Version()[0])
        FC_minorV = int(FreeCAD.Version()[1])
        if FC_majorV == 0 and FC_minorV >= 17:
            for o in docu.Objects:
                if hasattr(o, 'Shape'):
                    chks = cq_cad_tools.checkBOP(o.Shape)
                    print 'chks ', chks
                    print cq_cad_tools.mk_string(o.Label)
                    if chks != True:
                        msg = 'shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' is INVALID!\n'
                        FreeCAD.Console.PrintError(msg)
                        FreeCAD.Console.PrintWarning(chks[0])
                        stop
                    else:
                        msg = 'shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' is valid\n'
                        FreeCAD.Console.PrintMessage(msg)
        else:
            FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n')
            # Save the doc in Native FC format
        saveFCdoc(App, Gui, docu, ModelName, out_dir, False)
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)

    return 0
Beispiel #19
0
def print_export(objSelect):
    show_message = True
    PlaceOld = objSelect.Placement

    #_________Motor_Holder_________
    if 'motorholder' in objSelect.Name or 'nema_holder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 180)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Idler_Tensioner_________
    elif 'idler_tensioner' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Tensioner_Holder_________
    elif 'tensioner_holder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Filter_Holder_________
    elif 'filter_holder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Nema_Holder_________
    #elif 'nema_holder' in objSelect.Name:
    #    pos = objSelect.Placement.Base
    #    rot = FreeCAD.Rotation(FreeCAD.Vector(0,1,0),180)
    #    centre = FreeCAD.Vector(0,0,0)

    #_________Linbearhouse_________
    elif 'linbear' in objSelect.Name:
        if 'top' in objSelect.Name:
            pos = objSelect.Placement.Base
            rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 180)
            centre = FreeCAD.Vector(0, 0, 0)

        elif 'bot' in objSelect.Name:
            pos = objSelect.Placement.Base
            rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
            centre = FreeCAD.Vector(0, 0, 0)

        else:
            message = QtGui.QMessageBox()
            message.setText('Error')
            message.setStandardButtons(QtGui.QMessageBox.Ok)
            message.setDefaultButton(QtGui.QMessageBox.Ok)
            message.exec_()

    #_________Bracket_________
    elif 'bracket' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Bracket_3_________
    #elif bracket3 in objSelect.Name:
    #    pos = objSelect.Placement.Base
    #    rot = FreeCAD.Rotation(FreeCAD.Vector(0,0,0),0)
    #    centre = FreeCAD.Vector(0,0,0)

    #_________Bracket_Twin_________
    #elif bracket_twin in objSelect.Name:
    #    pos = objSelect.Placement.Base
    #    rot = FreeCAD.Rotation(FreeCAD.Vector(0,0,0),0)
    #    centre = FreeCAD.Vector(0,0,0)

    #_________Shaft_________
    elif 'shaft' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________IdlepulleyHold_________
    elif 'idlepulleyhold' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Simple_End_Stop_Holder_________
    elif 'simple_endstop_holder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Stop_Holder_________
    elif 'stop_holder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Belt_Clamp_________
    elif 'belt_clamp' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Sensor_Holder_________
    elif 'sensorholder' in objSelect.Name:
        pos = objSelect.Placement.Base
        rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90)
        centre = FreeCAD.Vector(0, 0, 0)

    #_________Not_Name_________
    else:
        message = QtGui.QMessageBox()
        message.setText('This object is not a workbench object.\n')
        message.setStandardButtons(QtGui.QMessageBox.Ok)
        message.setDefaultButton(QtGui.QMessageBox.Ok)
        message.exec_()
        show_message = False

    #######################################################
    #_________Message_And_Change_________
    if show_message == True:
        """message = QtGui.QMessageBox()
        message.setText("You select " + objSelect.Name + " to change to print position and export.\n")
        message.setStandardButtons(QtGui.QMessageBox.Ok)
        message.setDefaultButton(QtGui.QMessageBox.Ok)
        message.exec_()"""
        objSelect.Placement = FreeCAD.Placement(pos, rot, centre)
        FreeCADGui.activeDocument().activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")
        #_________EXPORT_________
        #Open the file explorer to set the folder
        gui = QtGui.QWidget()
        folderName = QtGui.QFileDialog.getExistingDirectory(
            gui, "Select directory", "c:/", QtGui.QFileDialog.ShowDirsOnly)

        # take the path and export the object
        stlFileName = str(folderName) + "/" + objSelect.Name + ".stl"
        mesh_shp = MeshPart.meshFromShape(objSelect.Shape,
                                          LinearDeflection=kparts.LIN_DEFL,
                                          AngularDeflection=kparts.ANG_DEFL)
        mesh_shp.write(stlFileName)
        del mesh_shp

        objSelect.Placement = PlaceOld

        message = QtGui.QMessageBox()
        message.setText("You export " + objSelect.Name + " in " + folderName)
        message.setStandardButtons(QtGui.QMessageBox.Ok)
        message.setDefaultButton(QtGui.QMessageBox.Ok)
        message.exec_()
    def accept(self):
        self.v.removeEventCallback("SoEvent", self.track)

        for obj in FreeCAD.ActiveDocument.Objects:
            if 'Point_d_w_h' == obj.Name:
                FreeCAD.ActiveDocument.removeObject('Point_d_w_h')

        Size_Value = {0: 6, 1: 8, 2: 10, 3: 12}
        Values_Pillow = {0: 0, 1: 1}
        TOL_Value = {0: 0.4, 1: 0.7}
        Size = Size_Value[self.Sk.Size_ComboBox.currentIndex()]
        Pillow = Values_Pillow[self.Sk.Pillow_ComboBox.currentIndex()]
        Tol = TOL_Value[self.Sk.Pillow_ComboBox.currentIndex()]
        pos = FreeCAD.Vector(self.Sk.pos_x.value(), self.Sk.pos_y.value(),
                             self.Sk.pos_z.value())
        positions_d = [0, 1]
        positions_w = [-1, 0, 1]
        positions_h = [0, 1]
        pos_d = positions_d[self.Sk.pos_d.currentIndex()]
        pos_w = positions_w[self.Sk.pos_w.currentIndex()]
        pos_h = positions_h[self.Sk.pos_h.currentIndex()]
        axis_d = FreeCAD.Vector(self.Sk.axis_d_x.value(),
                                self.Sk.axis_d_y.value(),
                                self.Sk.axis_d_z.value())
        axis_w = FreeCAD.Vector(self.Sk.axis_w_x.value(),
                                self.Sk.axis_w_y.value(),
                                self.Sk.axis_w_z.value())
        axis_h = FreeCAD.Vector(self.Sk.axis_h_x.value(),
                                self.Sk.axis_h_y.value(),
                                self.Sk.axis_h_z.value())

        if ortonormal_axis(axis_d, axis_w, axis_h) == True:
            if Pillow == 0 or (Pillow == 1
                               and Size == 8):  # Pillow only exist for size 8.

                comps_new.Sk_dir(
                    size=Size,
                    fc_axis_h=axis_h,
                    fc_axis_d=axis_d,
                    fc_axis_w=axis_w,
                    pos_h=pos_h,
                    pos_w=pos_w,
                    pos_d=pos_d,
                    pillow=Pillow,
                    pos=pos,
                    tol=Tol,  #0.7, # for the pillow block
                    wfco=1,
                    name="shaft" + str(Size) + "_holder")

                FreeCADGui.activeDocument().activeView().viewAxonometric(
                )  #Axonometric view
                FreeCADGui.SendMsgToActiveView(
                    "ViewFit")  #Fit the view to the object
                FreeCADGui.Control.closeDialog()  #close the dialog

            elif Pillow == 1 and Size != 8:
                message = QtWidgets.QMessageBox()
                message.setText("This Size don't have Pillow option")
                message.setStandardButtons(QtWidgets.QMessageBox.Ok)
                message.setDefaultButton(QtWidgets.QMessageBox.Ok)
                message.exec_()
def runw(window):

    window.rw = runwid(
        "Running ...<br>load the image and create the projections")
    window.rw.show()
    window.hide()

    fn = window.anz.text()
    FreeCAD.ParamGet('User parameter:Plugins/reconstruction').SetString(
        "Document", fn)

    bn = os.path.basename(fn)
    dn = os.path.dirname(fn)

    # load the image
    try:
        im = PIL.Image.open(fn)
    except:
        window.rw = runwid("Error loading file " + fn)
        window.show()
        window.rw.show()
        return

    sx, sy = im.size

    # load the image
    if App.ActiveDocument == None:
        App.ActiveDocument = App.newDocument("Unnamed")
        App.setActiveDocument("Unnamed")

    try:
        obj = App.ActiveDocument.Plane
    except:
        obj = App.ActiveDocument.addObject("Part::Plane", "Plane")
        App.ActiveDocument.recompute()
    obj.Label = bn

    obj.Length = sx
    obj.Width = sy

    addTextureImage(obj, fn)

    #set up the projection infrastructure
    try:
        obj2 = App.ActiveDocument.Plane001
    except:
        obj2 = App.ActiveDocument.addObject("Part::Plane", "Plane001")
        App.ActiveDocument.recompute()
    obj2.Label = "Landscape Trafo " + bn
    m = obj2.ViewObject.ShapeMaterial
    m.DiffuseColor = (0.0, 0.0, 0.0, 0.0)
    m.EmissiveColor = (0.0, 1.0, 1.0, 0.0)

    try:
        obj3 = App.ActiveDocument.Plane002
    except:
        obj3 = App.ActiveDocument.addObject("Part::Plane", "Plane002")
        App.ActiveDocument.recompute()
    obj3.Label = "Portrait Trafo " + bn
    m = obj3.ViewObject.ShapeMaterial
    m.DiffuseColor = (0.0, 0.0, 1.0, 1.0)
    m.EmissiveColor = (1.0, 1.0, 0.0, 1.0)

    try:
        sk = App.ActiveDocument.Sketch
        geo = sk.Geometry
    except:
        sk = App.ActiveDocument.addObject('Sketcher::SketchObject', 'Sketch')
        sk.addGeometry(
            Part.LineSegment(App.Vector(0, 0, 0), App.Vector(sx, 0, 0)), False)
        App.ActiveDocument.recompute()

        sk.addGeometry(
            Part.LineSegment(App.Vector(sx, 0, 0), App.Vector(sx, sy, 0)),
            False)
        App.ActiveDocument.recompute()
        sk.addConstraint(Sketcher.Constraint('Coincident', 0, 2, 1, 1))

        sk.addGeometry(
            Part.LineSegment(App.Vector(sx, sy, 0), App.Vector(0, sy, 0)),
            False)
        App.ActiveDocument.recompute()
        sk.addConstraint(Sketcher.Constraint('Coincident', 1, 2, 2, 1))

        sk.addGeometry(
            Part.LineSegment(App.Vector(-100, 100, 0),
                             App.Vector(-100, -100, 0)), False)
        App.ActiveDocument.recompute()
        sk.addConstraint(Sketcher.Constraint('Coincident', 2, 2, 3, 1))
        sk.addConstraint(Sketcher.Constraint('Coincident', 3, 2, 0, 1))
        App.ActiveDocument.recompute()
        geo = App.ActiveDocument.Sketch.Geometry

    sk.Label = "Border for " + bn
    sk.ViewObject.LineColor = (1.0, 0.0, 0.0)
    sk.ViewObject.LineWidth = 5

    pa = [(geo[i].StartPoint.x, sy - geo[i].StartPoint.y)
          for i in [0, 1, 3, 2]]

    #size of the results
    a = 3000
    b = 2000

    #border offset
    try:
        r = int(window.off.text())
    except:
        print "cannot convert offset value"
        window.off.setText('0')
        r = 0

    pb = [(r, r), (a - r, r), (r, b - r), (a - r, b - r)]

    M = find_coeffs(pb, pa)

    ima = im.transform((a, b), PIL.Image.PERSPECTIVE, M, PIL.Image.BICUBIC)

    im2 = ima.transpose(PIL.Image.FLIP_TOP_BOTTOM)

    a3, b3 = b, a
    im3 = ima.transpose(PIL.Image.ROTATE_90)

    rotpos = window.rotpos.isChecked()

    if rotpos and window.rotneg.isChecked():
        window.rotneg.click()

    rotneg = window.rotneg.isChecked()

    if (rotpos or rotneg) and window.rot180.isChecked():
        window.rot180.click()

    rot180 = window.rot180.isChecked()

    if rotpos:
        im3 = im3.transpose(PIL.Image.ROTATE_90)
        im2 = im2.transpose(PIL.Image.ROTATE_270)

    if rotneg:
        im3 = im3.transpose(PIL.Image.ROTATE_270)
        im2 = im2.transpose(PIL.Image.ROTATE_90)

    if rot180:
        im3 = im3.transpose(PIL.Image.ROTATE_180)
        im2 = im2.transpose(PIL.Image.ROTATE_180)

    # save the images into the sdame directory dn with profixes
    fn2 = dn + '/_land_' + bn
    im2.save(fn2)

    fn3 = dn + '/_port_' + bn
    im3.save(fn3)

    FreeCAD.Console.PrintMessage("\nSave images as " + fn2 + " " + fn3)

    obj2.Placement.Base.x = sx + 50
    obj2.Length = a
    obj2.Width = b
    addTextureImage(obj2, fn2)
    App.ActiveDocument.recompute()

    obj3.Placement.Base.x = sx + a + 100
    obj3.Length = a3
    obj3.Width = b3
    addTextureImage(obj3, fn3)
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")

    # geht noch nicht #?
    obj3.ViewObject.ShapeMaterial.DiffuseColor = (0.0, 0.0, 0.0, 0.0)
    obj3.ViewObject.ShapeMaterial.EmissiveColor = (1.0, 1.0, 0.0, 1.)
    obj2.ViewObject.ShapeMaterial.DiffuseColor = (0.0, 0.0, 0.0, 0.0)
    obj2.ViewObject.ShapeMaterial.EmissiveColor = (.0, 1.0, 1.0, 1.)

    print "colors"
    print obj3.ViewObject.ShapeMaterial.DiffuseColor

    for ob in [obj, obj2, obj3]:
        ob.ViewObject.Selectable = False

    window.show()
    window.rw.hide()
def make_3D_model(models_dir, model_class, modelName):

    LIST_license = [
        "",
    ]

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedmodelName)
    destination_dir = model_class.get_dest_3D_dir()

    material_substitutions = model_class.make_3D_model(modelName)

    doc = FreeCAD.ActiveDocument
    doc.Label = CheckedmodelName

    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir = models_dir + os.sep + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName, out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
        #out_dir=script_dir+os.sep+destination_dir+os.sep+all_params[variant].dest_dir_prefix
        out_dir=models_dir+destination_dir
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        #out_dir="./generated_qfp/"
        # export STEP model
        exportSTEP(doc, ModelName, out_dir)
        if LIST_license[0]=="":
            LIST_license=Lic.LIST_int_license
            LIST_license.append("")
        Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                           STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

        # scale and export Vrml model
        scale=1/2.54
        #exportVRML(doc,ModelName,scale,out_dir)
        objs=GetListOfObjects(FreeCAD, doc)
        expVRML.say("######################################################################")
        expVRML.say(objs)
        expVRML.say("######################################################################")
        export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
        export_file_name=out_dir+os.sep+ModelName+'.wrl'
        colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
        expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)
        # Save the doc in Native FC format
        saveFCdoc(App, Gui, doc, ModelName,out_dir)
        #display BBox
        #FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True
        Gui.activateWorkbench("PartWorkbench")
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()
Beispiel #24
0
def setup(doc=None, solver="ccxtools"):
    # setup model

    if doc is None:
        doc = init_doc()

    p1 = FreeCAD.Vector(0, 0, 50)
    p2 = FreeCAD.Vector(0, 0, -50)
    p3 = FreeCAD.Vector(0, 0, -4300)
    p4 = FreeCAD.Vector(4950, 0, -4300)
    p5 = FreeCAD.Vector(5000, 0, -4300)
    p6 = FreeCAD.Vector(8535.53, 0, -7835.53)
    p7 = FreeCAD.Vector(8569.88, 0, -7870.88)
    p8 = FreeCAD.Vector(12105.41, 0, -11406.41)
    p9 = FreeCAD.Vector(12140.76, 0, -11441.76)
    p10 = FreeCAD.Vector(13908.53, 0, -13209.53)
    p11 = FreeCAD.Vector(13943.88, 0, -13244.88)
    p12 = FreeCAD.Vector(15046.97, 0, -14347.97)
    p13 = FreeCAD.Vector(15046.97, 0, -7947.97)
    p14 = FreeCAD.Vector(15046.97, 0, -7847.97)
    p15 = FreeCAD.Vector(0, 0, 0)
    p16 = FreeCAD.Vector(0, 0, -2175)
    p17 = FreeCAD.Vector(2475, 0, -4300)
    p18 = FreeCAD.Vector(4975, 0, -4300)
    p19 = FreeCAD.Vector(6767.765, 0, -6067.765)
    p20 = FreeCAD.Vector(8552.705, 0, -7853.205)
    p21 = FreeCAD.Vector(10337.645, 0, -9638.645)
    p22 = FreeCAD.Vector(12123.085, 0, -11424.085)
    p23 = FreeCAD.Vector(13024.645, 0, -12325.645)
    p24 = FreeCAD.Vector(13926.205, 0, -13227.205)
    p25 = FreeCAD.Vector(14495.425, 0, -13796.425)
    p26 = FreeCAD.Vector(15046.97, 0, -11147.97)
    p27 = FreeCAD.Vector(15046.97, 0, -7897.97)
    points = [
        p1, p2, p3, p4, p5, p6, p7, p8, p9, p10,
        p11, p12, p13, p14, p15, p16, p17, p18, p19, p20,
        p21, p22, p23, p24, p25, p26, p27
    ]
    from Draft import makeWire
    line = makeWire(
        points,
        closed=False,
        face=False,
        support=None
    )
    doc.recompute()

    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.ActiveDocument.activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

    # analysis
    analysis = ObjectsFem.makeAnalysis(doc, "Analysis")

    # solver
    # TODO How to pass multiple solver for one analysis in one doc
    if solver == "calculix":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX")
        )[0]
    elif solver == "ccxtools":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools")  # CalculiX
        )[0]
        solver_object.WorkingDir = u""
    if solver == "calculix" or solver == "ccxtools":
        solver_object.AnalysisType = "thermomech"
        solver_object.GeometricalNonlinearity = "linear"
        solver_object.ThermoMechSteadyState = True
        solver_object.MatrixSolverType = "default"
        solver_object.IterationsThermoMechMaximum = 2000
        solver_object.IterationsControlParameterTimeUse = False

    # material
    material_object = analysis.addObject(
        ObjectsFem.makeMaterialFluid(doc, "FluidMaterial")
    )[0]
    mat = material_object.Material
    mat["Name"] = "Water"
    mat["Density"] = "998 kg/m^3"
    mat["SpecificHeat"] = "4.182 J/kg/K"
    mat["DynamicViscosity"] = "1.003e-3 kg/m/s"
    mat["VolumetricThermalExpansionCoefficient"] = "2.07e-4 m/m/K"
    mat["ThermalConductivity"] = "0.591 W/m/K"
    material_object.Material = mat

    inlet = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    inlet.SectionType = "Liquid"
    inlet.LiquidSectionType = "PIPE INLET"
    inlet.InletPressure = 0.1
    inlet.References = [(line, "Edge1")]

    entrance = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    entrance.SectionType = "Liquid"
    entrance.LiquidSectionType = "PIPE ENTRANCE"
    entrance.EntrancePipeArea = 31416.00
    entrance.EntranceArea = 25133.00
    entrance.References = [(line, "Edge2")]

    manning1 = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    manning1.SectionType = "Liquid"
    manning1.LiquidSectionType = "PIPE MANNING"
    manning1.ManningArea = 31416
    manning1.ManningRadius = 50
    manning1.ManningCoefficient = 0.002
    manning1.References = [(line, "Edge3"), (line, "Edge5")]

    bend = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    bend.SectionType = "Liquid"
    bend.LiquidSectionType = "PIPE BEND"
    bend.BendPipeArea = 31416
    bend.BendRadiusDiameter = 1.5
    bend.BendAngle = 45
    bend.BendLossCoefficient = 0.4
    bend.References = [(line, "Edge4")]

    enlargement1 = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    enlargement1.SectionType = "Liquid"
    enlargement1.LiquidSectionType = "PIPE ENLARGEMENT"
    enlargement1.EnlargeArea1 = 31416.00
    enlargement1.EnlargeArea2 = 70686.00
    enlargement1.References = [(line, "Edge6")]

    manning2 = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    manning2.SectionType = "Liquid"
    manning2.LiquidSectionType = "PIPE MANNING"
    manning2.ManningArea = 70686.00
    manning2.ManningRadius = 75
    manning2.ManningCoefficient = 0.002
    manning2.References = [(line, "Edge7")]

    contraction = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    contraction.SectionType = "Liquid"
    contraction.LiquidSectionType = "PIPE CONTRACTION"
    contraction.ContractArea1 = 70686
    contraction.ContractArea2 = 17671
    contraction.References = [(line, "Edge8")]

    manning3 = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    manning3.SectionType = "Liquid"
    manning3.LiquidSectionType = "PIPE MANNING"
    manning3.ManningArea = 17671.00
    manning3.ManningRadius = 37.5
    manning3.ManningCoefficient = 0.002
    manning3.References = [(line, "Edge11"), (line, "Edge9")]

    gate_valve = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    gate_valve.SectionType = "Liquid"
    gate_valve.LiquidSectionType = "PIPE GATE VALVE"
    gate_valve.GateValvePipeArea = 17671
    gate_valve.GateValveClosingCoeff = 0.5
    gate_valve.References = [(line, "Edge10")]

    enlargement2 = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    enlargement2.SectionType = "Liquid"
    enlargement2.LiquidSectionType = "PIPE ENLARGEMENT"
    enlargement2.EnlargeArea1 = 17671
    enlargement2.EnlargeArea2 = 1e12
    enlargement2.References = [(line, "Edge12")]

    outlet = analysis.addObject(
        ObjectsFem.makeElementFluid1D(doc, "ElementFluid1D")
    )[0]
    outlet.SectionType = "Liquid"
    outlet.LiquidSectionType = "PIPE OUTLET"
    outlet.OutletPressure = 0.1
    outlet.References = [(line, "Edge13")]

    self_weight = analysis.addObject(
        ObjectsFem.makeConstraintSelfWeight(doc, "ConstraintSelfWeight")
    )[0]
    self_weight.Gravity_x = 0.0
    self_weight.Gravity_y = 0.0
    self_weight.Gravity_z = -1.0

    # mesh
    from .meshes.mesh_thermomech_flow1d import create_nodes, create_elements
    fem_mesh = Fem.FemMesh()
    control = create_nodes(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating nodes.\n")
    control = create_elements(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating elements.\n")
    femmesh_obj = analysis.addObject(
        doc.addObject("Fem::FemMeshObject", mesh_name)
    )[0]
    femmesh_obj.FemMesh = fem_mesh

    doc.recompute()
    return doc
Beispiel #25
0
def read(filename):
    "reads the file and creates objects in the active document"
    #import importZip; reload(importZip)
    print("open Zip STEP version " + ___ZipVersion___)

    z = zipfile.ZipFile(filename)
    l = z.printdir()
    #il = z.infolist()
    nl = z.namelist()
    print("file list: ", nl)
    import ImportGui, FreeCADGui

    for f in nl:
        if '.stp' in f.lower() or '.step' in f.lower():  #\
            #or '.igs' in f.lower() or '.iges' in f.lower():
            file_content = z.read(f)
            #sfe = z.extract(f)
            #print ('extracted ',sfe)
            print('extracted ', f)
            # fname=os.path.splitext(os.path.basename(filename))[0]
            # ext = os.path.splitext(os.path.basename(filename))[1]
            fname = f
            print('fname ', f)
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            ImportGui.insert(tempfilepath, doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
        elif '.fcstd' in f.lower():  #\
            fname = f
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            i = 0
            for obj in FreeCAD.ActiveDocument.Objects:
                i += 1
            if i == 0:
                FreeCAD.closeDocument(doc.Name)
            FreeCAD.open(tempfilepath)
            #ImportGui.insert(tempfilepath,doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
        elif '.brep' in f.lower():  #\
            fname = f
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            import Part
            #Part.open(tempfilepath,doc.Name)
            Part.insert(tempfilepath, doc.Name)
            #FreeCAD.open(tempfilepath)
            #ImportGui.insert(tempfilepath,doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
def generateOneModel(params, log):
    excluded_pins_x = ()  ##no pin excluded
    excluded_pins_xmirror = ()  ##no pin excluded
    place_pinMark = True  ##default =True used to exclude pin mark to build sot23-3; sot23-5; sc70 (asimmetrical pins, no pinmark)

    ModelName = params.modelName
    FreeCAD.Console.PrintMessage('\n\n##############  ' + ModelName +
                                 '  ###############\n')
    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)
    #case, pins, pinmark = make_case(params)
    case_bot, case, pins, pinmark = make_case(params)

    if case_bot is not None:
        show(case_bot)
    show(case)
    show(pins)
    show(pinmark)
    #stop

    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    if case_bot is not None:
        Color_Objects(Gui, objs[0], body_bot_color)
        Color_Objects(Gui, objs[1], body_color)
        Color_Objects(Gui, objs[2], pins_color)
        Color_Objects(Gui, objs[3], marking_color)

        col_body_bot = Gui.ActiveDocument.getObject(
            objs[0].Name).DiffuseColor[0]
        col_body = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
        col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
        col_mark = Gui.ActiveDocument.getObject(objs[3].Name).DiffuseColor[0]
        material_substitutions = {
            col_body_bot[:-1]: body_bot_color_key,
            col_body[:-1]: body_color_key,
            col_pin[:-1]: pins_color_key,
            col_mark[:-1]: marking_color_key
        }
        expVRML.say(material_substitutions)
        if (color_pin_mark == True) and (place_pinMark == True):
            CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[1].Name,
                            objs[3].Name)
        else:
            #removing pinMark
            App.getDocument(doc.Name).removeObject(objs[3].Name)
        ###
        #sleep
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
    else:
        Color_Objects(Gui, objs[0], body_color)
        Color_Objects(Gui, objs[1], pins_color)
        Color_Objects(Gui, objs[2], marking_color)

        col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
        col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
        col_mark = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
        material_substitutions = {
            col_body[:-1]: body_color_key,
            col_pin[:-1]: pins_color_key,
            col_mark[:-1]: marking_color_key
        }
        #expVRML.say(material_substitutions)
        if (color_pin_mark == True) and (place_pinMark == True):
            CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                            objs[2].Name)
        else:
            #removing pinMark
            App.getDocument(doc.Name).removeObject(objs[2].Name)
        ###
        #sleep
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
    ## objs[0].Label='body'
    ## objs[1].Label='pins'
    ## objs[2].Label='mark'
    ###
    ## print objs[0].Name, objs[1].Name, objs[2].Name

    ## sleep
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()
    #rotate if required
    if (params.rotation != 0):
        rot = params.rotation
        z_RotateObject(doc, rot)
    #out_dir=destination_dir+params.dest_dir_prefix+'/'
    script_dir = os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    #expVRML.say(models_dir)
    if len(params.dest_dir_prefix) >= 1:
        out_dir = models_dir + destination_dir + os.sep + params.dest_dir_prefix
    else:
        out_dir = models_dir + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    #out_dir="./generated_qfp/"
    # export STEP model
    exportSTEP(doc, ModelName, out_dir)
    global LIST_license
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)

    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile added creaeAngle
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license, 0.9)
    # Save the doc in Native FC format
    #saveFCdoc(App, Gui, doc, ModelName,out_dir)
    #display BBox
    #FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True
    if footprints_dir is not None and os.path.isdir(
            footprints_dir
    ) and not save_memory and not check_Model:  #it doesn't make sense to import the footprint right before we close the file.
        #expVRML.say (ModelName)
        #stop
        sys.argv = [
            "fc", "dummy", footprints_dir + os.sep + ModelName, "savememory"
        ]
        #setup = get_setup_file()  # << You need the parentheses
        expVRML.say(sys.argv[2])
        if not ksu_present:
            try:
                import kicadStepUptools
                ksu_present = True
                expVRML.say("ksu present!")
                kicadStepUptools.KSUWidget.close()
                #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized)
                #kicadStepUptools.KSUWidget.destroy()
                #for i in QtGui.qApp.topLevelWidgets():
                #    if i.objectName() == "kicadStepUp":
                #        i.deleteLater()
                kicadStepUptools.KSUWidget.close()
            except:
                ksu_present = False
                expVRML.say("ksu not present")
        else:
            kicadStepUptools.KSUWidget.close()
            reload(kicadStepUptools)
            kicadStepUptools.KSUWidget.close()
            #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized)
            #kicadStepUptools.KSUWidget.destroy()

    #FreeCADGui.insert(u"C:\Temp\FCAD_sg\QFN_packages\QFN-12-1EP_3x3mm_Pitch0_5mm.kicad_mod")
    #FreeCADGui.insert(script_dir+os.sep+"ModelName.kicad_mod")
    if save_memory == False:
        Gui.activateWorkbench("PartWorkbench")
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewBottom()
        #Gui.activeDocument().activeView().viewAxometric()
    saveFCdoc(App, Gui, doc, ModelName, out_dir)

    if save_memory == True or check_Model == True:
        doc = FreeCAD.ActiveDocument
        print("closing: {}".format(doc.Name))
        FreeCAD.closeDocument(doc.Name)

    if check_Model == True:
        step_path = out_dir + '/' + ModelName + ".step"
        runGeometryCheck(App,
                         Gui,
                         step_path,
                         log,
                         ModelName,
                         save_memory=save_memory)
Beispiel #27
0
def setup(doc=None, solver="ccxtools"):
    # setup model

    if doc is None:
        doc = init_doc()

    # part
    box_obj = doc.addObject("Part::Box", "Box")
    box_obj.Height = 25.4
    box_obj.Width = 25.4
    box_obj.Length = 203.2
    doc.recompute()

    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.ActiveDocument.activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

    # analysis
    analysis = ObjectsFem.makeAnalysis(doc, "Analysis")

    # solver
    # TODO How to pass multiple solver for one analysis in one doc
    if solver == "calculix":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX"))[0]
    elif solver == "ccxtools":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools"))[0]
        solver_object.WorkingDir = u""
    # should be possible with elmer too
    # elif solver == "elmer":
    #     analysis.addObject(ObjectsFem.makeSolverElmer(doc, "SolverElmer"))
    if solver == "calculix" or solver == "ccxtools":
        solver_object.AnalysisType = "thermomech"
        solver_object.GeometricalNonlinearity = "linear"
        solver_object.ThermoMechSteadyState = True
        solver_object.MatrixSolverType = "default"
        solver_object.IterationsThermoMechMaximum = 2000
        solver_object.IterationsControlParameterTimeUse = True

    # material
    material_object = analysis.addObject(
        ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterial"))[0]
    mat = material_object.Material
    mat["Name"] = "Steel-Generic"
    mat["YoungsModulus"] = "200000 MPa"
    mat["PoissonRatio"] = "0.30"
    mat["Density"] = "7900 kg/m^3"
    mat["ThermalConductivity"] = "43.27 W/m/K"  # SvdW: Change to Ansys model values
    mat["ThermalExpansionCoefficient"] = "12 um/m/K"
    mat["SpecificHeat"] = "500 J/kg/K"  # SvdW: Change to Ansys model values
    material_object.Material = mat

    # fixed_constraint
    fixed_constraint = analysis.addObject(
        ObjectsFem.makeConstraintFixed(doc, "FemConstraintFixed"))[0]
    fixed_constraint.References = [(box_obj, "Face1")]

    # initialtemperature_constraint
    initialtemperature_constraint = analysis.addObject(
        ObjectsFem.makeConstraintInitialTemperature(
            doc, "FemConstraintInitialTemperature"))[0]
    initialtemperature_constraint.initialTemperature = 300.0

    # temperature_constraint
    temperature_constraint = analysis.addObject(
        ObjectsFem.makeConstraintTemperature(doc,
                                             "FemConstraintTemperature"))[0]
    temperature_constraint.References = [(box_obj, "Face1")]
    temperature_constraint.Temperature = 310.93

    # heatflux_constraint
    heatflux_constraint = analysis.addObject(
        ObjectsFem.makeConstraintHeatflux(doc, "FemConstraintHeatflux"))[0]
    heatflux_constraint.References = [(box_obj, "Face3"), (box_obj, "Face4"),
                                      (box_obj, "Face5"), (box_obj, "Face6")]
    heatflux_constraint.AmbientTemp = 255.3722
    heatflux_constraint.FilmCoef = 5.678

    # mesh
    from .meshes.mesh_thermomech_spine import create_nodes, create_elements
    fem_mesh = Fem.FemMesh()
    control = create_nodes(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating nodes.\n")
    control = create_elements(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating elements.\n")
    femmesh_obj = analysis.addObject(
        doc.addObject("Fem::FemMeshObject", mesh_name))[0]
    femmesh_obj.FemMesh = fem_mesh

    doc.recompute()
    return doc
Beispiel #28
0
 def Activated(self):
     Gui.doCommandGui("import freecad.gears.commands")
     Gui.doCommandGui("freecad.gears.commands.{}.create()".format(
         self.__class__.__name__))
     FreeCAD.ActiveDocument.recompute()
     Gui.SendMsgToActiveView("ViewFit")
def setup(doc=None, solvertype="ccxtools"):
    # setup model

    if doc is None:
        doc = init_doc()

    # geometry objects
    # TODO turn circle of upper tube to have the line on the other side
    # make a boolean fragment of them to be sure there is a mesh point on remesh
    # but as long as we do not remesh it works without the boolean fragment too

    # tubes
    tube_radius = 25
    tube_length = 500
    sh_lower_circle = Part.Wire(Part.makeCircle(tube_radius))
    sh_lower_tube = sh_lower_circle.extrude(FreeCAD.Vector(0, 0, tube_length))
    sh_lower_tube.reverse()
    lower_tube = doc.addObject("Part::Feature", "Lower_tube")
    lower_tube.Shape = sh_lower_tube

    sh_upper_circle = Part.Wire(Part.makeCircle(tube_radius))
    sh_upper_tube = sh_upper_circle.extrude(FreeCAD.Vector(0, 0, tube_length))
    sh_upper_tube.reverse()
    upper_tube = doc.addObject("Part::Feature", "Upper_tube")
    upper_tube.Shape = sh_upper_tube
    upper_tube.Placement = FreeCAD.Placement(
        FreeCAD.Vector(-25, 51, 475),
        FreeCAD.Rotation(90, 0, 90),
        FreeCAD.Vector(0, 0, 0),
    )

    # point for load
    v_force_pt = FreeCAD.Vector(0, 76, 475)
    sh_force_point = Part.Vertex(v_force_pt)
    force_point = doc.addObject("Part::Feature", "Load_place_point")
    force_point.Shape = sh_force_point
    if FreeCAD.GuiUp:
        force_point.ViewObject.PointSize = 10.0
        force_point.ViewObject.PointColor = (1.0, 0.0, 0.0)

    # boolean fragment of upper tubo and force point
    boolfrag = SplitFeatures.makeBooleanFragments(name='BooleanFragments')
    boolfrag.Objects = [upper_tube, force_point]
    if FreeCAD.GuiUp:
        upper_tube.ViewObject.hide()

    # compound out of bool frag and lower tube
    goem_obj = doc.addObject("Part::Compound", "AllGeomCompound")
    goem_obj.Links = [boolfrag, lower_tube]

    # line for load direction
    sh_load_line = Part.makeLine(v_force_pt, FreeCAD.Vector(0, 150, 475))
    load_line = doc.addObject("Part::Feature", "Load_direction_line")
    load_line.Shape = sh_load_line
    if FreeCAD.GuiUp:
        load_line.ViewObject.LineWidth = 5.0
        load_line.ViewObject.LineColor = (1.0, 0.0, 0.0)

    doc.recompute()

    if FreeCAD.GuiUp:
        import FreeCADGui
        goem_obj.ViewObject.Document.activeView().viewAxonometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")

    # analysis
    analysis = ObjectsFem.makeAnalysis(doc, "Analysis")

    # solver
    if solvertype == "calculix":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX")
        )[0]
    elif solvertype == "ccxtools":
        solver_object = analysis.addObject(
            ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools")
        )[0]
        solver_object.WorkingDir = u""
    if solvertype == "calculix" or solvertype == "ccxtools":
        solver_object.AnalysisType = "static"
        solver_object.BeamShellResultOutput3D = True
        solver_object.GeometricalNonlinearity = "linear"  # really?
        # TODO iterations parameter !!!
        solver_object.ThermoMechSteadyState = False
        solver_object.MatrixSolverType = "default"
        solver_object.IterationsControlParameterTimeUse = False
        solver_object.SplitInputWriter = False

    # shell thickness
    analysis.addObject(ObjectsFem.makeElementGeometry2D(doc, 0.5, 'ShellThickness'))

    # material
    material_obj = analysis.addObject(
        ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterial")
    )[0]
    mat = material_obj.Material
    mat["Name"] = "AlCuMgPb"
    mat["YoungsModulus"] = "72000 MPa"
    mat["PoissonRatio"] = "0.30"
    material_obj.Material = mat
    analysis.addObject(material_obj)

    # fixed_constraint
    fixed_constraint = analysis.addObject(
        ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed")
    )[0]
    fixed_constraint.References = [
        (lower_tube, "Edge2"),
        (upper_tube, "Edge3"),
    ]

    # force_constraint
    force_constraint = doc.Analysis.addObject(
        ObjectsFem.makeConstraintForce(doc, name="ConstraintForce")
    )[0]
    # TODO use point of tube boolean fragment
    force_constraint.References = [(force_point, "Vertex1")]
    force_constraint.Force = 5000.0
    force_constraint.Direction = (load_line, ["Edge1"])
    force_constraint.Reversed = True

    # contact constraint
    contact_constraint = doc.Analysis.addObject(
        ObjectsFem.makeConstraintContact(doc, name="ConstraintContact")
    )[0]
    contact_constraint.References = [
        (lower_tube, "Face1"),
        (upper_tube, "Face1"),
    ]
    contact_constraint.Friction = 0.0
    # contact_constrsh_aint.Slope = "1000000.0 kg/(mm*s^2)"  # contact stiffness
    contact_constraint.Slope = 1000000.0  # should be 1000000.0 kg/(mm*s^2)

    # mesh
    from .meshes.mesh_contact_tube_tube_tria3 import create_nodes, create_elements
    fem_mesh = Fem.FemMesh()
    control = create_nodes(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating nodes.\n")
    control = create_elements(fem_mesh)
    if not control:
        FreeCAD.Console.PrintError("Error on creating elements.\n")
    femmesh_obj = analysis.addObject(
        doc.addObject("Fem::FemMeshObject", mesh_name)
    )[0]
    femmesh_obj.FemMesh = fem_mesh

    doc.recompute()
    return doc
Beispiel #30
0
def makeFaceDXF():
    global copper_diffuse, silks_diffuse
    global use_LinkGroups, use_AppPart

    doc = FreeCAD.ActiveDocument
    if doc is None:
        FreeCAD.newDocument()
        doc = FreeCAD.ActiveDocument
    docG = FreeCADGui.ActiveDocument
    Filter = ""
    last_pcb_path = ""
    pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/kicadStepUp")
    last_pcb_path = pg.GetString("last_pcb_path")
    fn, Filter = PySide.QtGui.QFileDialog.getOpenFileNames(
        None, "Open File...", make_unicode(last_pcb_path), "*.dxf")
    for fname in fn:
        path, name = os.path.split(fname)
        filename = os.path.splitext(name)[0]
        #importDXF.open(os.path.join(dirname,filename))
        if len(fname) > 0:
            #importDXF.open(fname)
            last_pcb_path = os.path.dirname(fname)
            pg = FreeCAD.ParamGet(
                "User parameter:BaseApp/Preferences/Mod/kicadStepUp")
            pg.SetString("last_pcb_path",
                         make_string(last_pcb_path))  # py3 .decode("utf-8")
            pg = FreeCAD.ParamGet(
                "User parameter:BaseApp/Preferences/Mod/kicadStepUpGui")
            pcb_color_pos = pg.GetInt('pcb_color')
            #print(pcb_color_pos)
            if pcb_color_pos == 9:
                silks_diffuse = (0.18, 0.18, 0.18)  #slick black
            else:
                silks_diffuse = (
                    0.98, 0.92, 0.84
                )  # #antique white  # white (0.906,0.906,0.910)
            doc = FreeCAD.ActiveDocument
            objects = []
            say("loading... ")
            t = time.time()
            if doc is not None:
                for o in doc.Objects:
                    objects.append(o.Name)
                importDXF.insert(fname, doc.Name)
            else:
                importDXF.open(fname)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            timeP = time.time() - t
            say("loading time = " + str(timeP) + "s")

            edges = []
            sorted_edges = []
            w = []

            for o in doc.Objects:
                if o.Name not in str(objects):
                    if hasattr(o, 'Shape'):
                        w1 = Part.Wire(Part.__sortEdges__(o.Shape.Edges))
                        w.append(w1)
            #print (w)
            f = Part.makeFace(w, 'Part::FaceMakerBullseye')
            for o in doc.Objects:
                if o.Name not in str(objects):
                    doc.removeObject(o.Name)
            if 'Silk' in filename:
                layerName = 'Silks'
            else:
                layerName = 'Tracks'
            if 'F.' in filename or 'F_' in filename:
                layerName = 'top' + layerName
            if 'B.' in filename or 'B_' in filename:
                layerName = 'bot' + layerName

            doc.addObject('Part::Feature', layerName).Shape = f
            newShape = doc.ActiveObject
            botOffset = 1.6
            if 'Silk' in layerName:
                docG.getObject(newShape.Name).ShapeColor = silks_diffuse
            else:
                docG.getObject(
                    newShape.Name
                ).ShapeColor = brass_diffuse  #copper_diffuse  #(0.78,0.56,0.11)
            if len(doc.getObjectsByLabel('Pcb')) > 0:
                newShape.Placement = doc.getObjectsByLabel('Pcb')[0].Placement
                #botTracks.Placement = doc.Pcb.Placement
                if len(doc.getObjectsByLabel('Board_Geoms')) > 0:
                    if use_AppPart and not use_LinkGroups:
                        doc.getObject('Board_Geoms').addObject(newShape)
                    elif use_LinkGroups:
                        doc.getObject('Board_Geoms').ViewObject.dropObject(
                            newShape, None, '', [])
                if hasattr(doc.getObjectsByLabel('Pcb')[0], 'Shape'):
                    botOffset = doc.getObjectsByLabel(
                        'Pcb')[0].Shape.BoundBox.ZLength
                else:
                    botOffset = doc.getObjectsByLabel(
                        'Pcb')[0].OutList[1].Shape.BoundBox.ZLength
            #elif 'bot' in layerName:
            #    newShape.Placement.Base.z-=1.6
            if 'top' in layerName:
                newShape.Placement.Base.z += 0.07
            if 'bot' in layerName:
                newShape.Placement.Base.z -= botOffset + 0.07
            timeD = time.time() - t - timeP
            say("displaying time = " + str(timeD) + "s")
    FreeCADGui.SendMsgToActiveView("ViewFit")
    docG.activeView().viewAxonometric()