Exemple #1
0
        int ComponentDisplayStateChangeNotify(object swObject)
        {
            Component2 component = (Component2)swObject;
            ModelDoc2  modDoc    = (ModelDoc2)component.GetModelDoc();

            return(ComponentStateChange(modDoc));
        }
        public void setColour(Color c)
        {
            SldWorks swApp = ConnectToSolidWorks();

            Component2 swComp = default(Component2);

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager;

            swComp = swSelMgr.GetSelectedObjectsComponent3(1, 0);

            var vMatProp = (double[])swComp.MaterialPropertyValues;// GetModelMaterialPropertyValues("");

            if (vMatProp == null)
            {
                ModelDoc2 swCompModel = (ModelDoc2)swComp.GetModelDoc();

                vMatProp = (double[])swCompModel.MaterialPropertyValues;
            }

            vMatProp[0] = c.R / 255;
            vMatProp[1] = c.G / 255;
            vMatProp[2] = c.B / 255;

            swComp.MaterialPropertyValues = vMatProp;
        }
Exemple #3
0
        int ComponentVisualPropertiesChangeNotify(object swObject)
        {
            Component2 component = (Component2)swObject;
            ModelDoc2  modDoc    = (ModelDoc2)component.GetModelDoc();

            return(ComponentStateChange(modDoc));
        }
        // Set Materials
        public void ApplyMaterial(string partPath, string confName, int materialID, SldWorks swapp)
        {
            _swmodel = swapp.ActiveDoc;
            swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, GlobalPaths.PathToSwComplexFolder); // задаем базы данных материалов

            _swPartDoc = ((PartDoc)(_swmodel));

            const string dbMatName = "vents-materials.sldmat";

            ToSQL addMatXml = new ToSQL();

            if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                Component2 comp        = _swmodel.ISelectionManager.GetSelectedObject3(1);
                PartDoc    swPartAssem = comp.GetModelDoc();

                //// удаляем материал
                //swPartAssem.SetMaterialPropertyName("", "");

                // применяем материал
                swPartAssem.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID));
                _swmodel.ClearSelection2(true);
            }
            else if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                // Если имя не пустое
                if (partPath != "")
                {
                    //// удаляем материал
                    //swPartDoc.SetMaterialPropertyName("", "");

                    // применяем материал
                    _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID));


                    //_swmodel.ForceRebuild3(false);
                    //_swmodel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, 0);
                    //swapp.CloseDoc(partPath);
                    //swapp.ExitApp();
                    //swapp = null;
                }
                else
                {
                    //// удаляем материал
                    //swPartDoc.SetMaterialPropertyName(confName, "");

                    // применяем материал
                    _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID));
                }
            }


            //catch (Exception ex)
            //{
            //    //swapp.SendMsgToUser(ex.ToString());
            //    MessageBox.Show(ex.Message);
            //    Error = ex.ToString();
            //}
        }
Exemple #5
0
        int ComponentDisplayStateChangeNotify(object swObject)
        {
            Component2 component = (Component2)swObject;
            ModelDoc2  modDoc    = (ModelDoc2)component.GetModelDoc();

            //StringBuilder sb = new StringBuilder();
            //sb.Append(modDoc.SceneName + "----" + modDoc.SceneUserName);

            return(ComponentStateChange(modDoc));
        }
Exemple #6
0
        public static void Set_transparency(ModelDoc2 swModel, string name)
        {
            AssemblyDoc swAssembly = null;

            Component2 swComp     = null;
            ModelDoc2  swCompDoc  = null;
            bool       boolstatus = false;

            try
            {
                if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    swModel.ClearSelection2(true);
                    //  boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    //  SelectionMgr SwSelMgr = swModel.SelectionManager;
                    swAssembly = (AssemblyDoc)swModel;
                    var Components = swAssembly.GetComponents(false);

                    for (int i = 0; i < Components.Length; i++)
                    {
                        //swComp = swAssembly.GetComponentByName(name);
                        swComp = Components[i];
                        if (swComp != null)
                        {
                            if (swComp.Name2.Contains(name))
                            {
                                //   MessageBox.Show(name);

                                var vMatProps = swComp.MaterialPropertyValues;
                                if (vMatProps == null)
                                {
                                    swCompDoc = swComp.GetModelDoc();
                                    if (swCompDoc == null)
                                    {
                                        return;
                                    }
                                    vMatProps = swCompDoc.MaterialPropertyValues;
                                }
                                vMatProps[7] = 1; //Transparency

                                swComp.MaterialPropertyValues = vMatProps;
                                swModel.ClearSelection2(true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        public string CreateNewJoinPart(AssemblyDoc assemblyDoc, Component2 insertComponentSendtoCustomer, Component2 insertComponentLocal, ModelDoc2 swModel, string partname, out Component2 returnpart)
        {
            Component2 sendToCustomerBodies = default(Component2);

            object swFaceOrPlane = default(object);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies);

            sendToCustomerBodies.Select(true);

            assemblyDoc.FixComponent();
            sendToCustomerBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            object[] splits = sendToCustomerBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + partname;

            ModelDoc2 compModel = default(ModelDoc2);

            compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            bool ret;

            ret = sendToCustomerBodies.SaveVirtualComponent(compName);

            returnpart = sendToCustomerBodies;

            return(sendToCustomerBodies.GetSelectByIDString());
        }
        public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor)
        {
            // Fetch current properties from the selected part(s) (i.e. ChBody in C::E)
            for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++)
            {
                if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS)
                {
                    Component2 swPart      = (Component2)swSelMgr.GetSelectedObject6(isel, -1);
                    ModelDoc2  swPartModel = (ModelDoc2)swPart.GetModelDoc();

                    // fetch SW attribute with Chrono parameters for ChBody
                    SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0);
                    if (myattr == null)
                    {
                        // if not already added to part, create and attach it
                        myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPart, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration);

                        if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid))
                        {
                            System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!");
                        }
                        if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed))
                        {
                            System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!");
                        }
                        if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous))
                        {
                            System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!");
                        }
                        if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted))
                        {
                            System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!");
                        }

                        swPartModel.ForceRebuild3(false); // needed?
                    }

                    Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter(
                                                            "collision_on")).GetDoubleValue()));
                    Set_friction(((Parameter)myattr.GetParameter(
                                      "friction")).GetDoubleValue());
                    Set_rolling_friction(((Parameter)myattr.GetParameter(
                                              "rolling_friction")).GetDoubleValue());
                    Set_spinning_friction(((Parameter)myattr.GetParameter(
                                               "spinning_friction")).GetDoubleValue());
                    Set_restitution(((Parameter)myattr.GetParameter(
                                         "restitution")).GetDoubleValue());
                    Set_collision_envelope(((Parameter)myattr.GetParameter(
                                                "collision_envelope")).GetDoubleValue());
                    Set_collision_margin(((Parameter)myattr.GetParameter(
                                              "collision_margin")).GetDoubleValue());
                    Set_collision_family((int)((Parameter)myattr.GetParameter(
                                                   "collision_family")).GetDoubleValue());



                    // fetch SW attribute with Chrono parameters for ChConveyor

                    /*
                     * SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0);
                     * if (myattr_conv == null)
                     * {
                     *  // if not already added to part, create and attach it
                     *  //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration);
                     * }
                     */
                    /*
                     * // fetch SW attribute with Chrono parameters for ChConveyor (if any!)
                     * SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0);
                     * if (myattr_conveyor != null)
                     * {
                     *  show_conveyor_params = true;
                     *
                     *  Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter(
                     *                  "conveyor_speed")).GetDoubleValue());
                     * }
                     */
                }
            }
        }
        /// Convert a SolidWorks component to Wavefront OBJ mesh
        /// 
        public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress)
        {
            StringBuilder textbuilder = new StringBuilder();
            Body2 swBody = default(Body2);
            object[] vBodies = null;
            object[] vBodiesSolid = null;
            object[] vBodiesSheet = null;
            object vBodyInfo;
            int[] BodiesInfo = null;
            int j = 0;
            ModelDoc2 swModel;

            swModel = (ModelDoc2)swComp.GetModelDoc();

            vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);
            vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo);
            BodiesInfo = (int[])vBodyInfo;

            if (vBodiesSolid != null && vBodiesSheet == null)
                vBodies = vBodiesSolid;

            if (vBodiesSolid == null && vBodiesSheet != null)
                vBodies = vBodiesSheet;

            if (vBodiesSolid != null && vBodiesSheet != null)
                vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray();

            // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);

            if (vBodies != null)
            {
                int iNumBodies = vBodies.Length;
                int iNumSolidBodies = 0;
                int iNumSheetBodies = 0;
                int iNumTesselatedBodies = 0;

                if (iNumBodies >0)
                    asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n";

                int group_vstride = 0;
                int group_nstride = 0;

                // Loop through bodies
                for (j = 0; j <= vBodies.Length - 1; j++)
                {
                    swBody = (Body2)vBodies[j];

                    int nBodyType = (int)swBody.GetType();

                    if (nBodyType == (int)swBodyType_e.swSheetBody)
                        iNumSheetBodies++;

                    if (nBodyType == (int)swBodyType_e.swSolidBody)
                        iNumSolidBodies++;

                    if ((nBodyType == (int)swBodyType_e.swSheetBody ||
                         nBodyType == (int)swBodyType_e.swSolidBody) &&
                         !swBody.Name.StartsWith("COLL.") &&
                         swBody.Visible)
                    {
                        iNumTesselatedBodies++;

                        CultureInfo bz = new CultureInfo("en-BZ");

                        //asciitext += "g body_" + iNumTesselatedBodies + "\n";
                        textbuilder.Append("g body_" + iNumTesselatedBodies + "\n");

                        Face2 swFace = null;
                        Tessellation swTessellation = null;

                        bool bResult = false;

                        // Pass in null so the whole body will be tessellated
                        swTessellation = (Tessellation)swBody.GetTessellation(null);

                        // Set up the Tessellation object
                        swTessellation.NeedFaceFacetMap = true;
                        swTessellation.NeedVertexParams = true;
                        swTessellation.NeedVertexNormal = true;
                        swTessellation.ImprovedQuality = true;

                        // How to handle matches across common edges
                        swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology;

                        // Do it
                        if (swProgress != null)
                            swProgress.UpdateTitle("Exporting (tesselate process) ...");
                        bResult = swTessellation.Tessellate();

                        // Get the number of vertices and facets
                        //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount());
                        //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount());
                        //Debug.Print("Number of facets: " + swTessellation.GetFacetCount());

                        // Now get the facet data per face
                        int[] aFacetIds;
                        int iNumFacetIds;
                        int[] aFinIds;
                        int[] aVertexIds;
                        double[] aNormal;
                        double[] aVertexCoords1;
                        double[] aVertexCoords2;
                        double[] aVertexParams;

                        int numv = swTessellation.GetVertexCount();

                        // Write all vertexes
                        string mline;

                        for (int iv = 0; iv < numv; iv++)
                        {
                            if ((swProgress != null)&&(iv%200==0))
                                swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ...");
                            aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv);
                            mline = "v " +      (aVertexCoords1[0]*ChScale.L).ToString("f6", bz)
                                        + " " + (aVertexCoords1[1]*ChScale.L).ToString("f6", bz)
                                        + " " + (aVertexCoords1[2]*ChScale.L).ToString("f6", bz)
                                        + "\n";
                            textbuilder.Append(mline);
                        }

                        // Write all normals
                        for (int iv = 0; iv < numv; iv++)
                        {
                            if ((swProgress != null) && (iv % 200 == 0))
                                 swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ...");
                            aNormal = (double[])swTessellation.GetVertexNormal(iv);
                            mline = "vn " +     aNormal[0].ToString("f3", bz)
                                        + " " + aNormal[1].ToString("f3", bz)
                                        + " " + aNormal[2].ToString("f3", bz)
                                        + "\n";
                            textbuilder.Append(mline);
                        }
                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets, save two-sided triangles
                            for (int iv = 0; iv < numv; iv++)
                            {
                                if ((swProgress != null) && (iv % 200 == 0))
                                    swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ...");
                                aNormal = (double[])swTessellation.GetVertexNormal(iv);
                                mline = "vn "     + (-aNormal[0]).ToString("f3", bz)
                                            + " " + (-aNormal[1]).ToString("f3", bz)
                                            + " " + (-aNormal[2]).ToString("f3", bz)
                                            + "\n";
                                textbuilder.Append(mline);
                            }

                        // Write all UV (also with '0' as third value, for compatibility with some OBJ reader)
                        if (saveUV)
                            for (int iv = 0; iv < numv; iv++)
                            {
                                if ((swProgress != null) && (iv % 200 == 0))
                                     swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ...");
                                aVertexParams = (double[])swTessellation.GetVertexParams(iv);
                                mline = "vt " + aVertexParams[0].ToString("f4", bz)
                                            + " " + aVertexParams[1].ToString("f4", bz)
                                            + " " + "0"
                                            + "\n";
                                textbuilder.Append(mline);
                            }

                        // Loop over faces
                        swFace = (Face2)swBody.GetFirstFace();
                        while (swFace != null)
                        {
                            aFacetIds = (int[])swTessellation.GetFaceFacets(swFace);

                            iNumFacetIds = aFacetIds.Length;

                            for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++)
                            {
                                if ((swProgress != null) && (iFacetIdIdx % 100 == 0))
                                     swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ...");

                                mline = "f";

                                aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]);

                                // There should always be three fins per facet
                                for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++)
                                {
                                    aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]);

                                    // Three fins per face, two vertexes each fin,
                                    // only the 1st vertex of two is needed (because of sharing)
                                    if (saveUV)
                                        mline += " " + (aVertexIds[0] + group_vstride +1) + "/"
                                                     + (aVertexIds[0] + group_vstride +1) + "/"
                                                     + (aVertexIds[0] + group_nstride +1);
                                    else
                                        mline += " " + (aVertexIds[0] + group_vstride + 1) + "//"
                                                     + (aVertexIds[0] + group_nstride + 1);
                                }

                                mline += "\n";
                                textbuilder.Append(mline);
                            }
                            swFace = (Face2)swFace.GetNextFace();
                        }

                        swFace = (Face2)swBody.GetFirstFace();
                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets, save two-sided triangles
                         while (swFace != null)
                        {
                            aFacetIds = (int[])swTessellation.GetFaceFacets(swFace);

                            iNumFacetIds = aFacetIds.Length;

                            for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++)
                            {
                                if ((swProgress != null) && (iFacetIdIdx % 100 == 0))
                                    swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ...");

                                mline = "f";

                                aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]);

                                for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--)
                                {
                                    aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]);

                                    if (saveUV)
                                        mline += " " + (aVertexIds[0] + group_vstride + 1) + "/"
                                                     + (aVertexIds[0] + group_vstride + 1) + "/"
                                                     + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1);
                                    else
                                        mline += " " + (aVertexIds[0] + group_vstride + 1) + "//"
                                                     + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1);
                                }

                                mline += "\n";
                                textbuilder.Append(mline);
                            }
                            swFace = (Face2)swFace.GetNextFace();
                        }

                        group_vstride += swTessellation.GetVertexCount();
                        group_nstride += swTessellation.GetVertexCount();

                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets: two-sided triangles
                            group_nstride += swTessellation.GetVertexCount();
                    }

                } // end loop on bodies
            } // not null body

            asciitext += textbuilder.ToString();
        }
        // Set Materials
        public void ApplyMaterial(string partPath, string confName, int levelId, SldWorks swapp)
        {
            try
            {
                if (swapp == null)
                {
                    if (partPath == "")
                    {
                        swapp    = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                        _swmodel = swapp.ActiveDoc;
                    }
                    else
                    {
                        swapp = new SldWorks {
                            Visible = true
                        };
                        swapp.OpenDoc6(partPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel, confName, 0, 0);
                        _swmodel = swapp.ActivateDoc(partPath);
                        _swmodel = swapp.ActiveDoc;
                    }
                }
                else
                {
                    if (partPath == "")
                    {
                        _swmodel = swapp.ActiveDoc;
                    }
                    else
                    {
                        //swapp = new SldWorks { Visible = true };
                        swapp.OpenDoc6(partPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel, confName, 0, 0);
                        _swmodel = swapp.ActivateDoc(partPath);
                        _swmodel = swapp.ActiveDoc;
                    }
                }


                // Путь к APPDATA
                var userAppData = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
                // Создаем папку SW-Complex
                var folderAppData = userAppData + "\\" + "SW-Complex";

                //if (File.Exists(folderAppData) == false)
                //{
                Directory.CreateDirectory(folderAppData);
                //}

                swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, folderAppData);     // задаем базы данных материалов
                //swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, "C:\\Program Files\\SW-Complex"); // задаем базы данных материалов

                _swPartDoc = ((PartDoc)(_swmodel));

                var dbMatName = "vents-materials.sldmat";

                var addMatXml = new ToSQL();

                if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    _swmodel.ForceRebuild3(false);
                    Component2 comp        = _swmodel.ISelectionManager.GetSelectedObject3(1);
                    PartDoc    swPartAssem = comp.GetModelDoc();

                    //// удаляем материал
                    //swPartAssem.SetMaterialPropertyName("", "");

                    // применяем материал
                    swPartAssem.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));
                    _swmodel.ClearSelection2(true);
                    _swmodel.ForceRebuild3(false);
                }
                else if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocPART)
                {
                    // Если имя не пустое
                    if (partPath != "")
                    {
                        //// удаляем материал
                        //swPartDoc.SetMaterialPropertyName("", "");

                        // применяем материал
                        _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));

                        _swmodel.ForceRebuild3(false);
                        _swmodel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, 0);
                        swapp.CloseDoc(partPath);
                        swapp.ExitApp();
                        swapp = null;
                    }
                    else
                    {
                        //// удаляем материал
                        //swPartDoc.SetMaterialPropertyName(confName, "");

                        // применяем материал
                        _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));
                    }
                }
            }
            catch (Exception ex)
            {
                //swapp.SendMsgToUser(ex.Message);
                MessageBox.Show(ex.Message + ";" + ex.StackTrace);
                Error = ex.Message;
            }
        }
        public void PythonTraverseComponent_for_visualizationshapes(Component2 swComp, long nLevel, ref string asciitext, int nbody, ref int nvisshape, Component2 chbody_comp)
        {
            CultureInfo bz = new CultureInfo("en-BZ");
            object[] bodies;
            object bodyInfo;
            bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo);

            if (bodies != null)
              if (bodies.Length > 0)
            {
                // Export the component shape to a .OBJ file representing its SW body(s)
                nvisshape += 1;
                string bodyname  = "body_" + nbody;
                string shapename = "body_" + nbody + "_" + nvisshape;
                string obj_filename = this.save_dir_shapes + "\\" + shapename + ".obj";

                ModelDoc2 swCompModel = (ModelDoc2)swComp.GetModelDoc();
                if (!this.saved_shapes.ContainsKey(swCompModel.GetPathName()))
                {
                    try
                    {
                        FileStream ostream = new FileStream(obj_filename, FileMode.Create, FileAccess.ReadWrite);
                        StreamWriter writer = new StreamWriter(ostream); //, new UnicodeEncoding());
                        string asciiobj = "";
                        if (this.swProgress != null)
                            this.swProgress.UpdateTitle("Exporting " + swComp.Name2 + " (tesselate) ...");
                        // Write the OBJ converted visualization shapes:
                        TesselateToObj.Convert(swComp, ref asciiobj, this.checkBox_saveUV.Checked, ref this.swProgress);
                        writer.Write(asciiobj);
                        writer.Flush();
                        ostream.Close();

                        this.saved_shapes.Add(swCompModel.GetPathName(), shapename);
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("Cannot write to file: " + obj_filename);
                    }
                }
                else
                {
                    // reuse the already-saved shape name
                    shapename = (String)saved_shapes[swCompModel.GetPathName()];
                }

                asciitext += String.Format(bz, "\n# Visualization shape \n", bodyname);
                asciitext += String.Format(bz, "{0}_shape = chrono.ChObjShapeFile() \n", shapename);
                asciitext += String.Format(bz, "{0}_shape.SetFilename(shapes_dir +'{0}.obj') \n", shapename);

                object foo = null;
                double[] vMatProperties = (double[])swComp.GetMaterialPropertyValues2((int)swInConfigurationOpts_e.swThisConfiguration, foo);

                if (vMatProperties != null)
                    if (vMatProperties[0] != -1)
                    {
                        asciitext += String.Format(bz, "{0}_shape.SetColor(chrono.ChColor({1},{2},{3})) \n", shapename,
                            vMatProperties[0], vMatProperties[1], vMatProperties[2]);
                        asciitext += String.Format(bz, "{0}_shape.SetFading({1}) \n", shapename, vMatProperties[7]);
                    }

                MathTransform absframe_chbody = chbody_comp.GetTotalTransform(true);
                MathTransform absframe_shape  = swComp.GetTotalTransform(true);
                MathTransform absframe_chbody_inv = absframe_chbody.IInverse();
                MathTransform relframe_shape = absframe_shape.IMultiply(absframe_chbody_inv);  // row-ordered transf. -> reverse mult.order!
                double[] amatr = (double[])relframe_shape.ArrayData;
                double[] quat  = GetQuaternionFromMatrix(ref relframe_shape);

                asciitext += String.Format(bz, "{0}_level = chrono.ChAssetLevel() \n", shapename);
                asciitext += String.Format(bz, "{0}_level.GetFrame().SetPos(chrono.ChVectorD({1},{2},{3})) \n", shapename,
                    amatr[9] *ChScale.L,
                    amatr[10]*ChScale.L,
                    amatr[11]*ChScale.L);
                asciitext += String.Format(bz, "{0}_level.GetFrame().SetRot(chrono.ChQuaternionD({1},{2},{3},{4})) \n", shapename, quat[0], quat[1], quat[2], quat[3]);
                asciitext += String.Format(bz, "{0}_level.GetAssets().push_back({0}_shape) \n", shapename);

                asciitext += String.Format(bz, "{0}.GetAssets().push_back({1}_level) \n", bodyname, shapename);

            }

            // Recursive scan of subcomponents

            Component2 swChildComp;
            object[] vChildComp = (object[])swComp.GetChildren();

            for (long i = 0; i < vChildComp.Length; i++)
            {
                swChildComp = (Component2)vChildComp[i];

                if (swChildComp.Visible == (int)swComponentVisibilityState_e.swComponentVisible)
                    PythonTraverseComponent_for_visualizationshapes(swChildComp, nLevel + 1, ref asciitext, nbody, ref nvisshape, chbody_comp);
            }
        }
Exemple #12
0
        private void AddSuffix(LinkedList<CopiedFileNames> filesNames, Component2 swAddedComp, bool isAsync)
        {
            if (isAsync)
                needWait = true;

            var thisModel = (ModelDoc2)swAddedComp.GetModelDoc();

            if (thisModel != null)
            {
                thisModel.ReloadOrReplace(false, thisModel.GetPathName(), true);
                if (isAsync)
                {
                    lock (workerLocker2)
                        Monitor.PulseAll(workerLocker2);
                }

                Decors.AddModelToList(this, thisModel);
                string fileName;
                if (ExistingFileDictionaryWithMdb(out fileName))
                {
                    var strArr = File.ReadAllLines(fileName).ToList();
                    strArr.Add(thisModel.GetPathName().Substring(GetRootFolder(SwModel).Length));
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    File.WriteAllLines(fileName, strArr);
                    File.SetAttributes(fileName, FileAttributes.Hidden);
                }
                #region ���������� �������� � ��������

                try
                {
                    if (filesNames != null)
                    {
                        var dictNames = new Dictionary<string, string>();
                        foreach (var copiedFileNamese in filesNames)
                        {
                            if (
                                !dictNames.ContainsKey(Path.GetFileName(copiedFileNamese.OldName)))
                                dictNames.Add(Path.GetFileName(copiedFileNamese.OldName),
                                              Path.GetFileName(copiedFileNamese.NewName));
                        }

                        SwDMApplication swDocMgr = GetSwDmApp();

                        foreach (var copiedFileNamese in filesNames)
                        {
                            SwDmDocumentOpenError oe;

                            var swDoc = swDocMgr.GetDocument(copiedFileNamese.NewName,
                                                             SwDmDocumentType.
                                                                 swDmDocumentUnknown
                                                             , true, out oe);
                            if (swDoc != null)
                            {
                                var names = (string[])swDoc.GetCustomPropertyNames();
                                foreach (var name in names)
                                {
                                    SwDmCustomInfoType swDmCstInfoType;
                                    string valueOfName = swDoc.GetCustomProperty(name, out swDmCstInfoType);
                                    string lowValOfName = valueOfName.ToLower();

                                    if (lowValOfName.Contains("@") &&
                                        !lowValOfName.Contains("#") &&
                                        (lowValOfName.Contains(".sld")))
                                    {
                                        foreach (var dictName in dictNames)
                                        {
                                            string lowDictName = dictName.Key.ToLower();
                                            if (lowValOfName.Contains(lowDictName))
                                            {
                                                string oldModName =
                                                    valueOfName.Substring(
                                                        valueOfName.IndexOf(
                                                            dictName.Key.Split('.').First()),
                                                        dictName.Key.Length);

                                                string newStrVal =
                                                    valueOfName.Replace(oldModName,
                                                                        dictName.Value);
                                                ModelDoc2 outMod;

                                                if (GetModelByName(thisModel,
                                                                   Path.GetFileName(
                                                                       swDoc.FullName), true,
                                                                   out outMod))
                                                {
                                                    SetModelProperty(outMod, name, "",
                                                                     swCustomInfoType_e.
                                                                         swCustomInfoText,
                                                                     newStrVal);
                                                    outMod.Save();
                                                }
                                            }
                                        }
                                    }
                                }
                                swDoc.CloseDoc();
                            }
                        }
                    }
                }
                catch
                {
                }

                #endregion

                if (Properties.Settings.Default.AutoSaveDrawings)
                {

                    if (Properties.Settings.Default.ShowRPDBefore)
                    {
                        _frmPrm.SwAsmDoc.NewSelectionNotify -= _frmPrm.NewSelection;
                        bool select = swAddedComp.Select(false);
                        _frmPrm.SwAsmDoc.NewSelectionNotify += _frmPrm.NewSelection;
                        if (select)
                            CopyDrawings2(true, true, null);
                    }
                    else
                    {
                        if (swAddedComp.Select(false))
                            CopyDrawings2(true, true, null);
                    }

                }
                //thisModel.ReloadOrReplace(false, thisModel.GetPathName(), true);
                RebuildEquation(swAddedComp);

                if (Properties.Settings.Default.AutoRecalculateOnAdd)
                {
                    try
                    {
                        RecalculateModel(thisModel);
                    }
                    catch
                    {
                    }
                }

                // ��������, ��� �� ������ ������ ������ � ������ ������ ��� ������ � �� ������ �� ��������
            }
            if (Properties.Settings.Default.AutoCutOff) CutOff();
            if (Properties.Settings.Default.AutoRecalculateOnAdd) SwModel.EditRebuild3();

            needWait = false;
            //Logging.Log.Instance.TraceStop(startTime, "Stop");
            if (isAsync)
            {
                lock (workerLocker)
                    Monitor.PulseAll(workerLocker);
            }
        }
Exemple #13
0
        public bool GetComponents(Component2 inParseComponent, LinkedList<Component2> outComponents,
            bool isGetSubComponents, bool isRecursive)
        {
            bool ret = false;

            try
            {
                if (!isRecursive)
                    outComponents.Clear();

                if (inParseComponent != null)
                {
                    var subComponents = (object[])inParseComponent.GetChildren();

                    // GetChildren ������ �� ���������� �������������. ���������� ����������� GetComponents��
                    if (subComponents != null && subComponents.Length == 0)
                    {
                        var swCompModel = (ModelDoc2)inParseComponent.GetModelDoc();
                        var tt = ((AssemblyDoc)swCompModel).GetComponents(true);
                        if (tt.Length != 0)
                            subComponents = tt;
                    }

                    if (subComponents != null)
                        foreach (Component2 subSwComp in subComponents)
                        {
                            outComponents.AddLast(subSwComp);

                            if (isGetSubComponents)
                                GetComponents(subSwComp, outComponents, true, true);
                        }
                }
                ret = true;
            }
            catch { }
            return ret;
        }
Exemple #14
0
        public static void Change_Color(ModelDoc2 swModel, string name, string color)
        {
            AssemblyDoc swAssembly = null;

            Component2 swComp       = null;
            ModelDoc2  swCompDoc    = null;
            string     compare_name = "";

            string[] Componentsubstring;
            bool     boolstatus = false;

            try
            {
                if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    swModel.ClearSelection2(true);
                    //  boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    //  SelectionMgr SwSelMgr = swModel.SelectionManager;
                    swAssembly = (AssemblyDoc)swModel;
                    var Components = swAssembly.GetComponents(false);
                    // MessageBox.Show(Components.Length.ToString());
                    for (int i = 0; i < Components.Length; i++)
                    {
                        //swComp = swAssembly.GetComponentByName(name);
                        swComp = Components[i];
                        //  MessageBox.Show(swComp.Name2);
                        if (swComp != null)
                        {
                            if (swComp.Name2.Contains(name))
                            {
                                var vMatProps = swComp.MaterialPropertyValues;
                                if (vMatProps == null)
                                {
                                    swCompDoc = swComp.GetModelDoc();
                                    if (swCompDoc == null)
                                    {
                                        return;
                                    }
                                    vMatProps = swCompDoc.MaterialPropertyValues;
                                }
                                if (color != "")
                                {
                                    switch (color)
                                    {
                                    case "Green":
                                        vMatProps[0] = 0;      //Red
                                        vMatProps[1] = 1;      //Green
                                        vMatProps[2] = 0;      //Blue
                                        break;

                                    case "Blue":
                                        vMatProps[0] = 0;      //Red
                                        vMatProps[1] = 0;      //Green
                                        vMatProps[2] = 1;      //Blue
                                        break;

                                    case "Red":
                                        vMatProps[0] = 1;      //Red
                                        vMatProps[1] = 0;      //Green
                                        vMatProps[2] = 0;      //Blue
                                        break;

                                    default:
                                        vMatProps[0] = 1;     //Red
                                        vMatProps[1] = 0;     //Green
                                        vMatProps[2] = 0;     //Blue
                                        break;
                                    }
                                }

                                swComp.MaterialPropertyValues = vMatProps;
                                swModel.ClearSelection2(true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }

            //  boolstatus = swDoc.Extension.SelectByID2("195599_GRLA_F_1_8_QS_8_D-3@toolbox-tutorial", "COMPONENT", 0, 0, 0, false, 0, null, 0);
        }
        /// <summary>
        /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样
        /// </summary>
        /// <param name="sendTocustomer"></param>
        /// <param name="localModel"></param>
        /// <returns></returns>
        public bool CheckTwoParts(string sendTocustomer, string localModel)
        {
            bool different1 = false;

            bool different2 = false;

            swApp = ConnectToSolidWorks();
            // swApp = ConnectToSolidWorks();

            //加载参考关系零件
            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly);

            //后台模式 前台不显示界面

            swApp.EnableBackgroundProcessing = true;

            //禁止记录文件路径
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true);

            swApp.OpenDoc(localModel, 1);

            swApp.OpenDoc(sendTocustomer, 1);

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString();

            string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly);

            AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0);

            Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0);
            Component2 insertComponentLocal          = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0);

            string sendSelect  = insertComponentSendtoCustomer.GetSelectByIDString();
            string localSelect = insertComponentLocal.GetSelectByIDString();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);
            int  longstatus;

            Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.SaveAs(LocalPath + @"\TopCheck.sldasm");

            //不显示特征树
            //swModel.Extension.HideFeatureManager(true);

            swModel.ClearSelection2(true);
            //swModel.FeatureManager.ViewFeatures = false;

            //FeatureManager featureManager = swModel.FeatureManager;

            //禁用特征树
            //featureManager.EnableFeatureTree = false;

            // swModel.FeatureManager.EnableFeatureTreeWindow = false;

            #region first join

            Component2        sendToCustomerBodies     = default(Component2);
            List <Component2> sendToCustomerBodiesList = new List <Component2>();

            object swFaceOrPlane = default(object);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies);

            sendToCustomerBodies.Select(true);

            assemblyDoc.FixComponent();
            sendToCustomerBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            object[] splits = sendToCustomerBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1";

            ModelDoc2 compModel = default(ModelDoc2);
            compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            bool ret;

            ret = sendToCustomerBodies.SaveVirtualComponent(compName);

            sendToCustomerBodiesList.Add(sendToCustomerBodies);

            insertComponentSendtoCustomer.Select(false);

            swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesCustomer = new List <string>();

            PartDoc swPart = null;
            object  vBody;
            swPart = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr = null;
            Body2    swBody   = default(Body2);

            MathTransform swMathTrans = null;
            vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr)
                {
                    vBody  = vBody_loopVariable;
                    swBody = (Body2)vBody;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    //Debug.Print("Body--> " + swBody.Name + " " + "");

                    bodyNamesCustomer.Add(swBody.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1);

            if (bodyNamesCustomer.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesCustomer.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart);
                    sendToCustomerBodiesList.Add(returnpart);

                    OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);
            Feature theFeature;

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different1 = true;
            //    //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}
            //sendToCustomerBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion first join

            #region sercond join2

            Component2        localBodies     = default(Component2);
            List <Component2> LocalBodiesList = new List <Component2>();
            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies);

            localBodies.Select(true);

            assemblyDoc.FixComponent();
            localBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = localBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)localBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = localBodies.SaveVirtualComponent(compName);
            LocalBodiesList.Add(localBodies);
            insertComponentLocal.Select(false);

            swModel = (ModelDoc2)localBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesLocal = new List <string>();

            PartDoc swPart2 = null;
            object  vBody2;
            swPart2 = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr2 = null;
            Body2    swBody2   = default(Body2);

            MathTransform swMathTrans2 = null;
            vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr2 != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr2)
                {
                    vBody2  = vBody_loopVariable;
                    swBody2 = (Body2)vBody2;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody2.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    bodyNamesLocal.Add(swBody2.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2);

            if (bodyNamesLocal.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesLocal.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart);
                    LocalBodiesList.Add(returnpart);
                    OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

            //theFeature = swModel.FeatureByPositionReverse(0);

            //swModel = (ModelDoc2)localBodies.GetModelDoc2();

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different2 = true;
            //    //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}

            //localBodies.Select(true);

            //assemblyDoc.EditAssembly();

            #endregion sercond join2

            #region joinPartPublic

            Component2 publicBodies = default(Component2);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies);

            publicBodies.Select(true);

            assemblyDoc.FixComponent();
            publicBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = publicBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)publicBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = publicBodies.SaveVirtualComponent(compName);

            swModel.ClearSelection();

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }

            publicBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion joinPartPublic

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);
                setColour(Color.Red);
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);
                setColour(Color.Blue);
            }

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ClearSelection2(true);

            insertComponentLocal.Select(false);
            insertComponentSendtoCustomer.Select(true);
            swModel.HideComponent2();
            swModel.ClearSelection2(true);

            publicBodies.Select(false);
            assemblyDoc.SetComponentTransparent(true);
            setColour(Color.Green);
            swModel.EditRebuild3();
            swModel.Save();

            swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0);

            swApp.CloseDoc("TopCheck.sldasm");
            swApp.CloseAllDocuments(true);
            swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1);
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ShowNamedView2("*Isometric", 7);

            swModel.ViewZoomtofit2();

            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false);
            try
            {
                System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm");
                System.IO.File.Delete(LocalPath + @"\localBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt");
            }
            catch (Exception)
            {
            }

            //第二次反向剪切

            swApp.CloseDoc(sendTocustomer);
            swApp.CloseDoc(localModel);

            swModel.FeatureManager.EnableFeatureTree = true;

            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2);

            if (different1 == false && different2 == false)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        public void StoreToSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor)
        {
            System.Windows.Forms.MessageBox.Show("StoreToSelection()");

            // If user pressed OK, apply settings to all selected parts (i.e. ChBody in C::E):
            for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++)
            {
                if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS)
                {
                    Component2 swPart      = (Component2)swSelMgr.GetSelectedObject6(isel, -1);
                    ModelDoc2  swPartModel = (ModelDoc2)swPart.GetModelDoc();

                    // fetch SW attribute with Chrono parameters for ChBody
                    SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0);
                    if (myattr == null)
                    {
                        // if not already added to part, create and attach it
                        myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPart, "Chrono ChBody data", 0, (int)swInConfigurationOpts_e.swThisConfiguration);
                        swPartModel.ForceRebuild3(false); // needed?
                        if (myattr == null)
                        {
                            System.Windows.Forms.MessageBox.Show("myattr null in setting!!");
                        }
                    }

                    ((Parameter)myattr.GetParameter("collision_on")).SetDoubleValue2(
                        Convert.ToDouble(m_collide), (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("friction")).SetDoubleValue2(
                        m_friction, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("rolling_friction")).SetDoubleValue2(
                        m_rolling_friction, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("spinning_friction")).SetDoubleValue2(
                        m_spinning_friction, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("restitution")).SetDoubleValue2(
                        m_restitution, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("collision_margin")).SetDoubleValue2(
                        m_collision_margin, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("collision_envelope")).SetDoubleValue2(
                        m_collision_envelope, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    ((Parameter)myattr.GetParameter("collision_family")).SetDoubleValue2(
                        (double)m_collision_family, (int)swInConfigurationOpts_e.swThisConfiguration, "");

                    /*
                     * // fetch SW attribute with Chrono parameters for ChConveyor
                     * SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0);
                     * if (myattr_conveyor == null)
                     * {
                     *  // if not already added to part, create and attach it
                     *  myattr_conveyor = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono ChConveyor data", 0, (int)swInConfigurationOpts_e.swThisConfiguration);
                     *  if (myattr_conveyor == null)
                     *      System.Windows.Forms.MessageBox.Show("myattr null in setting!!");
                     * }
                     *
                     * ((Parameter)myattr_conveyor.GetParameter("conveyor_speed")).SetDoubleValue2(
                     *            m_conveyor_speed, (int)swInConfigurationOpts_e.swThisConfiguration, "");
                     */
                }
            }
        }
Exemple #17
0
        /// Convert a SolidWorks component to Wavefront OBJ mesh
        ///
        public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress)
        {
            StringBuilder textbuilder = new StringBuilder();
            Body2         swBody      = default(Body2);

            object[] vBodies      = null;
            object[] vBodiesSolid = null;
            object[] vBodiesSheet = null;
            object   vBodyInfo;

            int[]     BodiesInfo = null;
            int       j          = 0;
            ModelDoc2 swModel;


            swModel = (ModelDoc2)swComp.GetModelDoc();

            vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);
            vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo);
            BodiesInfo   = (int[])vBodyInfo;

            if (vBodiesSolid != null && vBodiesSheet == null)
            {
                vBodies = vBodiesSolid;
            }

            if (vBodiesSolid == null && vBodiesSheet != null)
            {
                vBodies = vBodiesSheet;
            }

            if (vBodiesSolid != null && vBodiesSheet != null)
            {
                vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray();
            }

            // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);


            if (vBodies != null)
            {
                int iNumBodies           = vBodies.Length;
                int iNumSolidBodies      = 0;
                int iNumSheetBodies      = 0;
                int iNumTesselatedBodies = 0;


                if (iNumBodies > 0)
                {
                    asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n";
                }

                int group_vstride = 0;
                int group_nstride = 0;

                // Loop through bodies
                for (j = 0; j <= vBodies.Length - 1; j++)
                {
                    swBody = (Body2)vBodies[j];

                    int nBodyType = (int)swBody.GetType();

                    if (nBodyType == (int)swBodyType_e.swSheetBody)
                    {
                        iNumSheetBodies++;
                    }

                    if (nBodyType == (int)swBodyType_e.swSolidBody)
                    {
                        iNumSolidBodies++;
                    }

                    if ((nBodyType == (int)swBodyType_e.swSheetBody ||
                         nBodyType == (int)swBodyType_e.swSolidBody) &&
                        !swBody.Name.StartsWith("COLL.") &&
                        swBody.Visible)
                    {
                        iNumTesselatedBodies++;

                        CultureInfo bz = new CultureInfo("en-BZ");

                        //asciitext += "g body_" + iNumTesselatedBodies + "\n";
                        textbuilder.Append("g body_" + iNumTesselatedBodies + "\n");

                        Face2        swFace         = null;
                        Tessellation swTessellation = null;

                        bool bResult = false;

                        // Pass in null so the whole body will be tessellated
                        swTessellation = (Tessellation)swBody.GetTessellation(null);

                        // Set up the Tessellation object
                        swTessellation.NeedFaceFacetMap = true;
                        swTessellation.NeedVertexParams = true;
                        swTessellation.NeedVertexNormal = true;
                        swTessellation.ImprovedQuality  = true;

                        // How to handle matches across common edges
                        swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology;

                        // Do it
                        if (swProgress != null)
                        {
                            swProgress.UpdateTitle("Exporting (tesselate process) ...");
                        }
                        bResult = swTessellation.Tessellate();

                        // Get the number of vertices and facets
                        //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount());
                        //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount());
                        //Debug.Print("Number of facets: " + swTessellation.GetFacetCount());

                        // Now get the facet data per face
                        int[]    aFacetIds;
                        int      iNumFacetIds;
                        int[]    aFinIds;
                        int[]    aVertexIds;
                        double[] aNormal;
                        double[] aVertexCoords1;
                        double[] aVertexCoords2;
                        double[] aVertexParams;

                        int numv = swTessellation.GetVertexCount();

                        // Write all vertexes
                        string mline;

                        for (int iv = 0; iv < numv; iv++)
                        {
                            if ((swProgress != null) && (iv % 200 == 0))
                            {
                                swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ...");
                            }
                            aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv);
                            mline          = "v " + (aVertexCoords1[0] * ChScale.L).ToString("f6", bz)
                                             + " " + (aVertexCoords1[1] * ChScale.L).ToString("f6", bz)
                                             + " " + (aVertexCoords1[2] * ChScale.L).ToString("f6", bz)
                                             + "\n";
                            textbuilder.Append(mline);
                        }

                        // Write all normals
                        for (int iv = 0; iv < numv; iv++)
                        {
                            if ((swProgress != null) && (iv % 200 == 0))
                            {
                                swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ...");
                            }
                            aNormal = (double[])swTessellation.GetVertexNormal(iv);
                            mline   = "vn " + aNormal[0].ToString("f3", bz)
                                      + " " + aNormal[1].ToString("f3", bz)
                                      + " " + aNormal[2].ToString("f3", bz)
                                      + "\n";
                            textbuilder.Append(mline);
                        }
                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets, save two-sided triangles
                        {
                            for (int iv = 0; iv < numv; iv++)
                            {
                                if ((swProgress != null) && (iv % 200 == 0))
                                {
                                    swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ...");
                                }
                                aNormal = (double[])swTessellation.GetVertexNormal(iv);
                                mline   = "vn " + (-aNormal[0]).ToString("f3", bz)
                                          + " " + (-aNormal[1]).ToString("f3", bz)
                                          + " " + (-aNormal[2]).ToString("f3", bz)
                                          + "\n";
                                textbuilder.Append(mline);
                            }
                        }

                        // Write all UV (also with '0' as third value, for compatibility with some OBJ reader)
                        if (saveUV)
                        {
                            for (int iv = 0; iv < numv; iv++)
                            {
                                if ((swProgress != null) && (iv % 200 == 0))
                                {
                                    swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ...");
                                }
                                aVertexParams = (double[])swTessellation.GetVertexParams(iv);
                                mline         = "vt " + aVertexParams[0].ToString("f4", bz)
                                                + " " + aVertexParams[1].ToString("f4", bz)
                                                + " " + "0"
                                                + "\n";
                                textbuilder.Append(mline);
                            }
                        }


                        // Loop over faces
                        swFace = (Face2)swBody.GetFirstFace();
                        while (swFace != null)
                        {
                            aFacetIds = (int[])swTessellation.GetFaceFacets(swFace);

                            iNumFacetIds = aFacetIds.Length;

                            for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++)
                            {
                                if ((swProgress != null) && (iFacetIdIdx % 100 == 0))
                                {
                                    swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ...");
                                }

                                mline = "f";

                                aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]);

                                // There should always be three fins per facet
                                for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++)
                                {
                                    aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]);

                                    // Three fins per face, two vertexes each fin,
                                    // only the 1st vertex of two is needed (because of sharing)
                                    if (saveUV)
                                    {
                                        mline += " " + (aVertexIds[0] + group_vstride + 1) + "/"
                                                 + (aVertexIds[0] + group_vstride + 1) + "/"
                                                 + (aVertexIds[0] + group_nstride + 1);
                                    }
                                    else
                                    {
                                        mline += " " + (aVertexIds[0] + group_vstride + 1) + "//"
                                                 + (aVertexIds[0] + group_nstride + 1);
                                    }
                                }

                                mline += "\n";
                                textbuilder.Append(mline);
                            }
                            swFace = (Face2)swFace.GetNextFace();
                        }

                        swFace = (Face2)swBody.GetFirstFace();
                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets, save two-sided triangles
                        {
                            while (swFace != null)
                            {
                                aFacetIds = (int[])swTessellation.GetFaceFacets(swFace);

                                iNumFacetIds = aFacetIds.Length;

                                for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++)
                                {
                                    if ((swProgress != null) && (iFacetIdIdx % 100 == 0))
                                    {
                                        swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ...");
                                    }

                                    mline = "f";

                                    aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]);

                                    for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--)
                                    {
                                        aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]);

                                        if (saveUV)
                                        {
                                            mline += " " + (aVertexIds[0] + group_vstride + 1) + "/"
                                                     + (aVertexIds[0] + group_vstride + 1) + "/"
                                                     + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1);
                                        }
                                        else
                                        {
                                            mline += " " + (aVertexIds[0] + group_vstride + 1) + "//"
                                                     + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1);
                                        }
                                    }

                                    mline += "\n";
                                    textbuilder.Append(mline);
                                }
                                swFace = (Face2)swFace.GetNextFace();
                            }
                        }

                        group_vstride += swTessellation.GetVertexCount();
                        group_nstride += swTessellation.GetVertexCount();

                        if (nBodyType == (int)swBodyType_e.swSheetBody)  // for sheets: two-sided triangles
                        {
                            group_nstride += swTessellation.GetVertexCount();
                        }
                    }
                } // end loop on bodies
            }     // not null body

            asciitext += textbuilder.ToString();
        }
Exemple #18
0
        private bool GetComponentModel(ModelDoc2 swModel, Component2 inComp, out ModelDoc2 swCompModel, out string modelFileName)
        {
            int i = 0;
            modelFileName = "";
            do
            {
                var compState = (swComponentSuppressionState_e)inComp.GetSuppression();

                if (compState.ToString() == "swComponentSuppressed")
                    inComp.SetSuppression2((int)swComponentSuppressionState_e.swComponentFullyResolved);

                swCompModel = (ModelDoc2)inComp.GetModelDoc();

                if (swCompModel == null)
                {
                    string newModelPath = CheckIsCompInOurLib(inComp.GetPathName());
                    if (inComp.Select(false))
                    {
                        ((AssemblyDoc)swModel).ReplaceComponents(newModelPath, "", true, true);
                        //((AssemblyDoc) swModel).ComponentReload();
                        swCompModel = inComp.IGetModelDoc();
                        //((AssemblyDoc) swModel).OpenCompFile();
                        //��� �������������� ��������� ���������� OpenCompFile �� ��������!
                        if (((ModelDoc2)_iSwApp.ActiveDoc).GetPathName() != swModel.GetPathName())
                            swCompModel = (ModelDoc2)_iSwApp.ActiveDoc;
                    }
                }
                i++;
            } while (swCompModel == null && i < 10);

            if (swCompModel != null)
                modelFileName = swCompModel.GetPathName();
            else
            {
                MessageBox.Show(@"��������� " + inComp.Name + @"�� ���������!", MyTitle, MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                return false;
            }
            return true;
        }
Exemple #19
0
        //k - ���������� ����������� ��� ������������
        private void SaveAsComponent(ModelDoc2 swModel, Component2 inComp, bool isFirstLevel, LinkedList<CopiedFileNames> filesNames, int k)
        {
            string offset = string.Empty;
            //for (int i = 0; i < k; i++)
            //    offset += "   ";
            try
            {
                string strSubCompOldFileNameFromComponent = inComp.GetPathName();
                if (strSubCompOldFileNameFromComponent == "")
                {
                    var swCompModel = (ModelDoc2)inComp.GetModelDoc();
                    if (swCompModel != null)
                        strSubCompOldFileNameFromComponent = swCompModel.GetPathName();
                    else
                        return;
                }

                bool isModelAlreadyReplaced =
                    filesNames.Any(oldfile => oldfile.OldName == strSubCompOldFileNameFromComponent);

                if (!isModelAlreadyReplaced)
                {
                    ModelDoc2 swCompModel;
                    string strSubCompOldFileNameFromModel;
                    if (GetComponentModel(swModel, inComp, out swCompModel, out strSubCompOldFileNameFromModel))
                    {

                        bool isAuxiliary = (swCompModel.get_CustomInfo2("", "Auxiliary") == "Yes");
                        bool isAccessory = (swCompModel.get_CustomInfo2("", "Accessories") == "Yes");

                        string strSubCompNewFileName;
                        if (GetComponentNewFileName(swModel, isAuxiliary, isAccessory,
                                                    isFirstLevel, strSubCompOldFileNameFromModel,
                                                    out strSubCompNewFileName))
                        {

                            bool isCopyError = false;

                            try
                            {
                                if (!File.Exists(strSubCompNewFileName)) //���������
                                {
                                    File.Copy(strSubCompOldFileNameFromModel, strSubCompNewFileName, true);

                                }
                            }
                            catch (Exception)
                            {
                                MessageBox.Show(@"�� ������� ��������� ���� " + strSubCompNewFileName,
                                                MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                isCopyError = true;
                            }
                            if (!isCopyError)
                            {
                                filesNames.AddLast(new CopiedFileNames(strSubCompOldFileNameFromComponent,
                                                                       strSubCompNewFileName));
                                File.SetAttributes(strSubCompNewFileName, FileAttributes.Normal);

                                var subComps = new LinkedList<Component2>();
                                if (GetComponents(inComp, subComps, false, false))
                                {
                                    foreach (Component2 subcmp in subComps)
                                    {
                                        SaveAsComponent(swModel, subcmp, false, filesNames, k + 1);
                                    }

                                }

                                SwDmDocumentOpenError oe;

                                SwDMApplication swDocMgr = GetSwDmApp();
                                var swDoc = (SwDMDocument8)swDocMgr.GetDocument(strSubCompNewFileName,
                                                                                 SwDmDocumentType.swDmDocumentAssembly,
                                                                                 false, out oe);

                                if (swDoc != null)
                                {
                                    SwDMSearchOption src = swDocMgr.GetSearchOptionObject();
                                    src.SearchFilters = 255;

                                    object brokenRefVar;
                                    var varRef = (object[])swDoc.GetAllExternalReferences2(src, out brokenRefVar);

                                    if (varRef != null)
                                    {
                                        foreach (object t in varRef)
                                        {
                                            var strRef = (string)t;
                                            string strRefFileName = Path.GetFileName(strRef);
                                            string strNewRef = "";
                                            foreach (CopiedFileNames oldfile in filesNames)
                                            {
                                                if (Path.GetFileName(oldfile.OldName).ToLower() == strRefFileName.ToLower())
                                                {
                                                    strNewRef = oldfile.NewName;
                                                    break;
                                                }
                                            }
                                            if (strNewRef != "")
                                                swDoc.ReplaceReference(strRef, strNewRef);
                                        }
                                    }
                                    swDoc.Save();
                                    swDoc.CloseDoc();
                                }

                                if (isFirstLevel)
                                {
                                    var outList1 = new LinkedList<Component2>();

                                    if (inComp.Select(false))
                                        ((AssemblyDoc)swModel).ReplaceComponents(strSubCompNewFileName, "", false, true);
                                    if (inComp.Select(false))
                                        ((AssemblyDoc)swModel).ComponentReload();

                                    if (GetComponents(inComp, outList1, true, false))
                                    {
                                        foreach (var component in outList1)
                                        {
                                            var model = component.IGetModelDoc();
                                            if (model != null && model.GetConfigurationCount() > 1)
                                            {
                                                int err = 0, wrn = 0;
                                                var mod = SwApp.OpenDoc6(model.GetPathName(),
                                                                         (int)swDocumentTypes_e.swDocPART,
                                                                         0, "", ref err, ref wrn);
                                                if (mod != null)
                                                {

                                                    mod.ShowConfiguration2(component.ReferencedConfiguration);
                                                    mod.Save();
                                                    SwApp.CloseDoc(mod.GetPathName());

                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Log.Instance.Fatal(e.Message + "SaveAsComponent()");
                MessageBox.Show(e.Message, MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return;
        }
Exemple #20
0
        public void TableTopProcess(Component2 swAddedComp)
        {
            var mates = swAddedComp.GetMates();
            Component2 firstComponent = null;
            var swAddedCompModel = (ModelDoc2)swAddedComp.GetModelDoc();
            bool? isLeft = null;
            if (swAddedCompModel.GetCustomInfoValue("", "KitchenType").Contains("левая"))
                isLeft = true;
            else if (swAddedCompModel.GetCustomInfoValue("", "KitchenType").Contains("правая"))
                isLeft = false;
            if (isLeft == null)
                return;
            if (mates != null)
            {
                foreach (var mate in mates)
                {
                    if (mate is Mate2)
                    {
                        var spec = (Mate2)mate;
                        int mec = spec.GetMateEntityCount();
                        if (mec > 1)
                        {
                            for (int ik = 0; ik < mec; ik++)
                            {
                                MateEntity2 me = spec.MateEntity(ik);
                                if (me.ReferenceComponent.Name.Contains(swAddedComp.Name))
                                {
                                    string firstComp = spec.MateEntity(0).ReferenceComponent.Name.Split('/')[0];
                                    swAddin.GetComponentByName(RootModel, firstComp, false, out firstComponent);
                                    break;

                                }
                            }
                        }
                    }
                }
            }
            if (firstComponent != null)
            {
                //привязать...
                swAddin.AddMate(RootModel, firstComponent.FeatureByName("#swrfЗадняя"), swAddedComp.FeatureByName("#swrfЗадняя"), true);
            }

            bool status;
            var swComponents = new LinkedList<Component2>();

            if (swAddin.GetComponents(swRootComponent, swComponents, false, false))
            {

                double[] origBox = swAddedComp.GetBox(true, true);
                double origaverx = Math.Min(origBox[3], origBox[0]) +
                                    Math.Abs(origBox[3] - origBox[0]) / 2;
                double origaverz = Math.Min(origBox[5], origBox[2]) +
                                    Math.Abs(origBox[5] - origBox[2]) / 2;

                var swCompModel = (ModelDoc2)firstComponent.GetModelDoc();
                bool isAnglePartFirst = false, isUpPartfirst = false, isTabletopFirst = false;
                if (swCompModel != null)
                    GetTypeProperty(swCompModel.GetCustomInfoValue("", "KitchenType"), out isAnglePartFirst, out isUpPartfirst, out isTabletopFirst);
                if (isTabletopFirst || isUpPartfirst)
                    return;
                string tmp = (bool)isLeft ? "#swrfЛевая" : "#swrfПравая";
                if (isAnglePartFirst)
                    swAddin.AddMate(RootModel, firstComponent.FeatureByName("#swrfЗадняя2"), swAddedComp.FeatureByName(tmp), true);
                else
                    swAddin.AddMate(RootModel, firstComponent.FeatureByName(tmp), swAddedComp.FeatureByName(tmp), true);

                InfoForMate maxDistance = FindMinTopTable(swComponents, swAddedComp, isLeft);
                InfoForMate maxDistance3 = FindMaxPlate(swComponents, swAddedComp, firstComponent, origaverx, origaverz, isAnglePartFirst, isLeft);

                if (maxDistance.planeDist != null && maxDistance.planeSource != null && maxDistance3.distance > maxDistance.distance)//&& maxDistance3.planeSource.Name == maxDistance.planeSource.Name)
                {
                    swModel.ClearSelection();
                    InfoForMate maxDistance2 = new InfoForMate(double.MinValue, null, null);
                    string tt = isAnglePartFirst ? "#swrfЗадняя2" : plateleft;
                    status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", tt, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0);
                    maxDistance.planeDist.Select(true);
                    measure.Calculate(null);
                    if (measure.IsParallel && maxDistance2.distance < measure.Distance)
                        maxDistance2 = new InfoForMate(measure.Distance, firstComponent.FeatureByName(tt), null);
                    swModel.ClearSelection();
                    status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", plateright, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0);
                    maxDistance.planeDist.Select(true);
                    measure.Calculate(null);
                    if (measure.IsParallel && maxDistance2.distance < measure.Distance)
                        maxDistance2 = new InfoForMate(measure.Distance, firstComponent.FeatureByName(plateright), null);
                    //if (maxDistance2.planeDist!=null)
                    //    swAddin.AddMate(swModel, maxDistance2.planeDist, maxDistance.planeSource, true);//distToTopTable = new InfoForMate(maxDistance.distance, maxDistance2.planeDist, maxDistance.planeSource);//
                    swModel.ClearSelection();
                    maxDistance.planeDist.Select(false);
                    maxDistance2.planeDist.Select(true);
                    measure.Calculate(null);
                    maxDistance.distance = measure.Distance;
                }
                else
                {

                    maxDistance = maxDistance3;//maxDistance = FindMaxPlate(swComponents, swAddedComp, firstComponent, origaverx, origaverz,isAnglePartFirst);
                    //if (maxDistance.planeDist != null && maxDistance.planeSource != null)
                    //{
                    //    if (maxDistance.planeSource.Name != "#swrfЗадняя2")
                    //        swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(maxDistance.planeSource.Name), true);
                    //    else
                    //    {
                    //        maxDistance.planeSource.Select(false);
                    //        swAddedComp.FeatureByName(plateleft).Select(true);
                    //        measure.Calculate(null);
                    //        double distanceleft = measure.Distance;
                    //        maxDistance.planeSource.Select(false);
                    //        swAddedComp.FeatureByName(plateright).Select(true);
                    //        measure.Calculate(null);
                    //        double distanceright = measure.Distance;
                    //        if (distanceleft<distanceright)
                    //            swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(plateleft), true);
                    //        else
                    //            swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(plateright), true);
                    //    }

                    //}
                }
                double distance2;
                swModel.ClearSelection();
                if (!isAnglePartFirst)
                    status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", "Передняя", firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0);
                else
                    status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", plateleft, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0);
                status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", "#swrfЗадняя", firstComponent.Name, rootName), "PLANE", 0, 0, 0, true, 0, null, 0);
                measure.Calculate(null);
                distance2 = measure.Distance * 1000;
                //поменять размер..
                var curModel = swAddedComp.GetModelDoc2();
                bool isNumber = false;
                OleDbConnection oleDb;
                OleDbDataReader rd;

                List<string> strObjNames = new List<string>();
                string filePath = swAddedComp.GetPathName();
                if (swAddin.OpenModelDatabase(curModel, out oleDb))
                {
                    using (oleDb)
                    {
                        OleDbCommand cm;
                        cm = isNumber
                                    ? new OleDbCommand(
                                        "SELECT * FROM objects WHERE number>0 ORDER BY number",
                                        oleDb)
                                    : new OleDbCommand("SELECT * FROM objects ORDER BY id", oleDb);
                        rd = cm.ExecuteReader();
                        while (rd.Read())
                        {
                            if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" ||
                            rd["caption"].ToString().Trim() == "")
                                continue;
                            string strObjName = rd["name"].ToString();

                            if (filePath.Contains("_SWLIB_BACKUP"))
                            {
                                string pn = Path.GetFileNameWithoutExtension(filePath);
                                string last3 = pn.Substring(pn.Length - 4, 4);
                                string[] arr = strObjName.Split('@');
                                if (arr.Length != 3)
                                    throw new Exception("что-то не так");
                                arr[2] = Path.GetFileNameWithoutExtension(arr[2]) + last3 + Path.GetExtension(arr[2]);
                                strObjName = string.Format("{0}@{1}@{2}", arr[0], arr[1], arr[2]);

                            }
                            strObjNames.Add(strObjName);
                        }
                    }
                }
                swAddin.SetObjectValue(curModel, strObjNames[0], 14, maxDistance.distance * 1000);
                swAddin.SetObjectValue(curModel, strObjNames[1], 14, distance2);
            }
        }