//BCOM.LineElement[] CreateAxisGrid() //{ // Tuple<BCOM.Point3d, BCOM.Point3d> temp = new Tuple<BCOM.Point3d, BCOM.Point3d>(app.Point3dZero(), app.Point3dZero()); // app.createli //} public void CreateMap() { BCOM.ModelReference modelref = AddNewModelReference("桩位图"); modelref.Activate(); List <BCOM.Element> elelist = new List <BCOM.Element>(); BG.DVector3d pilevector; foreach (var pile in Piles) { pilevector = new BG.DVector3d(pile.PilePropertyInfo.PileTopPoint.Point3dToDPoint3d(), pile.PilePropertyInfo.PileBottomPoint.Point3dToDPoint3d()); if (!pilevector.IsParallelOrOppositeTo(BG.DVector3d.UnitZ)) { elelist.AddRange(CreateArrowElement(pile.PilePropertyInfo.PileTopPoint, pile.PilePropertyInfo)); } elelist.Add(CreatePileSkewnessText(pile.PilePropertyInfo)); elelist.Add(CreatePileCrossSectionElement(pile.PilePropertyInfo)); elelist.Add(CreatePilePositionText(pile.PilePropertyInfo.PileTopPoint, pile.PileCode)); } foreach (var ele in elelist) { app.ActiveModelReference.AddElement(ele); } app.MessageCenter.AddMessage("桩位图绘制完成", "请在[桩位图]模型中查看", BCOM.MsdMessageCenterPriority.Info); }
/*-----------------------------------------------------------------------------*/ /// <summary> /// open a connection to a model does not have to be the active model /// </summary> /// <param name="oModel">the model that is being used as repository</param> /// <param name="ecSession">the session</param> /// <returns></returns> /*-----------------------------------------------------------------------------*/ public static ECSR.RepositoryConnection OpenConnectionToModel( BCOM.ModelReference oModel, ECSS.ECSession ecSession) { ECSR.RepositoryConnectionService repositoryConnectionService; repositoryConnectionService = ECSR.RepositoryConnectionServiceFactory.GetService(); string fileName = oModel.DesignFile.FullName; // implies active file string modelName = oModel.Name; // implies active model string location; location = BECP.Common.ECRepositoryConnectionHelper.BuildLocation( fileName, modelName); string ecPluginId = BDGNP.Constants.PluginID; #if DEBUG System.Diagnostics.Debug.WriteLine("location = " + location); System.Diagnostics.Debug.WriteLine("PluginID = " + ecPluginId); #endif ECSR.RepositoryConnection connection; connection = repositoryConnectionService.Open(ecSession, ecPluginId, location, null, null); System.Diagnostics.Debug.Assert(null != connection); string fsrPlugin = BFSRP.FSRClientHelper.FSRPluginId; return(connection); }
public static void AddToModel(this TFCOM.TFFrameList frameList, BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; AppTF.ModelReferenceAddFrameList(App.ActiveModelReference, frameList); frameList.ForceRedrawPerforator(); }
public static void ExportToCsv() { BCOM.ModelReference model = App.ActiveModelReference; BCOM.ElementScanCriteria criteria = new BCOM.ElementScanCriteriaClass(); criteria.ExcludeAllTypes(); criteria.ExcludeNonGraphical(); criteria.IncludeType(BCOM.MsdElementType.CellHeader); BCOM.ElementEnumerator iter = App.ActiveModelReference.Scan(criteria); var builder = new StringBuilder(); string dltr = ";"; while (iter.MoveNext()) { BCOM.Element element = iter.Current; XDocument xDoc = ElementHelper.getSp3dXDocument(element.ToElement()); var dgPropColl = new Dictionary <Sp3dToDataGroupMapProperty, string>(); Sp3dToDGMapping.Instance.LoadValuesFromXDoc(xDoc, dgPropColl, true); if (builder.Length == 0) { // строка заголовков: builder.Append("ElementId"); foreach (var pair in dgPropColl) { builder.Append(dltr + pair.Key.TargetName); } builder.AppendLine(); } builder.Append(element.ID); foreach (var pair in dgPropColl) { builder.Append(dltr + pair.Value); } builder.AppendLine(); } string path = Path.ChangeExtension(App.ActiveDesignFile.FullName, ".csv"); File.WriteAllText(path, builder.ToString()); if (File.Exists(path)) { System.Diagnostics.Process.Start(path); App.MessageCenter.AddMessage($"SUCCESS: экспорт '{path}'", "", BCOM.MsdMessageCenterPriority.None, false); } else { App.MessageCenter.AddMessage($"FAILED: экспорт '{path}'", "", BCOM.MsdMessageCenterPriority.Warning, false); } }
public static BCOM.Element getElementCOM(AddIn.SelectionChangedEventArgs eventArgs) { BCOM.ModelReference activeModel = App.MdlGetModelReferenceFromModelRefP(eventArgs.DgnModelRef.GetNative()); var cache = activeModel.ElementCacheContainingFilePosition( (int)eventArgs.FilePosition); int index = cache.IndexFromFilePosition((int)eventArgs.FilePosition); return(cache.GetElement(index)); }
private void DgvFields_SelectionChanged(object sender, EventArgs e) { // выделить(подсветить) объект задания в модели для пользователя selectionTranContainer?.Reset(); foreach (DataGridViewRow row in dgvFields.SelectedRows) { PenetrTask task = (PenetrTask)dgvFields.Rows[row.Index].DataBoundItem; BCOM.ModelReference modelRef = Addin.App.MdlGetModelReferenceFromModelRefP((int)task.modelRefP); BCOM.View view = ViewHelper.getActiveView(); List <long> itemsIds = new List <long> { task.elemId }; // добавляем фланцы: foreach (PenetrTaskFlange flangeTask in task.FlangesGeom) { itemsIds.Add(flangeTask.elemId); } foreach (long id in itemsIds) { BCOM.Element el = modelRef.GetElementByID(id); el.Color = 2; // зелёный el.LineWeight = 5; // для ОТЛАДКИ ************************************************* //BCOM.Transform3d taskTran; //{ // BCOM.Point3d origin = (el as BCOM.CellElement).Origin; // var shift = Addin.App.Vector3dSubtractPoint3dPoint3d( // Addin.App.Point3dZero(), task.Location); // el.Move(Addin.App.Point3dFromXYZ(shift.X, shift.Y, shift.Z)); // taskTran = Addin.App.Transform3dInverse( // Addin.App.Transform3dFromMatrix3d(task.Rotation)); // el.Transform(taskTran); // el.Move(task.Location); //} //************************************************************** selectionTranContainer.AppendCopyOfElement(el); } view.Redraw(); } }
/*-----------------------------------------------------------------------------*/ /// <summary> /// This tries to remove the reference files so they are not loaded in the process. /// </summary> /*-----------------------------------------------------------------------------*/ public static void CleanOffRefFiles() { BCOM.ModelReference oModel = BVSchemaChecker.ComApp.ActiveModelReference; int iAttachmentCount = oModel.Attachments.Count; for (int i = iAttachmentCount; i > 0; --i) { BCOM.Attachment oAtt = oModel.Attachments[i]; oModel.Attachments.Remove(oAtt); } return; }
//public static BCOM.Level getLevel(string name) //{ // BCOM.Levels levels = App.ActiveDesignFile.Levels; // var activeModel = App.ActiveModelReference; // activeModel.Levels.IncludeHidden = true; // try // { // return activeModel.Levels[name]; // } // catch (Exception) {} // не найден // BCOM.Level activeLevel = App.ActiveSettings.Level; // try // { // Addin.Instance.sendKeyin( // string.Format("level set active {0}", name)); // activeModel.Levels.IncludeHidden = true; // return activeModel.Levels[name]; // } // catch (Exception) // { // return null; // } // finally // { // App.ActiveSettings.Level = activeLevel; // } //} //public static BCOM.Level getLevelOrActive(string name) //{ // return getLevel(name) ?? App.ActiveSettings.Level; //} /// <summary> /// Поиск пересечений с элементами по диапазону заданного элемента в /// в пространстве заданной модели /// </summary> public static IEnumerable <BCOM.Element> scanIntersectsInElementRange( this BCOM.Element element, BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; BCOM.ElementScanCriteria criteria = new BCOM.ElementScanCriteriaClass(); criteria.ExcludeAllTypes(); criteria.ExcludeNonGraphical(); criteria.IncludeType(BCOM.MsdElementType.CellHeader); BCOM.Range3d scanRange = getElementScanRange(element, model); criteria.IncludeOnlyWithinRange(scanRange); return(model.Scan(criteria).BuildArrayFromContents()); }
public static BCOM.Attachment AsAttachment(this BCOM.ModelReference model, BCOM.ModelReference owner = null) { owner = owner ?? App.ActiveModelReference; foreach (BCOM.Attachment attach in owner.Attachments) { // равенство работает только для версии V8i if (attach.MdlModelRefP() == model.MdlModelRefP()) { return(attach); } } return(null); }
private BCOM.CellElement getTaskCell() { BCOM.ModelReference taskModel = // TODO App.MdlGetModelReferenceFromModelRefP(modelRefP); BCOM.ModelReference activeModel = App.ActiveModelReference; bool isAttachment = taskModel.IsAttachment; BCOM.CellElement cell = taskModel.IsAttachment ? taskModel.AsAttachment.GetElementByID(elemId).AsCellElement() : taskModel.GetElementByID(elemId).AsCellElement(); return(cell); }
public static BCOM.Range3d getElementScanRange( BCOM.Element element, BCOM.ModelReference model = null) { BCOM.Range3d scanRange = element.Range; #if CONNECT // корректировака для версии CONNECT if (element.ModelReference.IsAttachmentOf(model)) { // здесь есть различия с V8i: // TODO проверить double k = model.UORsPerStorageUnit / element.ModelReference.UORsPerStorageUnit; scanRange.High = App.Point3dScale(scanRange.High, k); scanRange.Low = App.Point3dScale(scanRange.Low, k); } #endif return(scanRange); }
private bool addToModel_(BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; BCOM.Element element; FrameList.GetElement(out element); if (element.ID != 0 && element.ModelReference == model) { return(true); } FrameList.AddToModel(model); FrameList.GetElement(out element); bool res = element.ID != 0; return(res); }
public void changeSelection(IEnumerable <DataRow> selection) { selectionTranCon_?.Reset(); foreach (DataRow taskRow in selection) { PenetrVueTask task = rowsToTasks_[taskRow]; BCOM.ModelReference modelRef = task.ModelRef; BCOM.View view = ViewHelper.getActiveView(); var taskUOR = new UOR(task.ModelRef); var activeUOR = new UOR(App.ActiveModelReference); List <long> itemsIds = new List <long> { task.elemId }; // добавляем фланцы: foreach (PenetrTaskFlange flangeTask in task.FlangesGeom) { itemsIds.Add(flangeTask.elemId); } foreach (long id in itemsIds) { BCOM.Element temp = modelRef.GetElementByID(id).Clone(); temp.Color = 2; // зелёный temp.LineWeight = 5; #if CONNECT // для версии CONNECT требуется поправка // в V8i возмоно она производится автоматически BCOM.Attachment attachment = task.getAttachment(); if (attachment != null) { temp.Transform(attachment.GetReferenceToMasterTransform()); } #endif selectionTranCon_.AppendCopyOfElement(temp); } } }
/*-----------------------------------------------------------------------------*/ /// <summary> /// checks to see if there is an imodel. /// </summary> /// <param name="pModel">the root model to search for references</param> /// <returns>true the model has an i-model referenced in.</returns> /*-----------------------------------------------------------------------------*/ public static bool HasIModelReference(BCOM.ModelReference pModel) { try { if (!pModel.IsAttachment || (pModel.IsAttachment && !pModel.AsAttachment.IsMissingFile)) { if (1 == IsIModel(pModel.MdlModelRefP())) { return(true); } } foreach (BCOM.Attachment oAttachment in pModel.Attachments) { BCOM.ModelReference rModel = (BCOM.ModelReference)oAttachment; if (!oAttachment.IsMissingFile) { if (1 == IsIModel(rModel.MdlModelRefP())) { return(true); } } foreach (BCOM.Attachment a in oAttachment.Attachments) { return(HasIModelReference((BCOM.ModelReference)a)); } } } catch (System.Reflection.TargetException te) { ComApp.MessageCenter.AddMessage("Exception on the isIModel call", "The Has IModel code has failed to detect an i-model", BCOM.MsdMessageCenterPriority.Error, false); } //if it makes it here must not be an imodel return(false); }
private bool addToModel_(BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; BCOM.Level level = ElementHelper.GetOrCreateLevel(LevelName); App.ActiveSettings.SetByLevel(level); BCOM.Element element; FrameList.GetElement(out element); if (element.ID != 0 && element.ModelReference == model) { return(true); } FrameList.AddToModel(model); FrameList.GetElement(out element); bool res = element.ID != 0; return(res); }
public static BCOM.Attachment AsAttachment(this BCOM.ModelReference model, BCOM.ModelReference owner = null) { owner = owner ?? App.ActiveModelReference; foreach (BCOM.Attachment attach in owner.Attachments) { //if (attach.IsMissingFile || attach.IsMissingModel) // continue; try { // attach.DesignFile в некоторых случаях выбрасывает ошибку // attach.IsMissingFile - не помогает if (attach.DesignFile.MdlModelRefP() == model.MdlModelRefP()) { return(attach); } } catch (Exception) {} } return(null); }
/// <summary> /// Поиск коллизий и пересечений /// </summary> public void scanInfo() { (TFFormsIntersected ?? (TFFormsIntersected = new List <TFCOM.TFElementList>())).Clear(); (CompoundsIntersected ?? (CompoundsIntersected = new List <TFCOM.TFElementList>())).Clear(); BCOM.ModelReference activeModel = App.ActiveModelReference; scanInfoPerModel(activeModel); // TODO удостовериться в корректности алгоритма относительно входящих // референсов foreach (BCOM.Attachment attachment in activeModel.Attachments) { if (!attachment.DisplayFlag) { continue; } scanInfoPerModel(App.MdlGetModelReferenceFromModelRefP( attachment.MdlModelRefP())); } }
public bool AddToModel(bool recoverSettings = true, BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; bool res = false; CatchExceptionsByMessageCenter(() => { if (recoverSettings) { ElementHelper.RunByRecovertingSettings(() => { res = addToModel_(model); }); } else { res = addToModel_(model); } // DataGroup свойства: res |= SetDataGroupInstance_(); }); return(res); }
public bool AddToModel(bool recoverSettings = true, BCOM.ModelReference model = null) { model = model ?? App.ActiveModelReference; bool res = false; BCOM.Level level = ElementHelper.GetOrCreateLevel(LEVEL_NAME); App.ActiveSettings.SetByLevel(level); if (recoverSettings) { ElementHelper.RunByRecovertingSettings(() => { res = addToModel_(model); }); } else { res = addToModel_(model); } // DataGroup свойства: res |= SetDataGroupInstance(); return(res); }
private void findFlanges() { BCOM.CellElement cell = getTaskCell(); if (cell == null) { return; } BCOM.ModelReference taskModel = // TODO App.MdlGetModelReferenceFromModelRefP(modelRefP); BCOM.ModelReference activeModel = App.ActiveModelReference; FlangesGeom.Clear(); // Поиск фланцев BCOM.ElementScanCriteria criteria = new BCOM.ElementScanCriteriaClass(); //criteria.IncludeOnlyVisible(); criteria.ExcludeAllTypes(); criteria.ExcludeNonGraphical(); criteria.IncludeType(BCOM.MsdElementType.CellHeader); BCOM.Range3d scanRange = cell.Range; // App.Range3dScaleAboutCenter(cell.Range, 1.01); if (taskModel.IsAttachment) { double k = taskModel.UORsPerStorageUnit / activeModel.UORsPerStorageUnit; scanRange.High = App.Point3dScale(scanRange.High, k); scanRange.Low = App.Point3dScale(scanRange.Low, k); } criteria.IncludeOnlyWithinRange(scanRange); BCOM.ElementEnumerator res = taskModel.Scan(criteria); foreach (BCOM.Element current in res?.BuildArrayFromContents()) { // todo использовать только один тип точек PenetrTaskFlange flangeTask = null; //Element curEl = Element.FromElementID((ulong)current.ID, // (IntPtr)current.ModelReference.MdlModelRefP()); if (PenetrTaskFlange.getFromElement(current, out flangeTask)) { BCOM.Range3d range = current.Range; if (flangeTask.Oid.Equals(Oid)) { FlangesGeom.Add(flangeTask); } } } //BCOM.Transform3d tran = App.Transform3dInverse( // App.Transform3dFromMatrix3d(Rotation)); //cell.Transform(tran); // TODO проверить корректность transform отн. rawLocation_ transformToBase(cell, rawLocation_); if (FlangesCount != FlangesGeom.Count) { Warnings.Add(string.Format("Несоответствие количества фланцев, " + "указанных в атрибутах - {0} и заданных геометрически - {1}", FlangesCount, FlangesGeom.Count)); } if (FlangesCount == 1 && FlangesGeom.Count > 0) { BCOM.Element flangeEl = taskModel.GetElementByID(FlangesGeom[0].elemId); //flangeEl.Transform(tran); // TODO проверить корректность transform отн. rawLocation_ transformToBase(flangeEl, rawLocation_); SingleFlangeSide = App.Vector3dSubtractPoint3dPoint3d( ElementHelper.getCenter(flangeEl), ElementHelper.getCenter(cell)); } else { SingleFlangeSide = App.Vector3dFromXYZ(0, 0, -1); } }
/// <summary> /// Поиск фланцев на объекте задания старого типа /// </summary> private void findFlangesOld() { BCOM.ModelReference model = App.MdlGetModelReferenceFromModelRefP(modelRefP); SingleFlangeSide = App.Vector3dZero(); // Todo из правильной модели BCOM.CellElement cell = model.GetElementByID(elemId).AsCellElement(); if (cell == null) { return; } //var tran = App.Transform3dFromMatrix3d(Rotation); //if (App.Matrix3dHasInverse(Rotation)) //{ // tran = App.Transform3dInverse(tran); //} //var tran = App.Transform3dInverse( // App.Transform3dFromMatrix3d(Rotation)); //cell.Transform(tran); // TODO проверить корректность transform отн. rawLocation_ transformToBase(cell, rawLocation_); var cones = new List <BCOM.ConeElement>(); collectSubElementsByType(cell, ref cones); //var iter = bcomEl.AsCellElement().GetSubElements(); //while (iter.MoveNext()) //{ // var iterSub = iter.Current.AsCellElement().GetSubElements(); // while (iterSub.MoveNext()) // { // if (iterSub.Current.IsConeElement()) // cones.Add(iterSub.Current.AsConeElement()); // } //} cones.Sort((BCOM.ConeElement lhs, BCOM.ConeElement rhs) => { return(-1 * ElementHelper.getHeight(lhs).CompareTo( ElementHelper.getHeight(rhs))); }); /* cones.Count == * 2: без фланцев * 4: 1 фланец, определяем вектор с какой стороны фланец * 6: 2 фланца */ int geomFlangesCount = cones.Count / 2 - 1; if (geomFlangesCount == 1) { // 1 фланец, определяем вектор с какой стороны фланец относительно центра SingleFlangeSide = App.Vector3dSubtractPoint3dPoint3d( ElementHelper.getCenter(cones[2]), ElementHelper.getCenter(cones[0])); } else { // базовая ориентация при построении // фланец совпадает с Точкой установки SingleFlangeSide = App.Vector3dFromXYZ(0, 0, -1); } if (FlangesCount != geomFlangesCount) { Warnings.Add(string.Format("Несоответствие количества фланцев, " + "указанных в атрибутах - {0} и заданных геометрически - {1}", FlangesCount, geomFlangesCount)); } }
private static void scanRecurse(BCOM.ModelReference model, BCOM.ElementScanCriteria criteria) { BCOM.ElementEnumerator iter = App.ActiveModelReference.Scan(criteria); var errorColl = new Dictionary <BCOM.Element, List <TagToDataGroupMapProperty> >(); var successList = new List <BCOM.Element>(); int summaryCount = 0; iter.Reset(); while (iter.MoveNext()) { IEnumerable <TagToDataGroupMapProperty> mapTags; if (!ScanElementHasMappingTags(iter.Current, out mapTags)) { continue; } ++summaryCount; var skippedProps = new List <TagToDataGroupMapProperty>(); foreach (TagToDataGroupMapProperty mapTag in mapTags) { bool res = DataGroupHelper.SetDataGroupPropertyValue(iter.Current, mapTag.DataGroupCatalogType, mapTag.DataGroupInstance, mapTag.DataGroupXPath, mapTag.TagName, mapTag.Value); if (!res) { skippedProps.Add(mapTag); } } if (skippedProps.Count == 0) { successList.Add(iter.Current); } else { errorColl.Add(iter.Current, skippedProps); } } string brief = $"Команда 'Экспорт свойств из Tags в DataGroup', успешно: {successList.Count()}/{summaryCount}"; var builder = new StringBuilder(); builder.AppendLine($"*** С ошибками: {errorColl.Count()} из {summaryCount}"); if (errorColl.Count() > 0) { foreach (var pair in errorColl) { var element = pair.Key; var errProps = pair.Value; builder.AppendLine(element.ID.ToString() + ":"); foreach (TagToDataGroupMapProperty prop in errProps) { builder.AppendLine(" -" + XmlSerializerEx.ToXml(prop)); } } } builder.Append("\n\n"); builder.AppendLine($"*** Успешно: {successList.Count()} из {summaryCount}"); if (successList.Count() > 0) { foreach (var element in successList) { builder.AppendLine(element.ID.ToString()); } } #if V8i App.MessageCenter.AddMessage(brief, builder.ToString(), BCOM.MsdMessageCenterPriority.Info, true); #elif CONNECT Bentley.MstnPlatformNET.MessageCenter.Instance.ShowMessage(MessageType.Info, brief, builder.ToString(), MessageAlert.Dialog); #endif // TODO ОБРАБОТКА РЕФЕРЕНСОВ //foreach (BCOM.Attachment attachment in model.Attachments) //{ // if (!attachment.IsActive || !attachment.IsMissingFile || !attachment.IsMissingModel) // return; // ModelReference modelRef = // App.MdlGetModelReferenceFromModelRefP(attachment.MdlModelRefP()); // scanRecurse(modelRef, criteria); //} }
//private void testScan() //{ // if (Cell == null) // return; // var surfaces = new List<BCOM.Element>(); // collectSubElementsByType(Cell, ref surfaces, BCOM.MsdElementType.Surface); // if (surfaces.Count > 0) // { // ; // } // else // { // var cones = new List<BCOM.ConeElement>(); // collectSubElementsByType(Cell, ref cones); // ; // } //} private PenetrVueTask(Element element, Sp3dTask_Old task) { initialize_(element); P3Dbase taskData = task.isEquipment() ? (P3Dbase)task.equipment : task.pipe; Oid = taskData.Oid; BCOM.ModelReference taskModel = App.MdlGetModelReferenceFromModelRefP(modelRefP); //BCOM.Element bcomEl = taskModel.GetElementByID(elemId); Rotation = taskData.getRotation(); Code = taskData.Name.Trim(); User = taskData.SP3D_UserLastModified.Trim(); Path = taskData.SP3D_SystemPath; //BCOM.Point3d pt = App.Point3dFromXYZ( // taskData.LocationX, taskData.LocationY, taskData.LocationZ); rawLocation_ = App.Point3dScale(taskData.getLocation(), taskModel.IsAttachmentOf(App.ActiveModelReference) ? UOR.subPerMaster : 1); //#if V8i // rawLocation_ = App.Point3dScale(pt, // taskModel.IsAttachment ? UOR.subPerMaster : 1); //#elif CONNECT // var actDgnModel = Session.Instance.GetActiveDgnModel(); // rawLocation_ = App.Point3dScale(pt, // element.DgnModel.IsDgnAttachmentOf(actDgnModel) ? // UOR.subPerMaster : 1); //#endif this.TaskType = task.isEquipment() ? TaskTypeEnum.PipeEquipment : task.component?.Description == "PenFlange" ? TaskTypeEnum.Flange : task.component?.Description == "PntrtPlate-d" ? TaskTypeEnum.PipeOld : TaskTypeEnum.Pipe; // разбор типоразмера: parseTypeSize(taskData.Description); // Свойства DataGroup // task.XmlDoc.Root foreach (var propMap in Sp3dToDGMapping.Instance.Items) { if (propMap.TargetXPath == null) { continue; } foreach (string path in propMap.Sp3dXmlPaths) { string propName; var xEl = task.XmlDoc.Root.GetChildByRegexPath(path, out propName); //var xEl = xDoc.Root.XPathSelectElement(path); if (xEl != null) { string value = propMap.getMapValue(xEl.Value); DataGroupPropsValues.Add(propMap, value); } } } if (TaskType == TaskTypeEnum.Pipe) { findFlanges(); } else { findFlangesOld(); } scanInfo(); }
/*-----------------------------------------------------------------------------*/ /// <summary> /// looking at possible solution for a MIA file problem. uses the File /// api to see if the file exists. /// </summary> /// <param name="pModel">the model to check</param> /// <returns>true the file is on the drive</returns> /*-----------------------------------------------------------------------------*/ bool findFile(BCOM.ModelReference pModel) { string filePath = pModel.DesignFile.FullName; return(File.Exists(filePath)); }
/*-----------------------------------------------------------------------------*/ /// <summary> /// processes a dgn model to see if it has embedded schema /// </summary> /// <param name="oModel">the model to check</param> /// <returns>true that the model was processed and does not have a schema.</returns> /*-----------------------------------------------------------------------------*/ public static bool ProcessModel(BCOM.ModelReference oModel) { List <string> schemaList = new List <string>(); bool m_debugMode = false; bool m_silentMode = false; string errMessage = "ERROR"; bool bStatus = true; ECSR.RepositoryConnection connection = null; CSVReporter.CreateReport(string.Format("SC_{0}.csv", DateTime.Now.ToString("yyyy-dd-MM"))); if (m_debugMode) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("created csv file", string.Format("created report file at {0}", CSVReporter.FileName), BCOM.MsdMessageCenterPriority.Info, m_debugMode); } try { ECSS.ECSession ecSession = ECSS.SessionManager.CreateSession(true); connection = BVSchemaChecker.OpenConnectionToModel(oModel, ecSession); if (BVSchemaChecker.FindEmbededSchemas(connection, schemaList)) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("found schema in the file", "found Schema", BCOM.MsdMessageCenterPriority.Error, m_silentMode); BVSchemaChecker.iSchemaFoundCount++; SchemaListForm sform = new SchemaListForm(); sform.SetSchemaNames(schemaList); sform.ShowDialog(); bStatus = false; } else { BVSchemaChecker.ComApp.MessageCenter.AddMessage("no schema in the file", "nothing found", BCOM.MsdMessageCenterPriority.Info, m_silentMode); } } catch (Exception e) { BVSchemaChecker.ComApp.MessageCenter.AddMessage(e.Message, e.Message, BCOM.MsdMessageCenterPriority.Error, !BVSchemaChecker.bUseLogFile); errMessage = e.Message; bStatus = false; } finally { if (null == connection) { CSVReporter.writeLine(BVSchemaChecker.strCurrentProjectName, BVSchemaChecker.ComApp.ActiveDesignFile.Name, BVSchemaChecker.ComApp.ActiveModelReference.Name, errMessage, false); } else { BVSchemaChecker.CloseConnection(connection); } CSVReporter.close(); } return(bStatus); }
public UOR(BCOM.ModelReference target) { target_ = target; }
private void scanInfoPerModel(BCOM.ModelReference model) { BCOM.CellElement cell = getTaskCell(); if (cell == null) { return; } //BCOM.ModelReference activeModel = App.ActiveModelReference; BCOM.ElementScanCriteria criteria = new BCOM.ElementScanCriteriaClass(); criteria.ExcludeAllTypes(); criteria.ExcludeNonGraphical(); criteria.IncludeType(BCOM.MsdElementType.CellHeader); BCOM.Range3d scanRange = cell.Range; #if CONNECT // корректировака для версии CONNECT if (cell.ModelReference.IsAttachmentOf(model)) // TODO ПРОВЕРИТЬ { // здесь есть различия с V8i: double k = model.UORsPerStorageUnit / cell.ModelReference.UORsPerStorageUnit; scanRange.High = App.Point3dScale(scanRange.High, k); scanRange.Low = App.Point3dScale(scanRange.Low, k); } #endif criteria.IncludeOnlyWithinRange(scanRange); BCOM.ElementEnumerator res = model.Scan(criteria); foreach (BCOM.Element current in res?.BuildArrayFromContents()) { TFCOM.TFElementList tfList = AppTF.CreateTFElement(); tfList.InitFromElement(current); if (tfList.AsTFElement == null) { continue; } int tfType = tfList.AsTFElement.GetApplicationType(); if (tfList.AsTFElement.GetIsCompoundCellType()) { CompoundsIntersected.Add(tfList); } else if (tfList.AsTFElement.GetIsFormType()) { bool coorrectType = isAvaliableTFFromType(tfType); if (isAvaliableTFFromType(tfType)) { TFFormsIntersected.Add(tfList); } } } projectLocationPointOnTFForm(TFFormsIntersected); }
public static ITFFrameList createFrameCN (PenetrTask task, PenetrInfo penInfo) { task.scanInfo(); // TODO отключено временно, до решения по алгоритму пересечений фланцев: //if (!Keyins.Penetrations.DEBUG_MODE) { // if (task.isCompoundExistsInPlace || task.TFFormsIntersected.Count == 0) // return null; //} var taskUOR = task.UOR; double pipeInsideDiam = penInfo.pipeDiameterInside * taskUOR.active_perSub; double pipeOutsideDiam = penInfo.pipeDiameterOutside * taskUOR.active_perSub; double flangeInsideDiam = penInfo.flangeDiameterInside * taskUOR.active_perSub; double flangeOutsideDiam = penInfo.flangeDiameterOutside * taskUOR.active_perSub; double flangeThick = penInfo.flangeThick * taskUOR.active_perSub; double length = task.Length * taskUOR.active_perSub; double pipeInRadius = pipeInsideDiam / 2; double pipeOutRadius = pipeOutsideDiam / 2; var tfApi = new Bentley.Building.Api.TFApplicationList().AsTFApplication; BCOM.ModelReference activeModel = App.ActiveModelReference; //ITFBrepList brepList; //tfApi.CreateTFBrep(0, out brepList); DPoint3d origin = task.Location.ToDPoint(); origin.ScaleInPlace(taskUOR.active_perMaster); DMatrix3d rot = task.Rotation.ToDMatrix3d(); var dTran = DTransform3d.FromMatrixAndTranslation(rot, origin); var tranInfo = new TransformInfo(dTran); // DMatrix3d.FromColumns( //rot.RowX.ToDVector(), rot.RowX.ToDVector(), rot.RowX.ToDVector()); //ITFFormRecipeList recipeList; var model = Session.Instance.GetActiveDgnModel(); var modelRef = Session.Instance.GetActiveDgnModelRef(); //CellHeaderElement taskEl = Element.GetFromElementRef(task.elemRefP) as CellHeaderElement; //DPoint3d taskOrigin; //taskEl.GetSnapOrigin(out taskOrigin); var ellips = new EllipseElement(model, null, DEllipse3d.FromCenterRadiusNormal(DPoint3d.Zero, pipeOutRadius, DVector3d.FromXY(0, 1))); ellips.ApplyTransform(tranInfo); var cone = new ConeElement(model, null, pipeOutRadius, pipeOutRadius, DPoint3d.FromXYZ(0, length, 0), DPoint3d.Zero, DMatrix3d.Rotation(DVector3d.UnitX, Angle.FromDegrees(-90)), true); cone.ApplyTransform(tranInfo); var ellips2 = new EllipseElement(model, null, DEllipse3d.FromCenterRadiusNormal( DPoint3d.Zero, pipeInRadius, DVector3d.FromXY(0, 1))); ellips2.ApplyTransform(tranInfo); var cone2 = new ConeElement(model, null, pipeInRadius, pipeInRadius, DPoint3d.Zero, DPoint3d.FromXYZ(0, length, 0), DMatrix3d.Zero, false); cone2.ApplyTransform(tranInfo); //int status = brepList.InitCylinder(pipeInsideRadius*task_subPerMaster, // (length - flangeThick)*task_subPerMaster, ref origin, // ref matrix, ""); //ITFElementList elemList; //tfApi.CreateTFElement(0, out elemList); // Bentley.GeometryNET.Common.CircularCylinder //ITFBrepList coneBrepList, cone2BrepList, resBrepList; //tfApi.CreateTFBrep(0, out coneBrepList); //tfApi.CreateTFBrep(0, out cone2BrepList); //coneBrepList.InitFromElement(cone, modelRef, ""); //cone2BrepList.InitFromElement(cone2, modelRef, ""); //coneBrepList.AsTFBrep.InitCylinder(pipeInsideRadius, length, ref origin, // ref matrix, 0); ITFItemList itemList; tfApi.CreateTFItem(0, out itemList); //var sweepDir = DVector3d.FromXY(1, 0); //coneBrepList.AsTFBrep.Drop(out resBrepList, cone2BrepList, 0); //sweepDir.NegateInPlace(); // coneBrepList.AsTFBrep.Cut(out resBrepList, cone2BrepList, ref sweepDir, length + 150, false, 0); //coneBrepList.AsTFBrep.SweepByVector3(ref sweepDir, length + 300, // pipeOutsideRadius - pipeInsideRadius, 0, 0); //Array arr = new System.Collections.ArrayList().ToArray(); //coneBrepList.AsTFBrep.Cut2(out resBrepList, cone2BrepList.AsTFBrep, ref sweepDir, //Bentley.Building.Api.TFdBrepCutMethod.tfdBrepCutMethod_Outside, //Bentley.Building.Api.TFdBrepCutDirection.tfdBrepCutDirection_Both, //Bentley.Building.Api.TFdBrepCutDepth.tfdBrepCutDepth_UpToSolid, length, //arr, 0, false, Bentley.Building.Api.TFdBrepCutDepth.tfdBrepCutDepth_UpToSolid, length, //arr, 0, false, 0, 0, 0.00005, 0); //lement resElement; //resBrepList.GetElement(out resElement, 0, ""); //coneBrepList.GetElement(out resElement, 0, ""); ITFFrameList frameList; tfApi.CreateTFFrame(0, out frameList); frameList.AsTFFrame.Add3DElement(cone, 0); //frameList.AsTFFrame.Add3DElement(cone2, 0); //frameList.AsTFFrame.Add3DElement(resElement, 0); //ITFFrameList openingFrameList; //tfApi.CreateTFFrame(0, out openingFrameList); //openingFrameList.AsTFFrame.Add3DElement(cone2, 0); //ITFFormRecipeList openRecipeList; ////tfApi.CreateTFFormRecipeArc //ITFFormRecipe openRecipe; //openingFrameList.AsTFFrame.GetFormRecipeList(0, out openRecipeList); //openRecipe = openRecipeList.AsTFFormRecipe; //ITFItemList featureList; //frameList.AsTFFrame.AddOpeningsToForm(out featureList, ref openRecipe, "", 0); ITFPerforatorList perfoList; tfApi.CreateTFPerforator(0, out perfoList); var dir = DVector3d.FromXY(1, 0); var tran = DTransform3d.Identity; perfoList.InitFromElement(ellips, ref dir, length, ref tran, ""); perfoList.AsTFPerforator.SetIsVisible(false, 0); perfoList.SetSweepMode(Bentley.Building.Api.TFdPerforatorSweepMode.tfdPerforatorSweepModeBi, ""); perfoList.SetPolicy(Bentley.Building.Api.TFdPerforatorPolicy.tfdPerforatorPolicyThroughHoleWithinSenseDist, ""); frameList.AsTFFrame.SetPerforatorList(ref perfoList, 0); frameList.AsTFFrame.SetSenseDistance2(length / 100, 0); frameList.AsTFFrame.SetPerforatorsAreActive(true, 0); int stat; // = tfApi.ModelReferenceAddFrameList(modelRef, ref frameList, 0); var frame = frameList.AsTFFrame; stat = tfApi.ModelReferenceUpdateAutoOpeningsByFrame(modelRef, ref frame, true, false, Bentley.Building.Api.TFdFramePerforationPolicy.tfdFramePerforationPolicyNone, 0); //Element cylindr; //brepList.GetElement(out cylindr, 0, ""); //cylindr.AddToModel(); //Element tfElement; //Element perfo = null; //Element dp_2d = null; //int value; //tfApi.ModelReferenceAddElement(ref cylindr, Session.Instance.GetActiveDgnModel(), // 0, 0, out value); //tfApi.ModelReferenceConstructFrameElement(Session.Instance.GetActiveDgnModel(), // 0, ref cylindr, ref perfo, ref origin, ref dp_2d, "name", null, // 1, 0, false, null, false, task.Length, 0.00005, 0, out tfElement); //frameList.InitFromElement(cylindr, ""); // frameList.AsTFFrame.Add3DElement(cylindr, 0); return(frameList); }
/*-----------------------------------------------------------------------------*/ /// <summary> /// The command to process the active file. It will attempt to create a session /// and open the connection to the active model. /// If the connection cannot be opened it will error out. /// The findEmbeded method to look at the file for embedded schemas /// </summary> /// <param name="unparsed">not used.</param> /*-----------------------------------------------------------------------------*/ public static void BVSchemaCheckerCommand(System.String unparsed) { string errMessage = "ERROR"; List <string> schemaList = new List <string>(); //set to silent mode m_silentMode = false; if (1 == BVSchemaChecker.mdlSystem_startedAsAutomationServer() && ((null != unparsed) && unparsed == "FROM_HOOK")) { return; } //if an unparsed string is sent in then set silent to true if (1 != BVSchemaChecker.mdlSystem_startedAsAutomationServer() && ((null != unparsed) && (unparsed.Length > 0))) { m_silentMode = true; } //see if it is an imodel if so then don't check. if (1 == BVSchemaChecker.IsIModel(BVSchemaChecker.ComApp.ActiveModelReference.MdlModelRefP())) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("this is an i-model", "i-models are not processed", BCOM.MsdMessageCenterPriority.Info, false); return; } //if there are references then we process special. if (BVSchemaChecker.ComApp.ActiveModelReference.Attachments.Count > 0) {//if the references are imodels then notify the users. if (BVSchemaChecker.HasIModelReference(BVSchemaChecker.ComApp.ActiveModelReference)) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("Has IModel Attached", "This file has an imodel in the attachment set", BCOM.MsdMessageCenterPriority.Info, false); } BCOM.DesignFile workFile = BVSchemaChecker.ComApp.OpenDesignFileForProgram( BVSchemaChecker.ComApp.ActiveDesignFile.FullName, true); //create a model in the file that has no references //proces the new model. this will avoid using the references as part //of the ec repository. //delete the model after the processing. try { BCOM.ModelReference workModel = workFile.Models.Add( workFile.DefaultModelReference, "working", "working", BCOM.MsdModelType.Normal, true); int iAttachmentCount = workModel.Attachments.Count; for (int i = iAttachmentCount; i > 0; --i) { BCOM.Attachment oAtt = workModel.Attachments[i]; workModel.Attachments.Remove(oAtt); } BVSchemaChecker.ProcessModel(workModel); workFile.Models.Delete(workModel); } catch (Exception e) { Console.WriteLine("unable to wrtie to file"); } workFile.Close(); return; } //if I am a simple file with normal dgn references ECSR.RepositoryConnection connection = null; CSVReporter.CreateReport(string.Format("SC_{0}.csv", DateTime.Now.ToString("yyyy-dd-MM"))); if (m_debugMode) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("created csv file", string.Format("created report file at {0}", CSVReporter.FileName), BCOM.MsdMessageCenterPriority.Info, m_debugMode); } if (m_usesSelector) { m_selectorForm.SetMessage("Processing File " + BVSchemaChecker.ComApp.ActiveDesignFile.Name); } try { ECSS.ECSession ecSession = ECSS.SessionManager.CreateSession(true); connection = BVSchemaChecker.OpenConnectionToActiveModel(ecSession); if (BVSchemaChecker.FindEmbededSchemas(connection, schemaList)) { BVSchemaChecker.ComApp.MessageCenter.AddMessage("Found schema in this file. \n Please contact the Bentley Execution team with the Schema list provided on the following dialog box. \n Select Ok to get a list of the schema you will need to provide", "Found Schema", BCOM.MsdMessageCenterPriority.Error, m_silentMode); BVSchemaChecker.iSchemaFoundCount++; //show the list... if (m_silentMode) { SchemaListForm sform = new SchemaListForm(); sform.SetSchemaNames(schemaList); sform.ShowDialog(); } } else { BVSchemaChecker.ComApp.MessageCenter.AddMessage("no schema in the file", "nothing found", BCOM.MsdMessageCenterPriority.Info, (unparsed != "FROM_HOOK")); } } catch (Exception e) { BVSchemaChecker.ComApp.MessageCenter.AddMessage(e.Message, e.Message, BCOM.MsdMessageCenterPriority.Error, !BVSchemaChecker.bUseLogFile); errMessage = e.Message; } finally { if (null == connection) { CSVReporter.writeLine(BVSchemaChecker.strCurrentProjectName, BVSchemaChecker.ComApp.ActiveDesignFile.Name, BVSchemaChecker.ComApp.ActiveModelReference.Name, errMessage, false); } else { BVSchemaChecker.CloseConnection(connection); } CSVReporter.close(); } }
public static void addToModelWithProjAndPerfo(ref TFCOM.TFFrameList frameList, PenetrTask task, PenetrInfo penInfo, BCOM.Level levelSymb, BCOM.Level levelRefPoint) { var taskUOR = new UOR(task.modelRef); double pipeInsideDiam = penInfo.pipeDiameterInside / taskUOR.active_subPerMaster; double pipeOutsideDiam = penInfo.pipeDiameterOutside / taskUOR.active_subPerMaster; double flangeInsideDiam = penInfo.flangeDiameterInside / taskUOR.active_subPerMaster; double flangeOutsideDiam = penInfo.flangeDiameterOutside / taskUOR.active_subPerMaster; double flangeThick = penInfo.flangeThick / taskUOR.active_subPerMaster; double length = task.LengthCm * 10 / taskUOR.active_subPerMaster; BCOM.ModelReference activeModel = App.ActiveModelReference; //AppTF.ModelReferenceAddFrameList(activeModel, ref frameList); frameList.Synchronize(); var frameListClass = frameList as TFCOM.TFFrameListClass; BCOM.Element bcomElem; frameListClass.GetElement(out bcomElem); var tfApi = new Bentley.Building.Api.TFApplicationList().AsTFApplication; var modelRef = Session.Instance.GetActiveDgnModelRef(); var model = Session.Instance.GetActiveDgnModel(); Element ielement = Element.GetFromElementRef((IntPtr)bcomElem.MdlElementRef()); modelRef.GetFromElementRef((IntPtr)bcomElem.MdlElementRef()); ITFFrameList iframeList; tfApi.CreateTFFrame(0, out iframeList); iframeList.InitFromElement(ielement, ""); iframeList.Synchronize(""); DPoint3d origin = task.Location.ToDPoint(); origin.ScaleInPlace(taskUOR.active_perMaster); DMatrix3d matrix = DMatrix3d.FromRows( task.Rotation.RowX.ToDVector(), task.Rotation.RowY.ToDVector(), task.Rotation.RowZ.ToDVector()); DTransform3d dTran = DTransform3d.FromMatrixAndTranslation(matrix, origin); TransformInfo tranInfo = new TransformInfo(dTran); double pipeInsideRadius = pipeOutsideDiam / 2 * taskUOR.active_perMaster; double dgnLength = length * taskUOR.active_perMaster; var ellips = new EllipseElement(model, null, DEllipse3d.FromCenterRadiusNormal(DPoint3d.Zero, pipeInsideRadius, DVector3d.FromXY(0, 1))); ellips.ApplyTransform(tranInfo); //{ // ПЕРФОРАТОР: // ITFPerforatorList perfoList; // tfApi.CreateTFPerforator(0, out perfoList); // var dir = DVector3d.FromXY(1, 0); // var tran = DTransform3d.Identity; // //perfoList.InitFromElement(ellips, ref dir, length*toUOR, ref tran, ""); // perfoList.InitFromElement2(ellips, length*taskUOR.active_perMaster, ""); // perfoList.AsTFPerforator.SetIsVisible(false, 0); // perfoList.SetSweepMode(Bentley.Building.Api.TFdPerforatorSweepMode.tfdPerforatorSweepModeBi, ""); // perfoList.SetPolicy(Bentley.Building.Api.TFdPerforatorPolicy.tfdPerforatorPolicyThroughHoleWithinSenseDist, ""); // (iframeList as Bentley.Building.Api.TFFrameList).SetPerforatorList(ref perfoList, 0); // // iframeList.AsTFFrame.SetPerforatorList(ref perfoList, 0); // iframeList.AsTFFrame.SetSenseDistance2(length, 0); // iframeList.AsTFFrame.SetPerforatorsAreActive(true, 0); // var frame = iframeList.AsTFFrame; // tfApi.ModelReferenceUpdateAutoOpeningsByFrame(modelRef, //ref frame, true, false, Bentley.Building.Api.TFdFramePerforationPolicy.tfdFramePerforationPolicyStrict, 0); //} // tfApi.ModelReferenceRewriteFrameInstance(modelRef, iframeList.AsTFFrame, 0); //iframeList.AsTFFrame.Synchronize(0); { // ПРОЕКЦИОННАЯ ГЕОМЕТРИЯ ITFProjectionList projList, projList1, projList2, projList3; tfApi.CreateTFProjection(0, out projList); tfApi.CreateTFProjection(0, out projList1); tfApi.CreateTFProjection(0, out projList2); tfApi.CreateTFProjection(0, out projList3); var zero = DPoint3d.Zero; DPoint3d[] verts = { zero, zero, zero, zero, zero }; double k = pipeInsideRadius * Math.Cos(Math.PI / 4); verts[0].X = -k; verts[0].Z = -k; verts[1].X = k; verts[1].Z = k; verts[3] = verts[0]; verts[3].Z *= -1; verts[4] = verts[1]; verts[4].Z *= -1; LineStringElement cross1 = new LineStringElement(model, null, verts); for (int i = 0; i < verts.Count(); ++i) { verts[i].Y = dgnLength; } LineStringElement cross2 = new LineStringElement(model, null, verts); cross1.ApplyTransform(tranInfo); cross2.ApplyTransform(tranInfo); projList1.AsTFProjection.SetEmbeddedElement(cross1, 0); projList2.AsTFProjection.SetEmbeddedElement(cross2, 0); LineElement refPoint = new LineElement(model, null, new DSegment3d(zero, zero)); refPoint.ApplyTransform(tranInfo); ElementPropertiesSetter setter = new ElementPropertiesSetter(); setter.SetWeight(7); setter.Apply(refPoint); projList3.AsTFProjection.SetEmbeddedElement(refPoint, 0); projList.Append(projList1, ""); projList.Append(projList2, ""); projList.Append(projList3, ""); iframeList.AsTFFrame.SetProjectionList(projList, 0); //iframeList.AsTFFrame.Synchronize(0); //iframeList.Synchronize(string.Empty); } tfApi.ModelReferenceRewriteFrameInstance(modelRef, iframeList.AsTFFrame, 0); // int stat = tfApi.ModelReferenceRewriteFrameList(modelRef, iframeList, 0); //tfApi.ModelReferenceAddFrameList(modelRef, ref iframeList, 0); // tfApi.ModelReferenceRewriteFrameList(modelRef, iframeList, 0); //frameListClass = frameList as TFCOM.TFFrameListClass; //frameListClass.GetElement(out bcomElem); // setDataGroupInstance(bcomElem, task); }