/// <summary> /// 获得配合类型 /// </summary> /// <param name="SwComp"></param> public static void GetMateType(Component2 SwComp) { object[] CompMateObjs = SwComp.GetMates(); foreach (object ObjMate in CompMateObjs) { if (ObjMate is Mate2) { Mate2 SwMate = (Mate2)ObjMate; System.Windows.MessageBox.Show(Enum.Parse(typeof(swMateType_e), SwMate.Type.ToString().Trim()).ToString().Trim()); } } }
/// <summary> /// 获得配合类型 /// </summary> /// <param name="SwComp"></param> public static void GetMateRefrence(Component2 SwComp) { object[] CompMateObjs = SwComp.GetMates(); StringBuilder Sb = new StringBuilder(""); foreach (object ObjMate in CompMateObjs) { if (ObjMate is Mate2) { Mate2 SwMate = (Mate2)ObjMate; Sb.Append("配合【" + ((Feature)SwMate).Name + "】参考对象:\r\n"); //配合名称 int n = SwMate.GetMateEntityCount(); for (int i = 0; i < n; i++) //配合参考 { MateEntity2 SwMateEntity2 = SwMate.MateEntity(i); string reftype = Enum.Parse(typeof(swSelectType_e), SwMateEntity2.ReferenceType2.ToString().Trim()).ToString().Trim(); string comp = SwMateEntity2.ReferenceComponent.Name2; string refname = SwMateEntity2.Reference.Name; Sb.Append("部件【" + comp + "】,参考【" + refname + "】" + ",类型【" + reftype + "】"); DisplayDimension SwDispDim = SwMate.DisplayDimension2[0]; if (SwDispDim != null) { if (SwMate.Type == (int)swMateType_e.swMateANGLE) { Sb.Append(",角度=" + SwDispDim.GetDimension2(0).Value.ToString().Trim()); } else if (SwMate.Type == (int)swMateType_e.swMateDISTANCE) { Sb.Append(",尺寸=" + SwDispDim.GetDimension2(0).Value.ToString().Trim()); } } Sb.Append("\r\n"); } Sb.Append("\r\n"); } } System.Windows.MessageBox.Show(Sb.ToString().Trim()); }
private void ReloadAllSetParameters(Component2 swTestSelComp) { #region Очистить все словари местные переменные int downPos = 0; //закоменчено, т.к. этот код вызывает ошибку внутри солида и его закрытие. //замена на похожие методы (ClearSelection2 и т.п.) не помогает /*/ if (!_isMate) { _swAsmDoc.NewSelectionNotify -= NewSelection; _swModel.ClearSelection(); _swAsmDoc.NewSelectionNotify += NewSelection; } /*/ _dictHeightPage.Clear(); _dictPathPict.Clear(); _dictionary.Clear(); _dictConfig.Clear(); _commonList.Clear(); _objListChanged.Clear(); _setNewListForComboBox = true; _butPlusTxt.Clear(); _dimensionConfig.Clear(); _textBoxListForRedraw.Clear(); _numbAndTextBoxes.Clear(); _comboBoxListForRedraw.Clear(); _namesOfColumnNameFromDimLimits.Clear(); refobj = null; #endregion if (swTestSelComp != null) { if (_mSwAddin.GetParentLibraryComponent(swTestSelComp, out _swSelComp)) { ModelDoc2 specModel; _swSelComp = _mSwAddin.GetMdbComponentTopLevel(_swSelComp, out specModel); _swSelModel = _swSelComp.IGetModelDoc(); #region ссылочный эскиз //bool draft = (specModel.CustomInfo2["", "Required Draft"] == "Yes" || // specModel.CustomInfo2[specModel.IGetActiveConfiguration().Name, "Required Draft"] == "Yes"); //if (draft) //{ // tabMain.Location = new Point(8, 70); // var dir = new DirectoryInfo(Path.GetDirectoryName(_mSwAddin.SwModel.GetPathName())); // var paths = // dir.GetFiles( // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + ".SLDDRW", // SearchOption.AllDirectories); // string path=null; // if (paths.Any()) // path = paths[0].FullName; // else // { // if (SwAddin.needWait) // { // path = Path.Combine(Path.GetDirectoryName(specModel.GetPathName()), // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + // ".SLDDRW"); // ThreadPool.QueueUserWorkItem(CheckDWRexistAfterCopy, path); // } // } // if (!string.IsNullOrEmpty(path)) // { // linkLabel1.Name = path; // linkLabel1.Click += LinkLabel1Click; // string textInfo = specModel.CustomInfo2["", "Sketch Number"]; // if (textInfo == "" || textInfo == "0" || textInfo == "Sketch Number") // linkLabel1.Text = @"ЭСКИЗ № н/о"; // else // linkLabel1.Text = @"ЭСКИЗ № " + textInfo; // } // else // tabMain.Location = new Point(8, 40); //} //else //{ // tabMain.Location = new Point(8, 40); // linkLabel1.Text = ""; //} #endregion _lblPrm.Clear(); _btnPrm.Clear(); tbpParams.Controls.Clear(); tbpPos.Controls.Clear(); lblCompName.Text = _swSelComp.Name2; OleDbConnection oleDb; int i; if (_mSwAddin.OpenModelDatabase(_swSelModel, out oleDb)) { using (oleDb) { #region Обработка файла *.mdb if (!tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpPos); tabMain.Controls.Add(tbpParams); tabMain.Controls.Add(tbpPos); } if (Properties.Settings.Default.KitchenModeOn) { tabMain.SelectTab(tbpPos); } else { if (tabMain.SelectedTab != tbpParams) { tabMain.SelectTab(tbpParams); } } var oleSchem = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); OleDbCommand cm; OleDbDataReader rd; listForDimensions = new List<DimensionConfForList>(); #region Если есть objects if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "objects")) { _chkMeasure = new CheckBox { Appearance = Appearance.Button, Location = new Point(133, 12), Name = @"chkMeasure", Size = new Size(80, 24), Text = @"Измерить", TextAlign = ContentAlignment.MiddleCenter, UseVisualStyleBackColor = true }; tbpParams.Controls.Add(_chkMeasure); _chkMeasure.CheckedChanged += StartMeasure; i = 0; bool isNumber = false, isIdSlave = false, isAsmConfig = false, isFixedValues = false; #region Dimension Configuration if ( oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimension_conf")) { cm = new OleDbCommand("SELECT * FROM dimension_conf ORDER BY id", oleDb); rd = cm.ExecuteReader(); var outComps = new LinkedList<Component2>(); if (_mSwAddin.GetComponents( _swSelModel.IGetActiveConfiguration().IGetRootComponent2(), outComps, true, false)) { _dimensionConfig = Decors.GetListComponentForDimension(_mSwAddin, rd, outComps); _dimensionConfig.Sort((x, y) => x.Number.CompareTo(y.Number)); rd.Close(); } } #endregion var thisDataSet = new DataSet(); var testAdapter = new OleDbDataAdapter("SELECT * FROM objects", oleDb); testAdapter.Fill(thisDataSet, "objects"); testAdapter.Dispose(); bool captConfigBool = thisDataSet.Tables["objects"].Columns.Contains("captConf"); foreach (var v in thisDataSet.Tables["objects"].Columns) { var vc = (DataColumn)v; if (vc.ColumnName == "number") isNumber = true; if (vc.ColumnName == "idslave") { if (vc.DataType.Name != "String") MessageBox.Show( @"Неверно указан тип данных в столбце 'ismaster'", _mSwAddin.MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); isIdSlave = true; } if (vc.ColumnName == "mainasmconf" && _swSelModel.GetConfigurationCount() > 1) isAsmConfig = true; if (vc.ColumnName == "fixedvalues") isFixedValues = true; } thisDataSet.Clear(); if (Properties.Settings.Default.CheckParamLimits && oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimlimits")) { testAdapter = new OleDbDataAdapter("SELECT * FROM dimlimits", oleDb); testAdapter.Fill(thisDataSet, "dimlimits"); testAdapter.Dispose(); foreach (var v in thisDataSet.Tables["dimlimits"].Columns) { var vc = (DataColumn)v; _namesOfColumnNameFromDimLimits.Add(vc.ColumnName); } thisDataSet.Clear(); } string currentConf = _swSelComp.ReferencedConfiguration; 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(); #region Размеры #region Считывание данных из objects int k = 1; var dictWithDiscretValues = new Dictionary<string, List<int>>(); while (rd.Read()) { if (captConfigBool && rd["captConf"] != null && rd["captConf"].ToString() != "all" && rd["captConf"].ToString() != currentConf && !string.IsNullOrEmpty(rd["captConf"].ToString())) continue; if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" || rd["caption"].ToString().Trim() == "") continue; #region Обработка поля mainasmconf if (isAsmConfig) { var neededConf = rd["mainasmconf"].ToString(); bool isNeededConf = neededConf.Split('+').Select(v => v.Trim()).Any( f => f == currentConf); if (neededConf == "all") isNeededConf = true; if (!isNeededConf) continue; } #endregion string strObjName = rd["name"].ToString(); double strObjVal; if (_swSelModel.GetPathName().Contains("_SWLIB_BACKUP")) { string pn = Path.GetFileNameWithoutExtension(_swSelModel.GetPathName()); 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]); } if (_mSwAddin.GetObjectValue(_swSelModel, strObjName, (int)rd["type"], out strObjVal)) { int val = GetCorrectIntValue(strObjVal); int number = isNumber ? (int)rd["number"] : (int)rd["id"]; while (number != k && _dimensionConfig.Count != 0) { listForDimensions.AddRange( from dimensionConfiguration in _dimensionConfig where dimensionConfiguration.Number == k select new DimensionConfForList(dimensionConfiguration.Number, dimensionConfiguration.Caption, "", -1, GetListIntFromString( dimensionConfiguration. IdSlave), dimensionConfiguration. Component, false, dimensionConfiguration.Id)); //Logging.Log.Instance.Debug("listForDimensions1:" + listForDimensions.Count.ToString()); k++; } var listId = new List<int>(); try { if (isIdSlave) listId = GetListIntFromString((string)rd["idslave"]); } catch { listId = null; } string labelName; try { labelName = rd["caption"].ToString(); } catch { string[] strObjNameParts = strObjName.Split('@'); labelName = strObjNameParts[0]; } if (isFixedValues) { try { var arr = (string)rd["fixedvalues"]; string[] arrs = arr.Split(','); var list = arrs.Select(s => Convert.ToInt32(s)).ToList(); if (!dictWithDiscretValues.ContainsKey(strObjName)) dictWithDiscretValues.Add(strObjName, list); } catch { } } listForDimensions.Add(new DimensionConfForList(number, labelName, strObjName, val, listId, null, (bool)rd["ismaster"], (int)rd["id"])); //Logging.Log.Instance.Debug("listForDimensions2:" + listForDimensions.Count.ToString()); k++; } } rd.Close(); #endregion listForDimensions.AddRange( _dimensionConfig.Where(x => x.Number >= k).Select( b => new DimensionConfForList(b.Number, b.Caption, "", -1, GetListIntFromString(b.IdSlave), b.Component, false, b.Id))); listForDimensions.Sort((x, y) => x.Number.CompareTo(y.Number)); //Logging.Log.Instance.Debug("listForDimensions3:" + listForDimensions.Count.ToString()); foreach (var dimensionConfForList in listForDimensions) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = dimensionConfForList.LabelName; lblNew.Tag = dimensionConfForList.StrObjName; tbpParams.Controls.Add(lblNew); _lblPrm.AddLast(lblNew); downPos = lblNew.Location.Y + lblNew.Size.Height; if (dimensionConfForList.StrObjName != "") { #region TextBox с размерами if (dictWithDiscretValues.ContainsKey(dimensionConfForList.StrObjName)) { #region Если дискретные значения var comboBoxWithDiscretValues = new ComboBox { Size = new Size(53, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = dimensionConfForList.StrObjName, TabIndex = i }; int val = dimensionConfForList.ObjVal; foreach (int vals in dictWithDiscretValues[dimensionConfForList.StrObjName]) { int ordNumb = comboBoxWithDiscretValues.Items.Add(vals); if (vals == val) comboBoxWithDiscretValues.SelectedIndex = ordNumb; } tbpParams.Controls.Add(comboBoxWithDiscretValues); _comboBoxListForRedraw.Add(comboBoxWithDiscretValues, dimensionConfForList.IdSlave); comboBoxWithDiscretValues.SelectedIndexChanged += ComboBoxWithDiscretValuesSelectedIndexChanged; #endregion } else { #region Если обычные значения int val = GetCorrectIntValue(dimensionConfForList.ObjVal); var txtNew = new TextBox { Size = new Size(35, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Name = lblNew.Text + "@" + dimensionConfForList.ObjVal, Text = val.ToString(), TextAlign = HorizontalAlignment.Right, Tag = dimensionConfForList.StrObjName, TabIndex = i }; _numbAndTextBoxes.Add(dimensionConfForList.Id, txtNew); if (!dimensionConfForList.IsGrey) txtNew.ReadOnly = true; else { _textBoxListForRedraw.Add(txtNew, dimensionConfForList.IdSlave); txtNew.KeyDown += TxtPrmKeyDown; txtNew.TextChanged += TxtNewTextChanged; var btnNew = new Button { ImageKey = @"Units1.ico", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + 4, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = txtNew.Name, Enabled = false }; if (!_butPlusTxt.ContainsKey(btnNew)) _butPlusTxt.Add(btnNew, txtNew); tbpParams.Controls.Add(btnNew); _btnPrm.AddLast(btnNew); btnNew.Click += MeasureLength; #region если есть таблица ref_objects и в ней есть хоть одна строка с соотв-щем id if (refobj == null) { refobj = new List<ref_object>(); if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "ref_objects_axe")) { cm = new OleDbCommand("SELECT * FROM ref_objects LEFT JOIN ref_objects_axe ON ref_objects_axe.id=ref_objects.objectsId", oleDb); rd = cm.ExecuteReader(); while (rd.Read()) { refobj.Add(new ref_object((string)rd["componentName"], (int)rd["objectsId"], (string)rd["axe"], (float)rd["correctionLeft_Up"], (float)rd["correctionRight_Down"])); } rd.Close(); } } ref_object[] currentrefs = refobj.Where(d => d.ObjectId == dimensionConfForList.Id).ToArray(); if (currentrefs.Length > 0) { //добавить кнопку //выбрать из refobj только dimensionConfigForList.Id var btnRef = new Button { ImageKey = @"expand.gif", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + btnNew.Size.Width + 8, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = currentrefs, Enabled = true }; tbpParams.Controls.Add(btnRef); //_btnPrm.AddLast(btnNew); btnRef.Click += ExpandBtn; if (!_butPlusTxt.ContainsKey(btnRef)) _butPlusTxt.Add(btnRef, txtNew); } #endregion } tbpParams.Controls.Add(txtNew); _commonList.Add(txtNew); #endregion } #endregion } else { #region ComboBox с конфигурациями var cmp = dimensionConfForList.Component; var comboBoxConfForDimTab = new ComboBox { Size = new Size(56, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = cmp, TabIndex = i }; var confNames = (string[])cmp.IGetModelDoc().GetConfigurationNames(); foreach (var confName in confNames) { int lonhName = confName.Length * 6; if (comboBoxConfForDimTab.DropDownWidth < lonhName) comboBoxConfForDimTab.DropDownWidth = lonhName; comboBoxConfForDimTab.Items.Add(confName); } comboBoxConfForDimTab.SelectedItem = cmp.ReferencedConfiguration; tbpParams.Controls.Add(comboBoxConfForDimTab); _comboBoxListForRedraw.Add(comboBoxConfForDimTab, dimensionConfForList.IdSlave); comboBoxConfForDimTab.SelectedIndexChanged += ComboBoxConfForDimTabSelectedIndexChanged; #endregion } i++; } #region Добавить выбор конфигурации try { if (_swSelModel.GetConfigurationCount() > 1) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = "Конфигурации:"; tbpParams.Controls.Add(lblNew); //lblNew.Tag = dimensionConfForList.StrObjName; downPos = lblNew.Location.Y + lblNew.Size.Height; string[] configurations = _swSelModel.GetConfigurationNames(); var comboBoxConfig = new ComboBox { Size = new Size(56, 24), Location = new Point(lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), }; string activeConf = _swSelComp.ReferencedConfiguration;//_swSelModel.IGetActiveConfiguration().Name; foreach (var configuration in configurations) { int currentIndex = comboBoxConfig.Items.Add(configuration); if (configuration == activeConf) comboBoxConfig.SelectedIndex = currentIndex; } Size size = TextRenderer.MeasureText(activeConf, comboBoxConfig.Font); int lonhName = size.Width; //nameOfConfiguration.Length * 5; if (comboBoxConfig.DropDownWidth < lonhName) comboBoxConfig.DropDownWidth = lonhName; tbpParams.Controls.Add(comboBoxConfig); comboBoxConfig.SelectedIndexChanged += ConfigurationChanged; } } catch { } #endregion #endregion _dictHeightPage.Add(tbpParams, downPos); } #endregion #region Если есть comments if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "comments")) { cm = new OleDbCommand("SELECT * FROM comments ORDER BY id", oleDb); rd = cm.ExecuteReader(); if (rd.Read()) { try { CommentLayout.Visible = true; WarningPB.Visible = (bool)rd["showSimbol"]; commentsTb.Text = (string)rd["comment"]; Size size = TextRenderer.MeasureText(commentsTb.Text, commentsTb.Font); commentsTb.Height = (size.Width / (commentsTb.Width - 10)) * 30; } catch { CommentLayout.Visible = false; } } rd.Close(); } else { CommentLayout.Visible = false; } #endregion #region Decors if (!ReloadDecorTab(oleDb, oleSchem)) return; #endregion oleDb.Close(); #endregion } } else if (_tabDec != null) tabMain.Controls.Remove(_tabDec); var swFeat = (Feature)_swSelModel.FirstFeature(); i = 0; #region Position var mates = _swSelComp.GetMates(); Dictionary<string, Mate2> existingMates = new Dictionary<string, Mate2>(); 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(_swSelComp.Name)) { Entity tt = me.Reference; var tt2 = tt as Feature; if (tt is RefPlane && tt2 != null) { if (!existingMates.ContainsKey(tt2.Name)) existingMates.Add(tt2.Name, spec); } } } } } } } int downPosPosition = 0; int tabIndex = 0; while (swFeat != null) { if (swFeat.GetTypeName2() == "RefPlane") { string strPlaneName = swFeat.Name; if (strPlaneName.Length > 1) { if (strPlaneName.Substring(0, 1) == "#") { var btnNew = new Button { Size = new Size(120, 20) }; btnNew.Location = new Point(62, 24 + i * (btnNew.Size.Height + 6)); //if (Properties.Settings.Default.KitchenModeOn) // btnNew.Name = strPlaneName;//"btnPos" + i; //else btnNew.Name = "btnPos" + i; btnNew.Text = strPlaneName.Substring(5); btnNew.Tag = strPlaneName; btnNew.TabIndex = tabIndex; tabIndex++; tbpPos.Controls.Add(btnNew); btnNew.Click += AddMate; downPosPosition = btnNew.Location.Y + btnNew.Size.Height; if (existingMates.ContainsKey(strPlaneName)) { //добавить кнопку для отвязки var btnDeattach = new Button { Size = new Size(20, 20) }; btnDeattach.Location = new Point(62 + btnNew.Size.Width + 10, 24 + i * (btnNew.Size.Height + 6)); btnDeattach.Name = strPlaneName; btnDeattach.Text = "X"; btnDeattach.Tag = existingMates[strPlaneName]; tbpPos.Controls.Add(btnDeattach); btnDeattach.Click += DeleteMate; } i++; } } } swFeat = (Feature)swFeat.GetNextFeature(); } _dictHeightPage.Add(tbpPos, downPosPosition); #endregion if (_lblPrm.Count == 0) { tabMain.SelectTab(tbpPos); downPos = downPosPosition; SetSizeForTab(downPos); if (tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpParams); //Logging.Log.Instance.Fatal("Вкладка на РПД не показана.Смотреть listForDimensions"); } } if (rbMode1 != null && rbMode2 != null) { if (controlsToHideWhenChangeMode == null || controlsToHideWhenChangeMode.Count == 0) pnlMode.Visible = false; if (Properties.Settings.Default.DefaultRPDView) { rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); rbMode1.Checked = true; } else { rbMode2.Checked = true; rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); } } SetSizeForTab(_dictHeightPage[tabMain.SelectedTab]); } } }
public void SelectContraintes() { try { EffacerContraintes(); Component2 cpMarche = MdlBase.eSelect_RecupererComposant(1, _Select_Marche.Marque); Feature fRepet = MdlBase.eSelect_RecupererObjet <Feature>(1, _Select_FonctionRepet.Marque); Component2 cpRepet = MdlBase.eSelect_RecupererComposant(1, _Select_FonctionRepet.Marque); Object[] Contraintes = cpMarche.GetMates(); if (cpMarche.IsNull() || fRepet.IsNull() || cpRepet.IsNull() || Contraintes.IsNull()) { return; } CurveDrivenPatternFeatureData def = fRepet.GetDefinition(); Object[] tabB = def.PatternBodyArray; Body2 b = (Body2)tabB[0]; foreach (Mate2 m in Contraintes) { MateEntity2 m1 = m.MateEntity(0); MateEntity2 m2 = m.MateEntity(1); if (AppartientAuCorps(cpRepet, b, m1)) { if ((m1.ReferenceType2 == (int)swSelectType_e.swSelVERTICES) && PointCorps.IsNull()) { PointCorps = m1.Reference; PointMarche = m2.Reference; } else if ((m1.ReferenceType2 == (int)swSelectType_e.swSelEDGES) && ArreteCorps.IsNull()) { ArreteCorps = m1.Reference; AxeMarche = m2.Reference; } } else if (AppartientAuComposant(cpRepet, m1) && (m1.ReferenceType2 == (int)swSelectType_e.swSelDATUMPLANES) && PlanComp.IsNull()) { PlanComp = m1.Reference; PlanMarche = m2.Reference; } else if (AppartientAuCorps(cpRepet, b, m2)) { if ((m2.ReferenceType2 == (int)swSelectType_e.swSelVERTICES) && PointCorps.IsNull()) { PointCorps = m2.Reference; PointMarche = m1.Reference; } else if ((m2.ReferenceType2 == (int)swSelectType_e.swSelEDGES) && ArreteCorps.IsNull()) { ArreteCorps = m2.Reference; AxeMarche = m1.Reference; } } else if (AppartientAuComposant(cpRepet, m2) && (m2.ReferenceType2 == (int)swSelectType_e.swSelDATUMPLANES) && PlanComp.IsNull()) { PlanComp = m2.Reference; PlanMarche = m1.Reference; } } MdlBase.eSelectMulti(PointCorps, _Select_Contraintes_PointCorps.Marque, true); MdlBase.eSelectMulti(PointMarche, _Select_Contraintes_PointMarche.Marque, true); MdlBase.eSelectMulti(ArreteCorps, _Select_Contraintes_ArreteCorps.Marque, true); MdlBase.eSelectMulti(AxeMarche, _Select_Contraintes_AxeMarche.Marque, true); MdlBase.eSelectMulti(PlanComp, _Select_Contraintes_PlanComp.Marque, true); MdlBase.eSelectMulti(PlanMarche, _Select_Contraintes_PlanMarche.Marque, true); ContraintesVide = false; } catch (Exception e) { this.LogMethode(new Object[] { e }); } }
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); } }
protected override void Command() { Ass = MdlBase.eAssemblyDoc(); try { CurveDrivenPatternFeatureData def = FonctionRepetition.GetDefinition(); Object[] tabB = def.PatternBodyArray; Body2 b = (Body2)tabB[0]; MathTransform compRepetTrans = ComposantRepetition.Transform2; MathTransform baseMarcheTrans = Marche.Transform2; Vertex v = (Vertex)Point; Edge e = (Edge)Arrete; List <Face2> ListeFace = FonctionRepetition.eListeDesFaces(); Sketch sk = PointMarche.GetSketch(); Feature fPointMarche = (Feature)sk; List <Component2> ListeComposants = new List <Component2>() { Marche }; Double arr = 0.0001; for (int i = 1; i <= (def.D1InstanceCount + def.D2InstanceCount); i++) { MathTransform bodyTrans = def.GetTransform(i); if (bodyTrans.IsNull()) { break; } MathTransform Transform = compRepetTrans.Inverse(); Transform = Transform.Multiply(bodyTrans); Transform = Transform.Multiply(compRepetTrans); Transform = baseMarcheTrans.Multiply(Transform); gPoint pt = new gPoint(v); gSegment sg = new gSegment(e); pt.MultiplyTransfom(bodyTrans); sg.MultiplyTransfom(bodyTrans); Vertex vertex = null; Edge edge = null; foreach (Face2 face in ListeFace) { foreach (Edge ed in face.eListeDesArretes()) { gSegment s = new gSegment(ed); if (sg.Compare(s, arr)) { edge = ed; } if (s.Start.Comparer(pt, arr)) { vertex = ed.GetStartVertex(); } if (s.End.Comparer(pt, arr)) { vertex = ed.GetEndVertex(); } if (edge.IsRef() && vertex.IsRef()) { break; } } if (edge.IsRef() && vertex.IsRef()) { break; } } Entity eVertex = (Entity)vertex; Entity eEdge = (Entity)edge; Component2 cp = Ass.AddComponent5(Marche.GetPathName(), (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", 0, 0, 0); if (cp.IsNull()) { continue; } // Quand on réinsere un composant, les précédentes contraintes sont recrées. // On les supprime pour eviter des conflits Object[] Mates = cp.GetMates(); if (Mates.IsRef()) { foreach (Feature mate in Mates) { mate.eSelect(); MdlBase.Extension.DeleteSelection2((int)swDeleteSelectionOptions_e.swDelete_Absorbed); } } WindowLog.Ecrire(cp.Name2); cp.Transform2 = Transform; ListeComposants.Add(cp); int longstatus = 0; MdlBase.eEffacerSelection(); eVertex.eSelectEntite(false); Feature f = cp.FeatureByName(fPointMarche.Name); Sketch sketchOrigine = f.GetSpecificFeature2(); Object[] tabPt = sketchOrigine.GetSketchPoints2(); SketchPoint origine = (SketchPoint)tabPt[0]; origine.Select4(true, null); Mate2 mPoint = Ass.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignCLOSEST, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); eEdge.eSelectEntite(false); cp.FeatureByName(AxeMarche.Name).eSelect(true); Mate2 mAxe = Ass.AddMate5((int)swMateType_e.swMateANGLE, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); Plan.eSelect(false); cp.FeatureByName(PlanMarche.Name).eSelect(true); Mate2 mPlan = Ass.AddMate5((int)swMateType_e.swMatePARALLEL, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); Feature m = (Feature)mPoint; WindowLog.Ecrire(" " + m.Name); m = (Feature)mAxe; WindowLog.Ecrire(" " + m.Name); m = (Feature)mPlan; WindowLog.Ecrire(" " + m.Name); } MdlBase.eEffacerSelection(); foreach (var cp in ListeComposants) { cp.eSelectById(MdlBase, -1, true); } Feature Dossier = MdlBase.FeatureManager.InsertFeatureTreeFolder2((int)swFeatureTreeFolderType_e.swFeatureTreeFolder_Containing); Dossier.eRenommerFonction(String.Format("Marches ({0} {1}) ", ComposantRepetition.Name2, FonctionRepetition.Name)); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }