Ejemplo n.º 1
0
        /// <summary>
        /// 遍历装配体零件
        /// </summary>
        /// <param name="swComp"></param>
        /// <param name="nLevel"></param>
        public static void TraverseCompXform(Component2 swComp, long nLevel, bool setcolor = false)
        {
            object[]      vChild;
            Component2    swChildComp;
            string        sPadStr = "";
            MathTransform swCompXform;

            long i;

            for (i = 0; i < nLevel; i++)
            {
                sPadStr = sPadStr + "  ";
            }
            swCompXform = swComp.Transform2;
            if (swCompXform != null)
            {
                ModelDoc2 swModel;
                swModel = (ModelDoc2)swComp.GetModelDoc2();

                if (swModel != null)
                {
                    Debug.Print("Loading:" + swComp.Name2);

                    if (swModel is PartDoc)
                    {
                        var partDoc = (PartDoc)swModel;
                        var vBodies = (Object[])partDoc.GetBodies2((int)swBodyType_e.swAllBodies, true);

                        for (int index = 0; index < vBodies.Length; index++)
                        {
                            AllBodies.Add((Body2)vBodies[index]);
                        }
                    }
                }
            }
            else
            {
                ModelDoc2 swModel;
                swModel = (ModelDoc2)swComp.GetModelDoc2();
            }

            vChild = (object[])swComp.GetChildren();
            for (i = 0; i <= (vChild.Length - 1); i++)
            {
                swChildComp = (Component2)vChild[i];
                TraverseCompXform(swChildComp, nLevel + 1, setcolor);
            }
        }
Ejemplo n.º 2
0
        void AddIds(Component2 component, Dictionary <Tuple <object, string, long?>, int> ids, ref int id)
        {
            if (component.IsHidden(true))
            {
                return;
            }

            var modelDoc = (IModelDoc2)component.GetModelDoc2();

            var tuple = GetTuple(component);

            if (ids.ContainsKey(tuple))
            {
                return;
            }

            ids[tuple] = id++;

            var assembly = modelDoc as IAssemblyDoc;

            if (assembly != null)
            {
                foreach (Component2 c in (object[])component.GetChildren())
                {
                    AddIds(c, ids, ref id);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Run this function after this.Document is populated. It fills two ref vars with swDocumentTypes_e.
        /// </summary>
        /// <param name="d">The document type.</param>
        /// <param name="od">The top-level document type.</param>
        private void GetTypes(ref swDocumentTypes_e d, ref swDocumentTypes_e od)
        {
            swDocumentTypes_e docT     = (swDocumentTypes_e)Document.GetType();
            ModelDoc2         overDoc  = (ModelDoc2)_swApp.ActiveDoc;
            swDocumentTypes_e overDocT = (swDocumentTypes_e)overDoc.GetType();

            if ((docT != swDocumentTypes_e.swDocDRAWING && swSelMgr != null) && swSelMgr.GetSelectedObjectCount2(-1) > 0)
            {
                Component2 comp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1);
                if (comp != null)
                {
                    ModelDoc2 cmd = (ModelDoc2)comp.GetModelDoc2();
                    docT = (swDocumentTypes_e)cmd.GetType();
                    prop.GetPropertyData(comp);
                    comp = null;
                }
                else
                {
                    prop.GetPropertyData(Document);
                }
            }
            else
            {
                swSelMgr = null;
                prop.GetPropertyData(Document);
            }
            d  = docT;
            od = overDocT;
        }
Ejemplo n.º 4
0
        private void ReplaceBolsaCP(Coletor coletor)
        {
            swApp.ActivateDoc(coletor.CodigoColetor + ".SLDASM");
            swModel = swApp.ActiveDoc;

            AssemblyDoc swAssembly = (AssemblyDoc)swModel;

            Object[] components = swAssembly.GetComponents(true);

            foreach (var componente in components)
            {
                Component2 component = (Component2)componente;

                swModel = component.GetModelDoc2();

                string nomeCompletoDoComponente = swModel.GetPathName();
                string nomeComExtensao          = Path.GetFileName(nomeCompletoDoComponente);

                if (String.Equals(nomeComExtensao, "BOLSA SOLDA SUCCAO CP TEMPLATE.SLDPRT"))
                {
                    component.Select(true);
                    break;
                }
            }

            swAssembly.ReplaceComponents($@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\COLETOR SUCCAO\{coletor.CodigoBolsaSoldaSuccaoCompressor}.SLDPRT",
                                         "", true, true);

            swModel = swApp.ActiveDoc;
            swModel.Save();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Возвращает экземпляр класса, представляющего кухонный компонент
        /// </summary>      
        public static KitchenComponent GetKitchenComponent(Component2 component)
        {
            ModelDoc2 model = component.GetModelDoc2();
            CustomPropertyManager propertyManager = model.Extension.get_CustomPropertyManager(string.Empty);
            string kitchenType = string.Empty;
            string resolvedKitchenType = string.Empty;
            propertyManager.Get4("KitchenType", false, out kitchenType, out resolvedKitchenType);

            KitchenComponentTypes.Type kitchentype = KitchenComponentTypes.GetType(kitchenType);

            switch (kitchentype)
            {
                case KitchenComponentTypes.Type.BottomStand:
                    return new BottomStand(component);
                case KitchenComponentTypes.Type.AngleBottomStand:
                    return null;
                case KitchenComponentTypes.Type.TopStand:
                    return null;
                case KitchenComponentTypes.Type.AngleTopStand:
                    return null;
                case KitchenComponentTypes.Type.Column:
                    return null;
                case KitchenComponentTypes.Type.Tabletop:
                    return new Tabletop(component);
                case KitchenComponentTypes.Type.AngleTabletop:
                    return null;
                case KitchenComponentTypes.Type.Plinth:
                    return new Plinth(component);
                default:
                    return null;
            }
        }
Ejemplo n.º 6
0
        public static void UsingCompModelDoc2(this Component2 comp, Action <ModelDoc2> action)
        {
            ModelDoc2 swModel = comp.GetModelDoc2() as ModelDoc2;

            if (swModel != null)
            {
                action(swModel);
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// 直接返回转换类型的ModelDoc对象
 /// </summary>
 /// <param name="comp"></param>
 /// <returns></returns>
 public static ModelDoc2 GetModelDoc2Ex(this Component2 comp)
 {
     try
     {
         return(comp.GetModelDoc2() as ModelDoc2);
     }
     catch (NullReferenceException)
     {
         throw;
     }
 }
Ejemplo n.º 8
0
        private void OnlyKeepNamedBody(string v, string s, AssemblyDoc assemblyDoc, Component2 sendToCustomerBodies, Component2 insertComponentSendtoCustomer, ref bool diff1)
        {
            //var tempswModel = (ModelDoc2)swModel;
            var swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.Extension.SelectByID2(v + "@" + s, "SOLIDBODY", 0, 0, 0, false, 0, null, 0);

            var myFeature = swModel.FeatureManager.InsertDeleteBody2(true);

            insertComponentSendtoCustomer.Select(false);

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

            var tempPart = (ModelDoc2)sendToCustomerBodies.GetModelDoc2();

            theFeature = (Feature)tempPart.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();
                diff1 = 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();

                theFeature = (Feature)tempPart.FeatureByPositionReverse(1);
                if (theFeature.Name.Contains("Join"))
                {
                    b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

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

            assemblyDoc.EditAssembly();
        }
Ejemplo n.º 9
0
        private void traverse(Component2 comp)
        {
            object[] childrens = comp.GetChildren();
            foreach (Component2 child in childrens)
            {
                traverse(child);
            }

            ModelDoc2 mdocChild = comp.GetModelDoc2();

            if (mdocChild.GetType() == 1)
            {
                // Bezeichnung kann über 2 Möglichkeiten erfolgen
                // Dateiname (mit GetFileName wird nur der Dateiname aus einem Dateipfad extrahiert
                string entry = System.IO.Path.GetFileName(comp.GetPathName());
                // oder
                string entry2 = comp.Name2;
                //entfernen der 2 hinteren Zeichen im String
                entry2 = entry2.Remove(entry2.Length - 2);

                int Row = 0;

                // überprüfen, ob aktueller Eintrag bereits vorhanden ist, wenn ja Zeilen-Index speichern
                for (int i = 2; i < index; i++)
                {
                    if ((string)exlSheet.Cells[i, 3].Value2 == entry)
                    {
                        Row = i;
                    }
                }
                // wenn Zeilen Index gesetzt wurde, Wert für Anzahl aus Zeile lesen und um 1 erhöhen
                // erhöhten Wert in Zelle schreiben
                if (Row > 0)
                {
                    double newCount = (double)exlSheet.Cells[Row, 1].Value2 + 1;
                    exlSheet.Cells[Row, 1] = newCount;
                }
                else
                {
                    // Wenn ZeilenIndex nicht gesetzt wurde, neuen Dateipfad
                    exlSheet.Cells[index, 1] = 1;
                    exlSheet.Cells[index, 2] = "Stück";
                    exlSheet.Cells[index, 3] = entry;

                    lb_output.Items.Add(entry);

                    index++;
                }
            }
        }
Ejemplo n.º 10
0
        private IConfiguration createNewConfiguration(Component2 swComponent)
        {
            string componentName = Utilities.stripIdentifier(swComponent.Name);
            string newConfigName = "SAURON-" + Utilities.randomString();

            IModelDoc2     component = swComponent.GetModelDoc2();
            IConfiguration newConfig = component.AddConfiguration3(newConfigName,
                                                                   "automatically generated configuration",
                                                                   "",
                                                                   0);

            swComponent.ReferencedConfiguration = newConfig.Name;
            swDoc.EditRebuild3();

            return(newConfig);
        }
        public static KLgraph.KLshapePart KL_GetShapePart(Component2 comp, SldWorks swApplication)
        {
            var body  = (Body2)comp.GetBody();
            var model = (ModelDoc2)comp.GetModelDoc2();
            var path  = model.GetPathName();

            DirectoryInfo parentDir = Directory.GetParent(path.EndsWith("\\") ? path : String.Concat(path, "\\"));

            var pathParentDir = parentDir.Parent.FullName;

            //var pathComponent = Path.GetFileName(comp.GetPathName());
            var componentName = comp.Name2;

            componentName = (componentName.Split('/').Last());
            componentName = componentName.Replace("_", string.Empty);
            componentName = componentName.Substring(0, componentName.LastIndexOf('-'));
            componentName = componentName.Replace(" ", string.Empty);
            //componentName = FolderUtilities.FolderUtilities.RemoveDiacritics(componentName);

            //var componentName = ((pathComponent.Split(new[] { " - " }, StringSplitOptions.None).Last()).Replace(" ", string.Empty)).Replace("/", string.Empty);

            /*
             * // Per essere coerente con le varie cazzate di Matteo, quando cerco le armoniche sferiche di una parte, non posso cercare il file con il suo nome,
             * // devo prendere come nome dall'ultimo spazio in poi,
             * // perché fare il trim degli spazi era troppo complicato per un "genio" come lui!
             *
             * var componentName = comp.Name;
             * componentName = componentName.Split(Convert.ToChar(" ")).Last();
             * componentName = componentName.Split(Convert.ToChar("/")).Last();
             * componentName = (componentName.Split(Convert.ToChar("."))).First();
             * //componentName = FolderUtilities.FolderUtilities.RemoveDiacritics(componentName);
             */

            var prop = model.Extension.CreateMassProperty();

            prop.AddBodies(body);
            var part = (PartDoc)model;

            var volume         = prop.Volume;
            var surface        = prop.SurfaceArea;
            var listFirstModel = ReadSHdescriptor(swApplication, pathParentDir, componentName);

            var shapePart = new KLgraph.KLshapePart(volume, surface, listFirstModel);

            return(shapePart);
        }
Ejemplo n.º 12
0
        Tuple <object, string, long?> GetTuple(Component2 component)
        {
            var modelDoc = (IModelDoc2)component.GetModelDoc2();

            if (modelDoc is IAssemblyDoc)
            {
                return(new Tuple <object, string, long?>(component, component.ReferencedConfiguration, null));
            }

            var componentColor = (double[])component.GetMaterialPropertyValues2((int)swInConfigurationOpts_e.swThisConfiguration, null);

            if (componentColor != null && componentColor[0] != -1)
            {
                return(new Tuple <object, string, long?>(modelDoc, component.ReferencedConfiguration, ColorArrayToColor(componentColor)));
            }
            return(new Tuple <object, string, long?>(modelDoc, component.ReferencedConfiguration, null));
        }
Ejemplo n.º 13
0
        public static MyRepeatedComponent ComputeNewRepeatedComponent(SldWorks swApplication, Component2 component2, int idCorrespondingNode,
                                                                      MyTransformMatrix newRelativeTransformMatrix, int indexRepEntity, bool newIsLeaf)
        {
            // Aggiunto calcolo dell'entità ripetuta alla parte.
            var currentModel = component2.GetModelDoc2();
            var entityList   =
                (List <Entity>)AssemblyTraverse.KL_GetPartFaces(currentModel, component2.Name2,
                                                                swApplication);

            double[,] compositionMatrixOfComponentPart =
                new double[4, 4]
            {
                {
                    (double)newRelativeTransformMatrix.RotationMatrix[0, 0],
                    (double)newRelativeTransformMatrix.RotationMatrix[0, 1],
                    (double)newRelativeTransformMatrix.RotationMatrix[0, 2],
                    (double)newRelativeTransformMatrix.TranslationVector[0]
                },
                {
                    (double)newRelativeTransformMatrix.RotationMatrix[1, 0],
                    (double)newRelativeTransformMatrix.RotationMatrix[1, 1],
                    (double)newRelativeTransformMatrix.RotationMatrix[1, 2],
                    (double)newRelativeTransformMatrix.TranslationVector[1]
                },
                {
                    (double)newRelativeTransformMatrix.RotationMatrix[2, 0],
                    (double)newRelativeTransformMatrix.RotationMatrix[2, 1],
                    (double)newRelativeTransformMatrix.RotationMatrix[2, 2],
                    (double)newRelativeTransformMatrix.TranslationVector[2]
                },
                { 0.0, 0.0, 0.0, 1 }
            };

            //swApplication.SendMsgToUser("Calcolo repeated entity di " + component2.Name2 + "\nnumero facce " + entityList.Count);
            MyRepeatedEntity newRepeatedEntity = ExtractInfoFromBRep.KLBuildRepeatedEntity(
                entityList, indexRepEntity, compositionMatrixOfComponentPart, swApplication);
            //swApplication.SendMsgToUser("Ha " + newRepeatedEntity.listOfVertices.Count + " vertici\n" + newRepeatedEntity.listOfAddedVertices.Count + " vertici aggiunti");

            // Fine calcolo entità rip da aggiungere alla componente.
            var newMyComponent = new MyRepeatedComponent(component2, idCorrespondingNode, newRelativeTransformMatrix, newIsLeaf,
                                                         newRepeatedEntity);

            return(newMyComponent);
        }
Ejemplo n.º 14
0
        public void Change()
        {
            ModelDoc2 swModel = (ModelDoc2)Component.GetModelDoc2();

            string[] names = (string[])swModel.GetConfigurationNames();

            for (int i = 0; i < names.Length; i++)
            {
                if (NewConfig == names[i])
                {
                    return;
                }
            }

            swModel.ShowConfiguration(OldConfig);
            swModel.AddConfiguration2(NewConfig, "", "", false, false, false, true, 0);

            swModel.Save();
        }
Ejemplo n.º 15
0
        public void GetParametersFromAssembly(ModelDoc2 doc, ref List <ModelDoc2> Parameters_List)
        {
            if (doc == null)
            {
                return;
            }

            int docType = doc.GetType();

            if (docType == (int)swDocumentTypes_e.swDocPART)
            {
                Parameters_List.Add(doc);
                return;
            }
            //object haha = doc.get;

            Configuration swConf = (Configuration)doc.GetActiveConfiguration();

            if (swConf == null)
            {
                return;
            }
            Component2 swRootComp  = (Component2)swConf.GetRootComponent();
            int        swRootComp1 = (int)swConf.GetParameterCount();

            if (swRootComp1 == null)
            {
                return;
            }
            else
            {
                Parameters_List.Add(doc);
                object[] haha = swRootComp.GetChildren();

                foreach (object hh in haha)
                {
                    Component2 hh2  = (Component2)hh;
                    ModelDoc2  hhhh = hh2.GetModelDoc2();
                    GetParametersFromAssembly(hhhh, ref Parameters_List);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// On click, update Redbrick.
        ///
        /// This is where we used to wait 10-20 seconds for the built-in property manager.
        ///
        /// If you were wondering, people don't get raises for that kind of increase in productivity.
        /// It pays the same as sitting in front of a brake all day. I'm considering bringing the
        /// wait back. We just need this:
        /// System.Threading.Thread.Sleep(10000);
        /// </summary>
        /// <returns>0</returns>
        int ad_UserSelectionPostNotify()
        {
            // What do we got?
            swSelComp = swSelMgr.GetSelectedObjectsComponent2(1);
            if (swSelComp != null)
            {
                // This thing!
                Document = swSelComp.GetModelDoc2();
                // Let's have a look.
                ConnectSelection();
            }
            else
            {
                // Nothing's selected?
                Document = SwApp.ActiveDoc;
                // Just look at the root item then.
                ConnectSelection();
            }

            return(0);
        }
Ejemplo n.º 17
0
        public void TraverseComponent(Component2 swComp)
        {
            string name = swComp.Name2;

            object[]   vChildComp;
            Component2 swChildComp;


            vChildComp = (object[])swComp.GetChildren();
            for (int i = 0; i < vChildComp.Length; i++)
            {
                swChildComp = (Component2)vChildComp[i];
                TraverseComponent(swChildComp);
            }
            try
            {
                ModelDoc2 compMdl = (ModelDoc2)swComp.GetModelDoc2();

                if (compMdl != null)
                {
                    string mdlName = Path.GetFileName(compMdl.GetPathName());
                    string refCfg  = swComp.ReferencedConfiguration;

                    string newConfig = GetNewConfig(mdlName, refCfg);
                    if (!string.IsNullOrEmpty(newConfig))
                    {
                        ModifyComponent comp = new ModifyComponent(swComp, refCfg, newConfig);
                        comp.Change();

                        swComp.Select(false);
                        AssemblyDoc assem = (AssemblyDoc)iSwApp.ActiveDoc;

                        assem.CompConfigProperties4(2, 0, true, true, newConfig, false);
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 获取根组件的配合(MATE)
        /// </summary>
        /// <param name="rootComponent"></param>
        /// <returns></returns>
        private static List <Mate2> GetMatesOfRootComponent(Component2 rootComponent)
        {
            if (rootComponent == null)
            {
                return(null);
            }

            Feature      feature = null;
            ModelDoc2    doc     = rootComponent.GetModelDoc2();
            List <Mate2> mates   = new List <Mate2>();
            Mate2        pMate   = null;

            //获得配合组(MateGroup)
            feature = doc.FirstFeature();
            while (feature != null)
            {
                if (feature.GetTypeName2() == "MateGroup")
                {
                    break;
                }
                feature = feature.GetNextFeature();
            }

            // 从配合组的子特征中提取配合
            if (feature != null)
            {
                feature = feature.GetFirstSubFeature();
                while (feature != null)
                {
                    pMate = feature.GetSpecificFeature2();
                    mates.Add(pMate);
                    feature = feature.GetNextSubFeature();
                }
            }

            return(mates);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 遍历装配体零件
        /// </summary>
        /// <param name="swComp"></param>
        /// <param name="nLevel"></param>
        public static void TraverseCompXform(Component2 swComp, long nLevel, bool setcolor = false)
        {
            object[]      vChild;
            Component2    swChildComp;
            string        sPadStr = "";
            MathTransform swCompXform;
            //  object vXform;
            long i;

            for (i = 0; i < nLevel; i++)
            {
                sPadStr = sPadStr + "  ";
            }
            swCompXform = swComp.Transform2;
            if (swCompXform != null)
            {
                ModelDoc2 swModel;
                swModel = (ModelDoc2)swComp.GetModelDoc2();

                try
                {
                    //子零件文件名
                    //Debug.Print(sPadStr + swComp.Name2);

                    if (swComp.GetSelectByIDString() == "")
                    {
                        //选择id
                        //Debug.Print(swComp.GetSelectByIDString());
                    }
                    else
                    {
                    }
                }
                catch
                {
                }
                if (swModel != null)
                {
                    Debug.Print("Loading:" + swComp.Name2);
                    //获取零件的一些信息,如属性,名字路径。
                    string tempPartNum      = swModel.get_CustomInfo2(swComp.ReferencedConfiguration, "PartNum");
                    string tempName2        = swComp.Name2;
                    string tempName         = swModel.GetPathName();
                    string tempConfigName   = swComp.ReferencedConfiguration;
                    string tempComponentRef = swComp.ComponentReference;

                    //如果要设定颜色
                    if (setcolor == true)
                    {
                        double[] matPropVals = (double[])swModel.MaterialPropertyValues;
                        var      tempC       = GetRadomColor(System.IO.Path.GetFileNameWithoutExtension(swModel.GetPathName()));
                        matPropVals[0] = Convert.ToDouble(tempC.R) / 255;
                        matPropVals[1] = Convert.ToDouble(tempC.G) / 255;
                        matPropVals[2] = Convert.ToDouble(tempC.B) / 255;
                        swModel.MaterialPropertyValues = matPropVals;

                        swModel.WindowRedraw();
                    }
                }
            }
            else
            {
                ModelDoc2 swModel;
                swModel = (ModelDoc2)swComp.GetModelDoc2();
            }

            vChild = (object[])swComp.GetChildren();
            for (i = 0; i <= (vChild.Length - 1); i++)
            {
                swChildComp = (Component2)vChild[i];
                TraverseCompXform(swChildComp, nLevel + 1, setcolor);
            }
        }
Ejemplo n.º 20
0
        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);
                    Component2 swPart      = swSelMgr.GetSelectedObjectsComponent3(isel, -1);
                    ModelDoc2  swPartModel = (ModelDoc2)swPart.GetModelDoc2();
                    Component2 swPartcorr  = swPartModel.Extension.GetCorresponding(swPart); // ***TODO*** for instanced parts? does not work...
                    swPartcorr = swPart;                                                     // ***TODO***

                    if (swPartModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                    {
                        if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentFlexibleSolving)
                        {
                            System.Windows.Forms.MessageBox.Show("Fexible assemblies not supported as ChBody (set as Rigid?)");
                            return;
                        }
                        if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentRigidSolving)
                        {
                            System.Windows.Forms.MessageBox.Show("Setting props to rigid assembly as ChBody");
                            AssemblyDoc swAssemblyDoc = (AssemblyDoc)swPartModel;
                            swPart.Select(false);
                            swAssemblyDoc.EditAssembly();
                            swAssemblyDoc.EditRebuild();
                            //return;
                        }
                    }

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

                        swPartModel.ForceRebuild3(false); // needed, but does not work...
                        //swPartModel.Rebuild((int)swRebuildOptions_e.swRebuildAll); // needed but does not work...

                        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!");
                        }
                    }

                    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());
                     * }
                     */
                }
            }
        }
Ejemplo n.º 21
0
        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);
                    Component2 swPart      = swSelMgr.GetSelectedObjectsComponent3(isel, -1);
                    ModelDoc2  swPartModel = (ModelDoc2)swPart.GetModelDoc2();
                    Component2 swPartcorr  = swPartModel.Extension.GetCorresponding(swPart); // ***TODO*** for instanced parts? does not work...
                    swPartcorr = swPart;                                                     // ***TODO***

                    // fetch SW attribute with Chrono parameters for ChBody
                    SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPartcorr.FindAttribute(mdefattr_chbody, 0);
                    if (myattr == null)
                    {
                        // if not already added to part, create and attach it
                        System.Windows.Forms.MessageBox.Show("Create data [should not happen here]");
                        myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody data", 0, (int)swInConfigurationOpts_e.swThisConfiguration);
                        swPartModel.ForceRebuild3(false); // needed?
                        if (myattr == null)
                        {
                            System.Windows.Forms.MessageBox.Show("Error: 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, "");
                     */
                }
            }
        }
        public SwModelWrapper GetModelWrapper()
        {
            ModelDoc2 swModel = swComp.GetModelDoc2();

            return(new SwModelWrapper(swApi, swApp, (swDocumentTypes_e)swModel.GetType(), swModel, this.swComp.ReferencedConfiguration));
        }
Ejemplo n.º 23
0
        public static string GetTitle(this Component2 component)
        {
            var model = component.GetModelDoc2() as ModelDoc2;

            return(model.GetTitle());
        }
Ejemplo n.º 24
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);
            }
        }
        public static KLgraph.KLstatisticPart KL_GetStatisticPart(Component2 comp, double compSurface, SldWorks swApplication)
        {
            var faceNumber   = 0;
            var edgeNumber   = 0;
            var vertexNumber = 0;

            var verticesList = new List <Vertex>();

            var planarPercent      = 0.0;
            var cylindricalPercent = 0.0;
            var conicalPercent     = 0.0;
            var sphericalPercent   = 0.0;
            var toroidalPercent    = 0.0;
            var freeformPercent    = 0.0;

            var planarNumber      = 0;
            var cylindricalNumber = 0;
            var conicalNumber     = 0;
            var sphericalNumber   = 0;
            var toroidalNumber    = 0;
            var freeformNumber    = 0;

            if (comp != null)
            {
                var model    = (ModelDoc2)comp.GetModelDoc2();
                var faceList = KL_GetPartFaces(model, comp.Name2, swApplication);
                foreach (Face2 face2 in faceList)
                {
                    faceNumber++;
                    edgeNumber += face2.GetEdgeCount();
                    foreach (Edge edge in face2.GetEdges())
                    {
                        var startVertex = edge.GetStartVertex();
                        var endVertex   = edge.GetEndVertex();

                        verticesList.Add(startVertex);
                        verticesList.Add(endVertex);
                    }
                    var surface = (Surface)face2.GetSurface();

                    if (surface.IsPlane())
                    {
                        planarPercent += face2.GetArea();
                        planarNumber++;
                    }
                    else if (surface.IsCylinder())
                    {
                        cylindricalPercent += face2.GetArea();
                        cylindricalNumber++;
                    }
                    else if (surface.IsCone())
                    {
                        conicalPercent += face2.GetArea();
                        conicalNumber++;
                    }
                    else if (surface.IsSphere())
                    {
                        sphericalPercent += face2.GetArea();
                        sphericalNumber++;
                    }
                    else if (surface.IsTorus())
                    {
                        toroidalPercent += face2.GetArea();
                        toroidalNumber++;
                    }
                    else
                    {
                        freeformPercent += face2.GetArea();
                        freeformNumber++;
                    }
                }

                planarPercent      = (double)planarPercent / (double)compSurface;
                cylindricalPercent = (double)cylindricalPercent / (double)compSurface;
                conicalPercent     = (double)conicalPercent / (double)compSurface;
                sphericalPercent   = (double)sphericalPercent / (double)compSurface;
                toroidalPercent    = (double)toroidalPercent / (double)compSurface;
                freeformPercent    = (double)freeformPercent / (double)compSurface;


                var genus = KL_ComputeGenus(model, comp.Name, swApplication);

                if (comp.Name.Contains("PRT_RoulementSortieRouleaux"))
                {
                    swApplication.SendMsgToUser("Genere " + genus);
                }
                var statistic = new KLgraph.KLstatisticPart(genus, planarPercent, cylindricalPercent, conicalPercent,
                                                            sphericalPercent, toroidalPercent,
                                                            freeformPercent, planarNumber, cylindricalNumber, conicalNumber, sphericalNumber, toroidalNumber,
                                                            freeformNumber);
                return(statistic);
            }
            var statisticEmpty = new KLgraph.KLstatisticPart();

            return(statisticEmpty);
        }
Ejemplo n.º 26
0
        public void getFeaturesOfType(Component2 component, string featureName, bool topLevelOnly, Dictionary<string, List<Feature>> features)
        {
            ModelDoc2 modeldoc;
            string ComponentName = "";
            if (component == null)
            {
                modeldoc = ActiveSWModel;
            }
            else
            {
                modeldoc = component.GetModelDoc2();
                ComponentName = component.Name2;
            }
            features[ComponentName] = new List<Feature>();

            object[] featureObjects;
            featureObjects = modeldoc.FeatureManager.GetFeatures(false);

            foreach (Feature feat in featureObjects)
            {
                string t = feat.GetTypeName2();
                if (feat.GetTypeName2() == featureName)
                {
                    features[ComponentName].Add(feat);
                }
            }

            if (!topLevelOnly && modeldoc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                AssemblyDoc assyDoc = (AssemblyDoc)modeldoc;

                //Get all components in an assembly
                object[] components = assyDoc.GetComponents(false);
                
                // If there are no components in an assembly, this object will be null.
                if (components != null)
                {
                    foreach (Component2 comp in components)
                    {
                        ModelDoc2 doc = comp.GetModelDoc2();
                        if (doc != null)
                        {
                            //We already have all the components in an assembly, we don't want to recur as we go through them. (topLevelOnly = true)
                            getFeaturesOfType(comp, featureName, true, features);
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
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);
            }
        }
Ejemplo n.º 28
0
        public void OutputCompXformTemp(Component2 swComp, long nLevel, string parents)
        {
            object[]      vChild;
            Component2    swChildComp;
            string        sPadStr      = "";
            string        tempSelectID = "";
            MathTransform swCompXform;
            //  object vXform;
            long i;

            for (i = 0; i < nLevel; i++)
            {
                sPadStr = sPadStr + ".";
            }

            swCompXform = swComp.Transform2;

            if (swCompXform != null)
            {
                ModelDoc2 swModel;
                swModel = (ModelDoc2)swComp.GetModelDoc2();
                Boolean tempSupp = swComp.IsSuppressed();
                Boolean tempHide = swComp.IsHidden(false);

                if (swModel != null && tempSupp == false)
                {
                    StatusLab.Text = "Loading:" + swComp.Name;

                    string tempCode     = Path.GetFileNameWithoutExtension(swModel.GetPathName());
                    string swMateDB     = "";
                    string tempMaterial = "";
                    if (swModel.GetType() == 1)
                    {
                        tempMaterial = ((PartDoc)swModel).GetMaterialPropertyName2("", out swMateDB);
                    }
                    else
                    {
                        tempMaterial = "";
                    }

                    string tempSize = swModel.GetCustomInfoValue("", "零件尺寸");

                    string tempComment = swModel.GetCustomInfoValue("", "其它说明");

                    string tempblanktype = swModel.GetCustomInfoValue("", "下料方式");

                    string tempName = CodetoName(tempCode);

                    string tempName2 = GetName(tempCode);

                    tempSelectID = swComp.GetSelectByIDString();

                    int tempblanqty = 1;

                    if (ignore != "" && tempSelectID.Contains(ignore) == true)
                    {
                    }
                    else
                    {
                        var q = bomItems.Where(x => x.name == tempName && x.parents == parents).ToList();

                        if (q.Count == 0 && tempCode.Contains("镜向") == false && tempCode.Contains("复制") == false)
                        {
                            bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype));
                        }
                        else if (tempCode.Contains("镜向"))
                        {
                            if (q.Count == 0)
                            {
                                if (sPadStr.Length == 1)
                                {
                                    bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 0, "", tempComment, tempName, 1, tempName, tempSelectID, parents, tempblanktype));
                                }

                                bomItems.Add(new BomItem(sPadStr, tempCode, "", "", 1, "", tempComment, "", 0, tempName2, tempSelectID, parents, tempblanktype));
                            }
                            else
                            {
                                if (bomItems[bomItems.IndexOf(q[0])].parents == parents)
                                {
                                    bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1;

                                    //	bomItems[bomItems.IndexOf(q[0])] = new BomItem(sPadStr, bomItems[bomItems.IndexOf(q[0])].code, bomItems[bomItems.IndexOf(q[0])].material, bomItems[bomItems.IndexOf(q[0])].size, bomItems[bomItems.IndexOf(q[0])].qty, bomItems[bomItems.IndexOf(q[0])].blanksize, tempComment, bomItems[bomItems.IndexOf(q[0])].name, bomItems[bomItems.IndexOf(q[0])].blankqty + 1, bomItems[bomItems.IndexOf(q[0])].name2);

                                    var q2 = bomItems.Where(x => x.name2 == tempName2).ToList();

                                    if (q2.Count == 0)
                                    {
                                        //bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 0, tempBlankSize, tempComment, tempName, 0, tempName2));
                                        bomItems.Add(new BomItem(sPadStr, tempCode, "", "", 1, "", tempComment, "", 0, tempName2, tempSelectID, parents, tempblanktype));
                                    }
                                    else
                                    {
                                        bomItems[bomItems.IndexOf(q2[0])].qty = bomItems[bomItems.IndexOf(q2[0])].qty + 1;
                                    }
                                }
                                else
                                {
                                    bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype));
                                }
                            }
                        }
                        else if (tempCode.Contains("复制"))
                        {
                            if (q.Count == 0)
                            {
                                bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, 1, tempName, tempSelectID, parents, tempblanktype));
                            }
                            else
                            {
                                bomItems[bomItems.IndexOf(q[0])].qty      = bomItems[bomItems.IndexOf(q[0])].qty + 1;
                                bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1;

                                if (swModel.GetType() == 2)
                                {
                                    ignore = tempSelectID;
                                }
                            }
                        }
                        else if (q.Count > 0 && tempCode.Contains("镜向") == false && tempCode.Contains("复制") == false && bomItems[bomItems.IndexOf(q[0])].parents == parents)
                        {
                            bomItems[bomItems.IndexOf(q[0])].qty      = bomItems[bomItems.IndexOf(q[0])].qty + 1;
                            bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1;

                            if (swModel.GetType() == 2)
                            {
                                ignore = tempSelectID;
                            }
                        }
                        else
                        {
                            bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype));
                        }
                    }
                }
            }
            ;

            vChild = (object[])swComp.GetChildren();

            for (i = 0; i <= (vChild.Length - 1); i++)
            {
                swChildComp = (Component2)vChild[i];

                OutputCompXformTemp(swChildComp, nLevel + 1, tempSelectID);

                if (i == vChild.Length - 1)
                {
                    ignore = "";
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// On click, update Redbrick. 
        /// 
        /// This is where we used to wait 10-20 seconds for the built-in property manager. 
        /// 
        /// If you were wondering, people don't get raises for that kind of increase in productivity. 
        /// It pays the same as sitting in front of a brake all day. I'm considering bringing the
        /// wait back. We just need this:
        /// System.Threading.Thread.Sleep(10000);
        /// </summary>
        /// <returns>0</returns>
        int ad_UserSelectionPostNotify()
        {
            // What do we got?
              swSelComp = swSelMgr.GetSelectedObjectsComponent2(1);
              if (swSelComp != null) {
            // This thing!
            Document = swSelComp.GetModelDoc2();
            // Let's have a look.
            ConnectSelection();
              } else {
            // Nothing's selected?
            Document = SwApp.ActiveDoc;
            // Just look at the root item then.
            ConnectSelection();
              }

              return 0;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Method that process an assembly document and check if every subpart and subassembly has been sent to the server and if it is updated.
        /// <param name="currentAssembly">The current assembly been processing</param>
        /// <param name="worker">The worker in charge of doing this task</param>
        /// </summary>
        public ProcessStatus ProcessAssemblyRecursively(Assembly currentAssembly, BackgroundWorker worker)
        {
            // If the current assembly is already been processed in the current session, skip this iteration
            ProcessStatus possibleResult;

            if (m_ProcessedAssemblies.TryGetValue(currentAssembly.Guid, out possibleResult))
            {
                return(possibleResult);
            }

            var allSubOccurrencesValid = true;
            var waitingForId           = false;

            if (!currentAssembly.IsPart)
            {
                // Access to the colection of occurrences
                object[] allComponents = (object[])currentAssembly.AssemblyDocument.GetComponents(true);

                // True if all the suboccurrences are already in the server

                // Verify that all the subassemblies and subparts have an id
                for (int i = 0; i < allComponents.Length; i++)
                {
                    // Access to the occurrence
                    Component2 component         = (Component2)allComponents[i];
                    object     modelDoc          = component.GetModelDoc2();
                    var        componentAssembly = new Assembly(new Model((ModelDoc2)modelDoc));

                    // Analize each occurrence
                    ProcessStatus result = ProcessAssemblyRecursively(componentAssembly, worker);

                    switch (result)
                    {
                    case ProcessStatus.UPDATE:
                    {
                        // Get the occurrence transform.
                        MatrixTransform transform = new MatrixTransform(component.Transform2);

                        // Create the relation between this assembly and it subassembly or subpart
                        Relation relation = new Relation(component.Name, componentAssembly.IdAssembly, new Position(transform.Translation(), transform.EulerAngles()));

                        currentAssembly.ListOfRelations.Add(relation);
                    }
                    break;

                    case ProcessStatus.FAIL:
                    {
                        allSubOccurrencesValid = false;
                    }
                    break;

                    case ProcessStatus.WAITING_FOR_ID:
                    case ProcessStatus.NEW:
                    {
                        waitingForId = true;

                        // Get the occurrence transform.
                        MatrixTransform transform = new MatrixTransform(component.Transform2);

                        // Create the relation between this assembly and it subassembly or subpart
                        Relation relation = new Relation(component.Name, componentAssembly.IdAssembly, new Position(transform.Translation(), transform.EulerAngles()));

                        if (currentAssembly.WaitingChildIds.ContainsKey(componentAssembly.Guid))
                        {
                            currentAssembly.WaitingChildIds[componentAssembly.Guid].Add(relation);
                        }
                        else
                        {
                            var relationsList = new List <Relation>();
                            relationsList.Add(relation);
                            currentAssembly.WaitingChildIds.Add(componentAssembly.Guid, relationsList);
                        }
                    }
                    break;
                    }
                }
            }

            // If at leat one of the childs can not be sent to the server, neither the current assembly
            if (!allSubOccurrencesValid)
            {
                worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "On of the assembly childs cannot be sent"));
                Add(currentAssembly, ProcessStatus.FAIL);
                return(ProcessStatus.FAIL);
            }

            // If some of the child are waiting for id, mark as waiting
            if (waitingForId && (currentAssembly.CanBeUpdated || currentAssembly.CanBeSent))
            {
                worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Waiting for child id"));
                Add(currentAssembly, ProcessStatus.WAITING_FOR_ID);
                return(ProcessStatus.WAITING_FOR_ID);
            }

            // If it can be updated, mark for update
            if (currentAssembly.CanBeUpdated)
            {
                worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Ready for update"));
                Add(currentAssembly, ProcessStatus.UPDATE);
                return(ProcessStatus.UPDATE);
            }

            // If it can be sent, mark for send
            if (currentAssembly.CanBeSent)
            {
                worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Ready to be sent"));
                Add(currentAssembly, ProcessStatus.NEW);
                return(ProcessStatus.NEW);
            }

            // If the current assembly cant be sent or updated, mark as failed
            worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Cannot be sent"));
            Add(currentAssembly, ProcessStatus.FAIL);
            return(ProcessStatus.FAIL);
        }
Ejemplo n.º 31
0
                public static ExternalFileReferences Get(SldWorks swApp)
                {
                    try
                    {
                        var               obj                = new ExternalFileReferences();
                        ModelDoc2         swModel            = default(ModelDoc2);
                        ModelDocExtension swModDocExt        = default(ModelDocExtension);
                        SelectionMgr      swSelMgr           = default(SelectionMgr);
                        Feature           swFeat             = default(Feature);
                        Component2        swComp             = default(Component2);
                        object            vModelPathName     = null;
                        object            vComponentPathName = null;
                        object            vFeature           = null;
                        object            vDataType          = null;
                        object            vStatus            = null;
                        object            vRefEntity         = null;
                        object            vFeatComp          = null;
                        int               nConfigOpt         = 0;
                        string            sConfigName        = null;
                        int               nRefCount          = 0;
                        int               nSelType           = 0;
                        int               i = 0;

                        swModel  = (ModelDoc2)swApp.ActiveDoc;
                        swSelMgr = (SelectionMgr)swModel.SelectionManager;

                        swModDocExt = (ModelDocExtension)swModel.Extension;
                        nSelType    = swSelMgr.GetSelectedObjectType3(1, -1);

                        switch (nSelType)
                        {
                        // Selected component in an assembly document
                        case (int)swSelectType_e.swSelCOMPONENTS:
                            swComp    = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, -1);
                            nRefCount = swComp.ListExternalFileReferencesCount();
                            swComp.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);

                            swModel = (ModelDoc2)swComp.GetModelDoc2();

                            break;

                        // Selected feature in a part or assembly document
                        case (int)swSelectType_e.swSelBODYFEATURES:
                        case (int)swSelectType_e.swSelSKETCHES:
                            swFeat    = (Feature)swSelMgr.GetSelectedObject6(1, -1);
                            nRefCount = swFeat.ListExternalFileReferencesCount();
                            swFeat.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);

                            break;

                        // Part document only
                        default:
                            nRefCount = swModDocExt.ListExternalFileReferencesCount();
                            swModDocExt.ListExternalFileReferences(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);

                            break;
                        }

                        //Debug.Print("Model name = " + swModel.GetPathName());

                        if (nRefCount >= 1)
                        {
                            object[] ModelPathName     = new object[nRefCount - 1];
                            object[] ComponentPathName = new object[nRefCount - 1];
                            object[] Feature           = new object[nRefCount - 1];
                            object[] DataType          = new object[nRefCount - 1];
                            int[]    Status            = new int[nRefCount - 1];
                            object[] RefEntity         = new object[nRefCount - 1];
                            object[] FeatComp          = new object[nRefCount - 1];

                            ModelPathName     = (object[])vModelPathName;
                            ComponentPathName = (object[])vComponentPathName;
                            Feature           = (object[])vFeature;
                            DataType          = (object[])vDataType;
                            Status            = (int[])vStatus;
                            RefEntity         = (object[])vRefEntity;
                            FeatComp          = (object[])vFeatComp;

                            for (i = 0; i <= nRefCount - 1; i++)
                            {
                                obj.ModelPathName     = ModelPathName[i].ToString();
                                obj.ComponentPathName = ComponentPathName[i].ToString();
                                obj.Feature           = Feature[i].ToString();
                                obj.DataType          = DataType[i].ToString();
                                obj.Status            = Status[i].ToString();
                                obj.ReferenceEntity   = RefEntity[i].ToString();
                                obj.FeatureComponent  = FeatComp[i].ToString();
                                obj.ConfigOption      = nConfigOpt.ToString();
                                obj.ConfigName        = sConfigName?.ToString();
                            }
                        }
                        return(obj);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.StackTrace);
                        return(null);
                    }
                }
Ejemplo n.º 32
0
        /// <summary>
        /// 获取根组件的配合(MATE)
        /// </summary>
        /// <param name="rootComponent"></param>
        /// <returns></returns>
        private static List<Mate2> GetMatesOfRootComponent(Component2 rootComponent) {
            if (rootComponent == null)
                return null;

            Feature feature = null;
            ModelDoc2 doc = rootComponent.GetModelDoc2();
            List<Mate2> mates = new List<Mate2>();
            Mate2 pMate = null;

            //获得配合组(MateGroup)
            feature = doc.FirstFeature();
            while (feature != null) {
                if (feature.GetTypeName2() == "MateGroup")
                    break;
                feature = feature.GetNextFeature();
            }

            // 从配合组的子特征中提取配合
            if (feature != null) {
                feature = feature.GetFirstSubFeature();
                while (feature != null) {
                    pMate = feature.GetSpecificFeature2();
                    mates.Add(pMate);
                    feature = feature.GetNextSubFeature();
                }
            }

            return mates;
        }