//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public bool UpdateFeatureFromAsm(PartFeature AsmFeature, PartFeature PartFeature, Matrix invTransfo) { ExtrudeFeature asmFeature = AsmFeature as ExtrudeFeature; ExtrudeFeature partFeature = PartFeature as ExtrudeFeature; try { PartComponentDefinition partCompDef = partFeature.Parent as PartComponentDefinition; PlanarSketch partSketch = partFeature.Profile.Parent as PlanarSketch; UnitVector xAxis = null; UnitVector yAxis = null; FeatureUtilities.UpdateSketch(asmFeature.Profile.Parent as PlanarSketch, partSketch, invTransfo, out xAxis, out yAxis); Document asmDocument = asmFeature.Parent.Document as Document; bool suppressed = partFeature.Suppressed; //Feature needs to be suppressed if we change the Profile partFeature.Suppressed = true; Profile newPartProfile = FeatureUtilities.UpdateProfile(asmDocument, partCompDef.Document as Document, asmFeature.Profile, partFeature.Profile, true); if (newPartProfile != null) { partFeature.Profile = newPartProfile; } partFeature.Suppressed = suppressed; partFeature.TaperAngle.Value = asmFeature.TaperAngle.Value; if (FeatureUtilities.UpdateFeatureExtent(asmFeature.Extent, partFeature.Extent, invTransfo)) { return(true); } switch (asmFeature.ExtentType) { case PartFeatureExtentEnum.kThroughAllExtent: { ThroughAllExtent asmThroughAllExtent = asmFeature.Extent as ThroughAllExtent; partFeature.SetThroughAllExtent(asmThroughAllExtent.Direction); break; } case PartFeatureExtentEnum.kDistanceExtent: { DistanceExtent asmDistanceExtent = asmFeature.Extent as DistanceExtent; partFeature.SetDistanceExtent(asmDistanceExtent.Distance.Value, asmDistanceExtent.Direction); break; } case PartFeatureExtentEnum.kToExtent: { ToExtent asmToExtent = asmFeature.Extent as ToExtent; object ToEntity = FeatureUtilities.CopyFromToEntity(asmToExtent.ToEntity, partCompDef, invTransfo); partFeature.SetToExtent(ToEntity, false); break; } case PartFeatureExtentEnum.kFromToExtent: { FromToExtent asmFromToExtent = asmFeature.Extent as FromToExtent; object FromEntity = FeatureUtilities.CopyFromToEntity(asmFromToExtent.FromFace, partCompDef, invTransfo); object ToEntity = FeatureUtilities.CopyFromToEntity(asmFromToExtent.ToFace, partCompDef, invTransfo); partFeature.SetFromToExtent(FromEntity, false, ToEntity, false); break; } default: return(false); } return(true); } catch { //Something went wrong return(false); } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static string GetSketchBase(ExtrudeFeature ExtrudeFeature) { PlanarSketch sketch = ExtrudeFeature.Profile.Parent as PlanarSketch; return(sketch.PlanarEntity is WorkPlane ? "WorkPlane" : "Face"); }
private void ButtonBuild_Click(object sender, EventArgs e) { if (FalseWrite) { MessageBox.Show("Неправильно заданы входные параметры\nИсправьте красные поля"); return; } string docName = "Первая деталь"; CreateDoc(docName); // Создание эскиза на YX PlanarSketch Sketch = CompDef[docName].Sketches.Add(CompDef[docName].WorkPlanes[3]); // 1 - YZ ; 2 - ZX; 3 - XY // Создание массивов Точек, Линий, Дуг, Окружностей List <SketchPoint> points = new List <SketchPoint>(); // Точки List <SketchLine> lines = new List <SketchLine>(); // Линии List <SketchArc> arcs = new List <SketchArc>(); // Дуги List <SketchCircle> circles = new List <SketchCircle>(); // Окружности /////////////////////////////////////////////////////////// Выдавливание points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(0, 0), false)); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(0, 5.0 / 10), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(0, 10.0 / 10), false)); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(0, 15.0 / 10), false)); arcs.Add(Sketch.SketchArcs.AddByCenterStartEndPoint(points[points.Count - 2], points[points.Count - 3], points[points.Count - 1], true)); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(0, 20.0 / 10), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(20.0 / 10, 20.0 / 10), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(20.0 / 10, 0), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[0], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(10.0 / 10, 10.0 / 10), false)); circles.Add(Sketch.SketchCircles.AddByCenterRadius(points[points.Count - 1], 4.0 / 10)); Profile ProfileMain = (Profile)Sketch.Profiles.AddForSolid(); ExtrudeFeature ExtrudeDef = CompDef[docName].Features.ExtrudeFeatures.AddByDistanceExtent( /*Эскиз*/ ProfileMain, /*Длина в см*/ 10.0 / 10, /*Направление вдоль оси*/ PartFeatureExtentDirectionEnum.kPositiveExtentDirection, /*Операция*/ PartFeatureOperationEnum.kJoinOperation, /*Эскиз*/ ProfileMain); /////////////////////////////////////////////////////////// Вращение WorkPlane WorkinPlace = CompDef[docName].WorkPlanes.AddByPlaneAndOffset( CompDef[docName].WorkPlanes[2], 20.0 / 10); WorkinPlace.Visible = false; Sketch = CompDef[docName].Sketches.Add(WorkinPlace); SketchLine line_axis; points.Clear(); lines.Clear(); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(-(10.0 - 5) / 10, 0), false)); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(-(10.0 - 5) / 10, 10.0 / 10), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(-10.0 / 10, 10.0 / 10), false)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1])); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(-10.0 / 10, 0), false)); line_axis = Sketch.SketchLines.AddByTwoPoints(points[points.Count - 2], points[points.Count - 1]); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[0], points[points.Count - 1])); Profile ProfileExternal = (Profile)Sketch.Profiles.AddForSolid(); RevolveFeature revolvefeature = CompDef[docName].Features.RevolveFeatures.AddFull( ProfileExternal, line_axis, PartFeatureOperationEnum.kCutOperation); Trans[docName].End(); /////////////////////////////////////////////////////////// Вторая деталь docName = "Вторая деталь"; CreateDoc(docName); Sketch = CompDef[docName].Sketches.Add(CompDef[docName].WorkPlanes[3]); points.Clear(); lines.Clear(); ///////////////////////////////////////////////// Шестиугольник double R = 2 * (4.0 / 10) / Math.Sqrt(3), Angle; points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d( 1.65 * Math.Cos(((double)210 / 180) * Math.PI), 1.65 * Math.Sin(((double)210 / 180) * Math.PI)), true)); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d(points[0].Geometry.X + R, points[0].Geometry.Y), true)); for (int i = 2; i < 7; i++) { Angle = ((((double)i - 2) * 60 + 120) / 180); points.Add(Sketch.SketchPoints.Add(TransGeom[docName].CreatePoint2d( points[i - 1].Geometry.X + R * Math.Cos(Angle * Math.PI), points[i - 1].Geometry.Y + R * Math.Sin(Angle * Math.PI)), true)); lines.Add(Sketch.SketchLines.AddByTwoPoints(points[i - 1], points[i])); } lines.Add(Sketch.SketchLines.AddByTwoPoints(points[6], points[1])); ProfileMain = (Profile)Sketch.Profiles.AddForSolid(); ExtrudeDef = CompDef[docName].Features.ExtrudeFeatures.AddByDistanceExtent( /*Эскиз*/ ProfileMain, /*Длина*/ 10.0 / 10, /*Направление вдоль оси*/ PartFeatureExtentDirectionEnum.kPositiveExtentDirection, /*Операция*/ PartFeatureOperationEnum.kJoinOperation, /*Эскиз*/ ProfileMain); ///////////////////////////////////////////////// Фаска ChamferFeature Fillet; EdgeCollection Edges = ThisApplication.TransientObjects.CreateEdgeCollection(); int k = 0; foreach (SurfaceBody SurfBody in PartDoc[docName].ComponentDefinition.SurfaceBodies) { foreach (Edge Edge in SurfBody.Edges) { if (k == 2) { Edges.Add(Edge); } if (k == 5) { Edges.Add(Edge); } if (k == 8) { Edges.Add(Edge); } if (k == 11) { Edges.Add(Edge); } if (k == 14) { Edges.Add(Edge); } if (k == 17) { Edges.Add(Edge); } k++; } } Fillet = CompDef[docName].Features.ChamferFeatures.AddUsingDistance(Edges, 2.0 / 10); ///////////////////////////////////////////////// СОПРЯЖЕНИЕ FilletFeature Fillet1; Edges.Clear(); int n = 0; foreach (SurfaceBody SurfBody in PartDoc[docName].ComponentDefinition.SurfaceBodies) { foreach (Edge Edge in SurfBody.Edges) { if (n == 18) { Edges.Add(Edge); } if (n == 20) { Edges.Add(Edge); } if (n == 21) { Edges.Add(Edge); } if (n == 23) { Edges.Add(Edge); } if (n == 26) { Edges.Add(Edge); } if (n == 27) { Edges.Add(Edge); } n++; } } Fillet1 = CompDef[docName].Features.FilletFeatures.AddSimple(Edges, /*Радиус*/ 1.0 / 10); // Заврешение транзакции Trans[docName].End(); }
public void RunWithArguments(Document doc, NameValueMap map) { LogTrace("Initialiting"); PartDocument oPartDoc = (PartDocument)inventorApplication.Documents.Add(DocumentTypeEnum.kPartDocumentObject, inventorApplication.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject), true); LogTrace("Part template opened"); TransientGeometry oTG = inventorApplication.TransientGeometry; PartComponentDefinition oPartComDef = oPartDoc.ComponentDefinition; UserParameters oParams = oPartComDef.Parameters.UserParameters; XmlDocument xmlDoc = new XmlDocument(); string currentDir = System.IO.Directory.GetCurrentDirectory(); string projectDir = Directory.GetParent(currentDir).Parent.FullName; LogTrace("Reading XML input file from " + projectDir); xmlDoc.Load(System.IO.Path.Combine(projectDir, "react-test-output.xml")); //xmlDoc.Load("react-test-output.xml"); //xmlDoc.Load("C:\\webapps\\IpartCreator\\React-BIM-output.xml"); XmlNodeList FloorList = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor"); XmlNodeList FloorPointList = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor/BoundaryPoints/Point"); XmlNodeList ComponentName = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor/ComponentName"); XmlNodeList PointX = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor/BoundaryPoints/Point/X"); XmlNodeList PointY = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor/BoundaryPoints/Point/Y"); XmlNodeList PointZ = xmlDoc.DocumentElement.SelectNodes("/Building/Floors/Floor/BoundaryPoints/Point/Z"); for (int i = 0; i < FloorList.Count; i++) { //oParams.AddByExpression("ComponentName" + i, ComponentName[i].InnerText, UnitsTypeEnum.kUnitlessUnits); int numPoint = FloorPointList.Count / FloorList.Count; Point2d[] oPoints = new Point2d[numPoint]; SketchPoint[] osPoints = new SketchPoint[numPoint]; for (int j = 0; j < numPoint; j++) { oParams.AddByExpression("PointX" + j, PointX[j].InnerText, UnitsTypeEnum.kMillimeterLengthUnits); oParams.AddByExpression("PointY" + j, PointY[j].InnerText, UnitsTypeEnum.kMillimeterLengthUnits); oParams.AddByExpression("PointZ" + j, PointZ[j].InnerText, UnitsTypeEnum.kMillimeterLengthUnits); oPoints[j] = oTG.CreatePoint2d(oPartComDef.Parameters.GetValueFromExpression("PointX" + j, UnitsTypeEnum.kMillimeterLengthUnits), oPartComDef.Parameters.GetValueFromExpression("PointY" + j, UnitsTypeEnum.kMillimeterLengthUnits)); } SketchLine[] oLines = new SketchLine[numPoint]; PlanarSketch oSketch = oPartComDef.Sketches.Add(oPartComDef.WorkPlanes[2]); osPoints[0] = oSketch.SketchPoints.Add(oPoints[0]); osPoints[1] = oSketch.SketchPoints.Add(oPoints[1]); osPoints[2] = oSketch.SketchPoints.Add(oPoints[2]); osPoints[3] = oSketch.SketchPoints.Add(oPoints[3]); oLines[0] = oSketch.SketchLines.AddByTwoPoints(osPoints[0], osPoints[1]); oLines[1] = oSketch.SketchLines.AddByTwoPoints(oLines[0].EndSketchPoint, osPoints[2]); oLines[2] = oSketch.SketchLines.AddByTwoPoints(oLines[1].EndSketchPoint, osPoints[3]); oLines[3] = oSketch.SketchLines.AddByTwoPoints(oLines[2].EndSketchPoint, oLines[0].StartSketchPoint); oSketch.DimensionConstraints.AddTwoPointDistance(osPoints[0], osPoints[1], DimensionOrientationEnum.kAlignedDim, oPoints[1]); //d0// oSketch.DimensionConstraints.AddTwoPointDistance(osPoints[1], osPoints[2], DimensionOrientationEnum.kAlignedDim, oPoints[3]); //d1// Profile oProfile = oSketch.Profiles.AddForSolid(); ExtrudeDefinition oExtrudeDef = oPartComDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, PartFeatureOperationEnum.kJoinOperation); oExtrudeDef.SetDistanceExtent(oPartComDef.Parameters.UserParameters.AddByExpression("length", "8", UnitsTypeEnum.kMillimeterLengthUnits), PartFeatureExtentDirectionEnum.kPositiveExtentDirection); ExtrudeFeature oExtrude = oPartComDef.Features.ExtrudeFeatures.Add(oExtrudeDef); string PartPath = projectDir + "/results/" + ComponentName[i].InnerText + i + ".ipt"; //string PartPath = ComponentName[i].InnerText + i + ".ipt"; oPartDoc.SaveAs(PartPath, false); oExtrude.Delete(); } oPartDoc.Close(false); AssemblyDocument oAssyDoc = (AssemblyDocument)inventorApplication.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject, inventorApplication.FileManager.GetTemplateFile(DocumentTypeEnum.kAssemblyDocumentObject), true); AssemblyComponentDefinition oAssyComDef = oAssyDoc.ComponentDefinition; ComponentOccurrences oAssyCompOccs = oAssyComDef.Occurrences; Matrix oPos = oTG.CreateMatrix(); int oStep = 0; int icomp; int numite = FloorPointList.Count / FloorList.Count; for (icomp = 0; icomp <= numite; icomp++) { oStep = oStep + 150; oPos.SetTranslation(oTG.CreateVector(oStep, oStep, 0), false); string PartPath = projectDir + "/results/" + ComponentName[icomp].InnerText + icomp + ".ipt"; //string PartPath = ComponentName[icomp].InnerText + icomp + ".ipt"; ComponentOccurrence oOcc = oAssyCompOccs.Add(PartPath, oPos); } oAssyDoc.SaveAs(projectDir + "/results/result.iam", false); //oAssyDoc.SaveAs("result.iam", false); oAssyDoc.Close(); ZipFile.CreateFromDirectory(projectDir + "/results", projectDir + "/forgeResult.zip"); }
} //end of method IntersectOperation private string ExtrudeSketch(ExtrudeFeature extrudeFeature) { StringBuilder extrusionLine = new StringBuilder(); MasterM.ExtrudeDirection direction = MasterM.GetDirection(extrudeFeature); string objectName = extrudeFeature.Name; string name = "Extrusion" + _numberOfSketches; if (direction == MasterM.ExtrudeDirection.Positive) { if (extrudeFeature.ExtentType == PartFeatureExtentEnum.kDistanceExtent) { //get length of extrusion Inventor.Parameter param = (extrudeFeature.Definition.Extent as DistanceExtent).Distance; double length = param._Value * factor; string paramString = "params." + name; Parameter extrusionParameter = new Parameter(name, "Length of " + name, "float", length, 0.1); ListOfParameter.Add(extrusionParameter); //with parameter: extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0," + paramString + "] });"); //without parameter: //extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0," + height.ToString(myCultureInfo) + "] });"); } else //default: extruding with 10 { extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0,10] });"); } } else if (direction == MasterM.ExtrudeDirection.Negative) { if (extrudeFeature.ExtentType == PartFeatureExtentEnum.kDistanceExtent) { //because when extruding in openjscad you cant choose a direction //we extrude in the same direction but then translating same length in reversed direction //get length of extrusion Inventor.Parameter param = (extrudeFeature.Definition.Extent as DistanceExtent).Distance; double length = param._Value * factor; string paramString = "params." + name; Parameter extrusionParameter = new Parameter(name, "Length of " + name, "float", length, 0.1); ListOfParameter.Add(extrusionParameter); //with parameter: extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0," + paramString + "] })"); extrusionLine.Append(TranslateObject("z", paramString, true)); //without parameter: //extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0," + height.ToString(myCultureInfo) + "] });"); //extrusionLine.Append(TranslateObject("z", height.ToString(myCultureInfo), true)); } else //default: extruding with 10 { extrusionLine.Append("\t" + "var " + objectName + " = sketch" + _numberOfSketches + ".extrude({ offset: [0,0,10] });"); } } else //if(direction == ExtrudeDirection.Symetric) { //extrude distance //translate distance/2 } return(extrusionLine.ToString()); } //end of method ExtrudeSketch
private void Button_ok_Click(object sender, EventArgs e) { // references to some useful objects TransientGeometry geom = m_inventorApplication.TransientGeometry; //PartDocument document = m_inventorApplication.ActiveDocument as PartDocument; //_Document document = m_inventorApplication.ActiveDocument; /* * if (document == null) * { * AssemblyDocument asm = m_inventorApplication.ActiveDocument as AssemblyDocument; * m_inventorApplication.ActiveDocument; * } */ PartComponentDefinition def; // = document.ComponentDefinition; UnitsOfMeasure units; // = document.UnitsOfMeasure; UserParameters user_params; Document document = m_inventorApplication.ActiveDocument; if (m_inventorApplication.ActiveDocument is AssemblyDocument) { AssemblyDocument doc = m_inventorApplication.ActiveDocument as AssemblyDocument; PartDocument part = doc.ActivatedObject as PartDocument; if (part == null) { m_inventorApplication.ErrorManager.Show("Please activate a part!", true, false); return; } def = part.ComponentDefinition; units = part.UnitsOfMeasure; user_params = part.ComponentDefinition.Parameters.UserParameters; } else if (m_inventorApplication.ActiveDocument is PartDocument) { PartDocument doc = m_inventorApplication.ActiveDocument as PartDocument; def = doc.ComponentDefinition; units = doc.UnitsOfMeasure; user_params = doc.ComponentDefinition.Parameters.UserParameters; } else { m_inventorApplication.ErrorManager.Show("Current document is neither an Assembly nor a Part.", true, false); return; } // get and check selected faces ObjectsEnumerator JustSelectedEntities = m_selects.SelectedEntities; if (JustSelectedEntities.Count == 0) { m_inventorApplication.ErrorManager.Show("Select at least one planar, rectangular face.", true, false); return; } foreach (Object _f in JustSelectedEntities) { Face f = _f as Face; if (f == null) { m_inventorApplication.ErrorManager.Show("Somehow, you managed to select something that isn't a face. This should not happen, please report it.", true, false); return; } if (f.Edges.Count != 4) { m_inventorApplication.ErrorManager.Show("Please only select rectangular faces.", true, false); return; } } // TODO: catch exception when invalid was is entered UserParameter tab_user_constr; if (m_dialog.mode_count.Checked) { tab_user_constr = user_params.AddByExpression("tab_count", m_dialog.tab_size_input.Text, UnitsTypeEnum.kUnitlessUnits); } else { tab_user_constr = user_params.AddByExpression("tab_size", m_dialog.tab_size_input.Text, UnitsTypeEnum.kDefaultDisplayLengthUnits); } int total_operations = JustSelectedEntities.Count; WorkAxis[] extrusion_dir = new WorkAxis[total_operations]; bool[] long_edge_dir = new bool[total_operations]; PlanarSketch[] all_sketches = new PlanarSketch[total_operations]; Profile[] profile = new Profile[total_operations]; ExtrudeFeature[] extrusion = new ExtrudeFeature[total_operations]; TwoPointDistanceDimConstraint[] tab_length_constr = new TwoPointDistanceDimConstraint[total_operations]; TwoPointDistanceDimConstraint[] tab_widthdepth_constr = new TwoPointDistanceDimConstraint[total_operations]; TwoPointDistanceDimConstraint[] total_length_constr = new TwoPointDistanceDimConstraint[total_operations]; RectangularPatternFeature[] rect_pattern = new RectangularPatternFeature[total_operations]; Transaction transaction = m_inventorApplication.TransactionManager.StartTransaction(m_inventorApplication.ActiveDocument, "LaserTab"); // create extrusion feature for each face int i = 0; foreach (Object _f in JustSelectedEntities) { Face f = _f as Face; if (_f is FaceProxy) { f = ((FaceProxy)_f).NativeObject; } // TODO: make sure active document is a partDocument and ActiveEditObject is not a sketch (should be also a partDocument?) // TODO: wrap it all into a ClientFeature // TODO: maybe also wrap it in a Transaction? // create sketch PlanarSketch sketch = def.Sketches.Add(f, false); // don't project anything //PlanarSketch sketch = def.Sketches.Add(f, true); // project existing geometry //PlanarSketch sketch = def.Sketches.AddWithOrientation(f, long_edge, true, true, long_edge.StartVertex, true); Edge short_edge, long_edge; Vertex vert_origin, vert_short_end, vert_long_end; determine_orientation(f, out long_edge, out short_edge, out vert_origin, out vert_long_end, out vert_short_end); // remember wheter 'long_edge' starts or stops at 'P_orig' (which is important for the direction of the rectangular pattern) long_edge_dir[i] = long_edge.StartVertex == vert_origin; extrusion_dir[i] = def.WorkAxes.AddByLine(long_edge, true); // project important points SketchPoint P_orig = sketch.AddByProjectingEntity(vert_origin) as SketchPoint; SketchPoint P_long = sketch.AddByProjectingEntity(vert_long_end) as SketchPoint; SketchPoint P_short = sketch.AddByProjectingEntity(vert_short_end) as SketchPoint; // fails! :( // driven constraint of short dimension (determining thickness and depth of tab) tab_widthdepth_constr[i] = sketch.DimensionConstraints.AddTwoPointDistance( P_orig, P_short, DimensionOrientationEnum.kAlignedDim, P_short.Geometry, true); // driven constraint of long dimenstion (determining number/size of tabs) total_length_constr[i] = sketch.DimensionConstraints.AddTwoPointDistance( P_orig, P_long, DimensionOrientationEnum.kAlignedDim, P_long.Geometry, true); // appearantly, Profiles.AddForSolid() doesn't like lines that are made entirely out of projected points... (maybe because the line already exists?) SketchPoint P_orig_proj = P_orig, P_short_proj = P_short; P_short = sketch.SketchPoints.Add(P_short_proj.Geometry, false); P_orig = sketch.SketchPoints.Add(P_orig_proj.Geometry, false); // create dimension constraints // TODO: calculate better position for text label //Debug.Print("constraint short: {0} = {1}", constr_short.Parameter.Expression, constr_short.Parameter.Value); //Debug.Print("constraint long: {0} = {1}", constr_long.Parameter.Expression, constr_long.Parameter.Value); // create endpoint for rectangle Point2d P_end2 = P_short.Geometry.Copy(); Point2d P_end1 = P_orig.Geometry.Copy(); Vector2d long_direction = P_orig.Geometry.VectorTo(P_long.Geometry); long_direction.ScaleBy(0.2); P_end1.TranslateBy(long_direction); P_end2.TranslateBy(long_direction); SketchPoint P_end1_sk = sketch.SketchPoints.Add(P_end1, false); SketchPoint P_end2_sk = sketch.SketchPoints.Add(P_end2, false); // constrain endpoints properly //sketch.GeometricConstraints.AddCoincident((SketchEntity)long_line2, (SketchEntity)P_end2_sk); //sketch.GeometricConstraints.AddCoincident((SketchEntity)long_line, (SketchEntity)P_end1_sk); // constraint for tab length (twice, once for each side of the rectangle) TwoPointDistanceDimConstraint tab_len_constraint1 = sketch.DimensionConstraints.AddTwoPointDistance(P_orig, P_end1_sk, DimensionOrientationEnum.kAlignedDim, P_end1); TwoPointDistanceDimConstraint tab_len_constraint2 = sketch.DimensionConstraints.AddTwoPointDistance(P_short, P_end2_sk, DimensionOrientationEnum.kAlignedDim, P_end2); tab_length_constr[i] = tab_len_constraint1; // {0}: total length // {1}: user input (count or length of single tab) string expr; if (m_dialog.mode_count.Checked) { if (m_dialog.force_parity.Checked) { if (m_dialog.parity_even.Checked) { expr = "{0} / ( round({1}/2)*2 )"; } else { expr = "{0} / ( round( ({1}+1)/2 )*2 - 1 )"; } } else { expr = "{0} / {1}"; } } else { // TODO: take dropdown of >/</~ into account if (m_dialog.force_parity.Checked) { if (m_dialog.parity_even.Checked) { expr = "{0} / ( round( {0}/{1}/2 )*2 )"; } else { expr = "{0} / ( round( ({0}/{1}+1)/2 )*2 - 1)"; } } else { expr = "{0} / round({0}/{1})"; } } tab_len_constraint1.Parameter.Expression = string.Format(expr, total_length_constr[i].Parameter.Name, tab_user_constr.Name); tab_len_constraint2.Parameter.Expression = tab_len_constraint1.Parameter.Name; // create a rectangle based on these points // two-point rectangle is always axis-aligned -> doesn't work for rotated stuff //SketchEntitiesEnumerator rect = sketch.SketchLines.AddAsTwoPointRectangle(P_orig, P_end_sk); // this is cumbersome, as the third point is transient and therefore the rectangle would have to be constrained afterwards //SketchEntitiesEnumerator rect = sketch.SketchLines.AddAsThreePointRectangle(P_orig, P_short, P_end); ObjectCollection rect = m_inventorApplication.TransientObjects.CreateObjectCollection(); rect.Add(sketch.SketchLines.AddByTwoPoints(P_orig, P_end1_sk)); rect.Add(sketch.SketchLines.AddByTwoPoints(P_end1_sk, P_end2_sk)); rect.Add(sketch.SketchLines.AddByTwoPoints(P_end2_sk, P_short)); rect.Add(sketch.SketchLines.AddByTwoPoints(P_short, P_orig)); // constrain rectangle if (m_dialog.offset.Checked) { sketch.GeometricConstraints.AddCoincident((SketchEntity)rect[1], (SketchEntity)P_orig_proj); sketch.GeometricConstraints.AddCoincident((SketchEntity)rect[3], (SketchEntity)P_short_proj); sketch.GeometricConstraints.AddPerpendicular((SketchEntity)rect[1], (SketchEntity)rect[2]); TwoPointDistanceDimConstraint offset_dist = sketch.DimensionConstraints.AddTwoPointDistance(P_orig, P_orig_proj, DimensionOrientationEnum.kAlignedDim, P_orig_proj.Geometry); offset_dist.Parameter.Expression = tab_len_constraint1.Parameter.Name; } else { sketch.GeometricConstraints.AddCoincident((SketchEntity)P_short, (SketchEntity)P_short_proj); sketch.GeometricConstraints.AddCoincident((SketchEntity)P_orig, (SketchEntity)P_orig_proj); } sketch.GeometricConstraints.AddCoincident((SketchEntity)rect[1], (SketchEntity)P_long); sketch.GeometricConstraints.AddParallel((SketchEntity)rect[1], (SketchEntity)rect[3]); profile[i] = sketch.Profiles.AddForSolid(false, rect); all_sketches[i] = sketch; i++; } // do extrusions for (i = 0; i < total_operations; i++) { string dist_expr; if (m_dialog.auto_depth.Checked) { // use thickness of material dist_expr = tab_widthdepth_constr[i].Parameter.Name; } else { // use user input // TODO: validate! dist_expr = m_dialog.tab_depth_input.Text; } PartFeatureExtentDirectionEnum dir; PartFeatureOperationEnum op; if (m_dialog.extrude_positive.Checked) { dir = PartFeatureExtentDirectionEnum.kPositiveExtentDirection; op = PartFeatureOperationEnum.kJoinOperation; } else { dir = PartFeatureExtentDirectionEnum.kNegativeExtentDirection; op = PartFeatureOperationEnum.kCutOperation; } // extrude said rectangle ExtrudeDefinition extrusion_def = def.Features.ExtrudeFeatures.CreateExtrudeDefinition(profile[i], op); extrusion_def.SetDistanceExtent(dist_expr, dir); extrusion[i] = def.Features.ExtrudeFeatures.Add(extrusion_def); } // do rectangular patterns for (i = 0; i < total_operations; i++) { // now repeat that extrusion ObjectCollection col = m_inventorApplication.TransientObjects.CreateObjectCollection(); col.Add(extrusion[i]); // TODO: is ceil() actually correct here? string offset = (m_dialog.offset.Checked ? "1" : "0"); string count_expr = string.Format("ceil(round({0} / {1} - {2}) / 2)", total_length_constr[i].Parameter.Name, tab_length_constr[i].Parameter.Name, offset); RectangularPatternFeatureDefinition pattern_def = def.Features.RectangularPatternFeatures.CreateDefinition( col, extrusion_dir[i], long_edge_dir[i], count_expr, tab_length_constr[i].Parameter.Name + "*2"); // TODO: we could use PatternSpacingType kFitToPathLength here... try { rect_pattern[i] = def.Features.RectangularPatternFeatures.AddByDefinition(pattern_def); } catch (Exception ex) { Debug.Print("rect pattern failed: {0}", ex.Message); Debug.Print("long edge: {0}, dir: {1}, count_expr = '{2}', len = '{3}'", extrusion_dir[i], long_edge_dir[i], count_expr, tab_length_constr[i].Parameter.Name + "*2"); transaction.End(); return; } } stop_selection(); // create custom feature (called a ClientFeature by Inventor) containing all our sketches, extrusions and patterns in a single node object start_element; if (total_operations == 1) { // if there is only a single operation, the tree looks like this: /* * - extrusion 1 (consumed sketch 1) * - pattern 1 */ start_element = extrusion[0]; } else { // if there are multiple operations, the sketch is not consumed by the extrusion // and the tree looks like this: /* * - sketch 1 * - sketch 2 * - extrusion 1 * - extrusion 2 * - pattern 1 * - pattern 2 */ start_element = all_sketches[0]; } ClientFeatureDefinition feature_def = def.Features.ClientFeatures.CreateDefinition("LaserTab", start_element, rect_pattern[total_operations - 1]); ClientFeature feature = def.Features.ClientFeatures.Add(feature_def, "{0defbf22-e302-4266-9bc9-fb80d5c8eb7e}"); // load the icon for our custom feature if not done so already if (m_browser_icon == null) { stdole.IPictureDisp icon = PictureConverter.ImageToPictureDisp(Properties.Resources.browser_icon_16); m_browser_icon = document.BrowserPanes.ClientNodeResources.Add("{0defbf22-e302-4266-9bc9-fb80d5c8eb7e}", -1, icon); } NativeBrowserNodeDefinition ndef = document.BrowserPanes[1].GetBrowserNodeFromObject(feature).BrowserNodeDefinition as NativeBrowserNodeDefinition; ndef.OverrideIcon = m_browser_icon; transaction.End(); }
} //end of method InterpretePartFeatures private void InterpretePartFeature(object partFeature) { switch (Microsoft.VisualBasic.Information.TypeName(partFeature)) { case "ExtrudeFeature": { ExtrudeFeature extrudeFeature = (ExtrudeFeature)partFeature; string firstObjectName = extrudeFeature.Name; string secondObjectName; //no matter which operation will be executed, object gets created listOfCodeLines.Add(ExtrudeSketch(extrudeFeature)); switch (extrudeFeature.Operation) { //this is new extrusion or revolve case PartFeatureOperationEnum.kNewBodyOperation: listOfObjectNames.Add(firstObjectName); break; case PartFeatureOperationEnum.kJoinOperation: listOfObjectNames.Add(firstObjectName); break; //this case uses new created object and will cut it with another object case PartFeatureOperationEnum.kCutOperation: //TODO get other object name(s), which interfere with object //method kinda works. not returning the name i am using secondObjectName = string.Join(",", MasterM.GetAffectedBodyNames(extrudeFeature)); //old object gets deleted, new subtraction gets created which includs both objects _numberOfSubtractions++; listOfObjectNames.Remove(secondObjectName); listOfObjectNames.Add("Subtraction" + _numberOfSubtractions); CutOperation(secondObjectName, firstObjectName); break; //this case uses new created object and will intersect it with another object case PartFeatureOperationEnum.kIntersectOperation: //method kinda works. not returning the name i am using secondObjectName = string.Join(",", MasterM.GetAffectedBodyNames(extrudeFeature)); //old object gets deleted, new intersection gets created which includs both objects _numberOfIntersections++; listOfObjectNames.Remove(secondObjectName); listOfObjectNames.Add("Intersection" + _numberOfIntersections); IntersectOperation(secondObjectName, firstObjectName); break; } } break; case "RevolveFeature": { //revolving is not really working like in inventor. openjscad is always revolving around y-axis //so when revolveFeature is used we will create it but it will be at a different spot //and maybe interfere with another object var revolveFeature = (RevolveFeature)partFeature; string firstObjectName = revolveFeature.Name; //no matter which operation will be executed, object gets created listOfCodeLines.Add(RevolveSketch(revolveFeature)); switch (revolveFeature.Operation) { case PartFeatureOperationEnum.kNewBodyOperation: listOfObjectNames.Add(firstObjectName); break; case PartFeatureOperationEnum.kJoinOperation: listOfObjectNames.Add(firstObjectName); break; case PartFeatureOperationEnum.kCutOperation: listOfObjectNames.Add(firstObjectName); break; case PartFeatureOperationEnum.kIntersectOperation: listOfObjectNames.Add(firstObjectName); break; } } break; } /* * //TODO * //find out in which layer the sketch is orientated, eg. XY, XZ or YZ * //then rotate sketch if possible * * bool needToRotate = true; * if (rotationIsNeeded) * { * AppendToLastLineOfCode(RotateObject("x")); * * } * * //if sketch is not on BasePlane it has to be translated * bool needToTranslate = true; * if (needToTranslate) * { * AppendToLastLineOfCode(TranslateObject("z", value, false)); * } */ } //end of method InterpretePartFeature
private void Button1_Click(object sender, EventArgs e) { PartDocument oDoc = mApp.Documents.Add(DocumentTypeEnum.kPartDocumentObject, mApp.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject, SystemOfMeasureEnum.kDefaultSystemOfMeasure, DraftingStandardEnum.kDefault_DraftingStandard, null), true) as PartDocument; // Get the XZ Plane WorkPlane oWorkPlane = oDoc.ComponentDefinition.WorkPlanes[2]; PlanarSketch oSketch = oDoc.ComponentDefinition.Sketches.Add(oWorkPlane, false); TransientGeometry oTG = mApp.TransientGeometry; //Create some transient points used for defining the lines (see BRep Module) Point2d[] oPoints = new Point2d[5]; oPoints[0] = oTG.CreatePoint2d(0, 0); oPoints[1] = oTG.CreatePoint2d(-10, 0); oPoints[2] = oTG.CreatePoint2d(-10, -10); oPoints[3] = oTG.CreatePoint2d(5, -10); oPoints[4] = oTG.CreatePoint2d(5, -5); //Add the sketchlines, coincident constraints will be created automatically //since the "Line.EndSketchPoint" are provided each time we create a new line SketchLine[] oLines = new SketchLine[5]; oLines[0] = oSketch.SketchLines.AddByTwoPoints(oPoints[0], oPoints[1]); oLines[1] = oSketch.SketchLines.AddByTwoPoints(oLines[0].EndSketchPoint, oPoints[2]); oLines[2] = oSketch.SketchLines.AddByTwoPoints(oLines[1].EndSketchPoint, oPoints[3]); oLines[3] = oSketch.SketchLines.AddByTwoPoints(oLines[2].EndSketchPoint, oPoints[4]); oSketch.SketchArcs.AddByCenterStartEndPoint(oTG.CreatePoint2d(0, -5), oLines[3].EndSketchPoint, oLines[0].StartSketchPoint, true); //Create a profile for the extrusion, here no need to worry since there is only //a single profile that is possible Profile oProfile = oSketch.Profiles.AddForSolid(true, null, null); //this is the old way, i.e. create the extrude feature directly. it is still supported for backward compatibility //ExtrudeFeature oExtrude = oDoc.ComponentDefinition.Features.ExtrudeFeatures.AddByDistanceExtent(oProfile, // 5.0, PartFeatureExtentDirectionEnum.kPositiveExtentDirection, PartFeatureOperationEnum.kNewBodyOperation, 0.0); // Definition Way: PartComponentDefinition oPartDocDef = oDoc.ComponentDefinition; // get ExtrudeFeatures collection ExtrudeFeatures extrudes = oPartDocDef.Features.ExtrudeFeatures; // Create an extrude definition in the new surface body ExtrudeDefinition extrudeDef = extrudes.CreateExtrudeDefinition(oProfile, PartFeatureOperationEnum.kNewBodyOperation); // Modify the extent and taper angles. extrudeDef.SetDistanceExtent(8, PartFeatureExtentDirectionEnum.kPositiveExtentDirection); extrudeDef.SetDistanceExtentTwo(20); extrudeDef.TaperAngle = "-2 deg"; extrudeDef.TaperAngleTwo = "-10 deg"; // Create the extrusion. ExtrudeFeature extrude = extrudes.Add(extrudeDef); //Fit the view programmatically Camera oCamera = mApp.ActiveView.Camera; oCamera.ViewOrientationType = ViewOrientationTypeEnum.kIsoTopRightViewOrientation; oCamera.Apply(); mApp.ActiveView.Fit(true); }
public static double D1R = 380, D1r = 260, T1R = 240, O1r = 22, O1R = 168, R1R = 540; // Загрузка сыпучих материалов public static void Build(InventorAPI api, string formName) { var oParameters = api.GetCompDef().Parameters; PlanarSketch[] sketch = new PlanarSketch[12]; Profile[] profile = new Profile[12]; SketchPoint[] point = new SketchPoint[8]; SketchLine[] line = new SketchLine[8]; SketchCircle[] circle = new SketchCircle[1]; ExtrudeFeature[] extrude = new ExtrudeFeature[12]; // Основа корпуса sketch[0] = api.Sketch(api.GetCompDef().WorkPlanes[3]); point[0] = api.Point(sketch[0], 0, H / 10 - T / 10); point[1] = api.Point(sketch[0], 0, H / 10); point[2] = api.Point(sketch[0], D1 / 10 / 2, H / 10); point[3] = api.Point(sketch[0], D1 / 10 / 2, T / 10); point[4] = api.Point(sketch[0], D / 10 / 2, T / 10); point[5] = api.Point(sketch[0], D / 10 / 2, 0); point[6] = api.Point(sketch[0], D1 / 10 / 2 - T / 10, 0); point[7] = api.Point(sketch[0], D1 / 10 / 2 - T / 10, H / 10 - T / 10); line[0] = api.Line(sketch[0], point[0], point[1]); line[1] = api.Line(sketch[0], point[1], point[2]); line[2] = api.Line(sketch[0], point[2], point[3]); line[3] = api.Line(sketch[0], point[3], point[4]); line[4] = api.Line(sketch[0], point[4], point[5]); line[5] = api.Line(sketch[0], point[5], point[6]); line[6] = api.Line(sketch[0], point[6], point[7]); line[7] = api.Line(sketch[0], point[7], point[0]); profile[0] = api.Profile(sketch[0]); api.Revolve(profile[0], line[0], 0); // Ребра жесткости sketch[1] = api.Sketch(api.GetCompDef().WorkPlanes[3]); point[0] = api.Point(sketch[1], D1 / 10 / 2 - T / 10, H / 10); point[1] = api.Point(sketch[1], point[0].Geometry.X + T / 10 * 2, H / 10); point[2] = api.Point(sketch[1], D / 10 / 2, T / 10 * 2); point[3] = api.Point(sketch[1], D / 10 / 2, T / 10); point[4] = api.Point(sketch[1], point[0].Geometry.X, T / 10); line[0] = api.Line(sketch[1], point[0], point[1]); line[0] = api.Line(sketch[1], point[1], point[2]); line[0] = api.Line(sketch[1], point[2], point[3]); line[0] = api.Line(sketch[1], point[3], point[4]); line[0] = api.Line(sketch[1], point[4], point[0]); profile[1] = api.Profile(sketch[1]); extrude[1] = api.Extrude(profile[1], A / 10, 2, 0); var objCollection1 = api.ObjectCollection(); objCollection1.Add(extrude[1]); api.GetCompDef().Features.CircularPatternFeatures.Add(objCollection1, api.GetCompDef().WorkAxes[2], true, ACount, "360 degree", true, PatternComputeTypeEnum.kIdenticalCompute); // Резервные проходы (2 штуки) var oWorkPlane2 = api.GetCompDef().WorkPlanes.AddByPlaneAndOffset(api.GetCompDef().WorkPlanes[2], HR / 10); oWorkPlane2.Visible = false; sketch[2] = api.Sketch(oWorkPlane2); circle[0] = api.Circle(sketch[2], api.Point(sketch[2], RR / 10, 0), DR / 10 / 2); profile[2] = api.Profile(sketch[2]); extrude[2] = api.Extrude(profile[2], Hr / 10, 2, 0); sketch[3] = api.Sketch(oWorkPlane2); circle[0] = api.Circle(sketch[3], api.Point(sketch[3], RR / 10, 0), Dr / 10 / 2); profile[3] = api.Profile(sketch[3]); extrude[3] = api.Extrude(profile[3], HR / 10 - H / 10, 1, 0); sketch[4] = api.Sketch(oWorkPlane2); circle[0] = api.Circle(sketch[4], api.Point(sketch[4], RR / 10, 0), TR / 10 / 2); profile[4] = api.Profile(sketch[4]); extrude[4] = api.Extrude(profile[4], 10000, 2, 1); sketch[5] = api.GetCompDef().Sketches.Add(oWorkPlane2); sketch[5] = api.Sketch(oWorkPlane2); circle[0] = api.Circle(sketch[5], api.Point(sketch[5], RR / 10, OR / 10), Or / 10 / 2); profile[5] = api.Profile(sketch[5]); extrude[5] = api.Extrude(profile[5], Hr / 10, 2, 1); var Axis5 = api.GetCompDef().WorkAxes.AddByRevolvedFace(extrude[4].Faces[1]); Axis5.Visible = false; var objCollection5 = api.ObjectCollection(); objCollection5.Add(extrude[5]); var CircularPatternFeature5 = api.GetCompDef().Features.CircularPatternFeatures.Add(objCollection5, Axis5, true, 8, "360 degree", true, PatternComputeTypeEnum.kIdenticalCompute); var objCollection6 = api.ObjectCollection(); for (int i = 2; i < 6; i++) { objCollection6.Add(extrude[i]); } objCollection6.Add(CircularPatternFeature5); api.GetCompDef().Features.CircularPatternFeatures.Add(objCollection6, api.GetCompDef().WorkAxes[2], true, 2, "150 degree", true, PatternComputeTypeEnum.kIdenticalCompute); // Отверстия под болты sketch[7] = api.Sketch(api.GetCompDef().WorkPlanes[2]); point[0] = api.Point(sketch[7], 0, 0); point[1] = api.Point(sketch[7], 0, MBRb / 10); point[2] = api.Point(sketch[7], MBRb / 10, 0); line[0] = api.Line(sketch[7], point[1], point[0]); line[1] = api.Line(sketch[7], point[0], point[2]); sketch[7].DimensionConstraints.AddTwoLineAngle(line[0], line[1], api.GetTransGeom().CreatePoint2d(1, 1)); sketch[7].GeometricConstraints.AddHorizontal((SketchEntity)line[1]); circle[0] = api.Circle(sketch[7], point[1], MBRm / 10 / 2); oParameters["d21"].Expression = "82.5 degree"; sketch[7].GeometricConstraints.AddCoincident((SketchEntity)circle[0].CenterSketchPoint, (SketchEntity)point[1]); profile[7] = api.Profile(sketch[7]); extrude[7] = api.Extrude(profile[7], 10000, 2, 1); var objCollection7 = api.ObjectCollection(); objCollection7.Add(extrude[7]); api.GetCompDef().Features.CircularPatternFeatures.Add(objCollection7, api.GetCompDef().WorkAxes[2], true, 3, "360 degree", true, PatternComputeTypeEnum.kIdenticalCompute); // Загрузка сыпучих материалов sketch[8] = api.Sketch(oWorkPlane2); point[0] = api.Point(sketch[8], 0, 0); point[1] = api.Point(sketch[8], 0, -R1R / 10); point[2] = api.Point(sketch[8], -R1R / 10, 0); line[0] = api.Line(sketch[8], point[0], point[1]); line[1] = api.Line(sketch[8], point[0], point[2]); sketch[8].DimensionConstraints.AddTwoLineAngle(line[0], line[1], api.GetTransGeom().CreatePoint2d(1, 1)); sketch[8].GeometricConstraints.AddVertical((SketchEntity)line[0]); circle[0] = api.Circle(sketch[8], api.Point(sketch[8], -R1R / 10, -1), D1R / 10 / 2); oParameters["d27"].Expression = "75 degree"; sketch[8].GeometricConstraints.AddCoincident((SketchEntity)circle[0].CenterSketchPoint, (SketchEntity)point[2]); profile[8] = api.Profile(sketch[8]); extrude[8] = api.Extrude(profile[8], Hr / 10, 2, 0); sketch[9] = api.Sketch(extrude[8].Faces[1]); circle[0] = api.Circle(sketch[9], api.Point(sketch[9], 0, 0), D1r / 10 / 2); profile[9] = api.Profile(sketch[9]); extrude[9] = api.Extrude(profile[9], HR / 10 - H / 10, 0, 0); sketch[10] = api.Sketch(extrude[8].Faces[1]); circle[0] = api.Circle(sketch[10], api.Point(sketch[10], 0, 0), T1R / 10 / 2); profile[10] = api.Profile(sketch[10]); extrude[10] = api.Extrude(profile[10], 10000, 2, 1); sketch[11] = api.Sketch(extrude[8].Faces[1]); circle[0] = api.Circle(sketch[11], api.Point(sketch[11], 0, O1R / 10), O1r / 10 / 2); profile[11] = api.Profile(sketch[11]); extrude[11] = api.Extrude(profile[11], Hr / 10, 1, 1); var Axis11 = api.GetCompDef().WorkAxes.AddByRevolvedFace(extrude[10].Faces[1]); Axis11.Visible = false; var objCollection11 = api.ObjectCollection(); objCollection11.Add(extrude[11]); api.GetCompDef().Features.CircularPatternFeatures.Add(objCollection11, Axis11, true, 12, "360 degree", true, PatternComputeTypeEnum.kIdenticalCompute); System.Windows.Forms.MessageBox.Show(formName + " завершено.", formName); }
public void RunWithArguments(Document doc, NameValueMap map) { //LogTrace("Processing " + doc.FullFileName); //try //{ // if (doc.DocumentType == DocumentTypeEnum.kPartDocumentObject) // { // using (new HeartBeat()) // { // // TODO: handle the Inventor part here // } // } // else if (doc.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject) // Assembly. // { // using (new HeartBeat()) // { // // TODO: handle the Inventor assembly here // } // } //} //catch (Exception e) //{ // LogError("Processing failed. " + e.ToString()); //} LogTrace("Initialiting"); PartDocument oPartDoc = (PartDocument)inventorApplication.Documents.Add(DocumentTypeEnum.kPartDocumentObject, inventorApplication.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject), true); LogTrace("Part template opened"); TransientGeometry oTG = inventorApplication.TransientGeometry; PartComponentDefinition oPartComDef = oPartDoc.ComponentDefinition; UserParameters oParams = oPartComDef.Parameters.UserParameters; oParams.AddByExpression("width", "50", UnitsTypeEnum.kMillimeterLengthUnits); oParams.AddByExpression("height", "10", UnitsTypeEnum.kMillimeterLengthUnits); oParams.AddByExpression("length", "10", UnitsTypeEnum.kMillimeterLengthUnits); LogTrace("Standard parameters created"); Point2d[] oPoints = new Point2d[4]; oPoints[0] = oTG.CreatePoint2d(0, 0); oPoints[1] = oTG.CreatePoint2d(0, oPartComDef.Parameters.GetValueFromExpression("width", UnitsTypeEnum.kMillimeterLengthUnits)); oPoints[2] = oTG.CreatePoint2d(oPartComDef.Parameters.GetValueFromExpression("height", UnitsTypeEnum.kMillimeterLengthUnits), 0); oPoints[3] = oTG.CreatePoint2d(oPartComDef.Parameters.GetValueFromExpression("height", UnitsTypeEnum.kMillimeterLengthUnits), oPartComDef.Parameters.GetValueFromExpression("width", UnitsTypeEnum.kMillimeterLengthUnits)); LogTrace("Inventor points created"); LogTrace("Initiating sketch creation..."); PlanarSketch oSketch = oPartComDef.Sketches.Add(oPartComDef.WorkPlanes[1]); SketchPoint[] osPoints = new SketchPoint[4]; SketchLine[] oLines = new SketchLine[4]; osPoints[0] = oSketch.SketchPoints.Add(oPoints[0]); osPoints[1] = oSketch.SketchPoints.Add(oPoints[1]); osPoints[2] = oSketch.SketchPoints.Add(oPoints[2]); osPoints[3] = oSketch.SketchPoints.Add(oPoints[3]); oLines[0] = oSketch.SketchLines.AddByTwoPoints(osPoints[0], osPoints[1]); oLines[1] = oSketch.SketchLines.AddByTwoPoints(oLines[0].EndSketchPoint, osPoints[3]); oLines[2] = oSketch.SketchLines.AddByTwoPoints(oLines[1].EndSketchPoint, osPoints[2]); oLines[3] = oSketch.SketchLines.AddByTwoPoints(oLines[2].EndSketchPoint, oLines[0].StartSketchPoint); LogTrace("Sketch created, adding dimensions"); oSketch.DimensionConstraints.AddTwoPointDistance(osPoints[0], osPoints[1], DimensionOrientationEnum.kAlignedDim, oPoints[1]); //d0// oSketch.DimensionConstraints.AddTwoPointDistance(osPoints[1], osPoints[3], DimensionOrientationEnum.kAlignedDim, oPoints[3]); //d1// LogTrace("Dimensions added to the sketch, changing standard values for User parameter values"); var inventorMParams = oPartComDef.Parameters.ModelParameters; foreach (ModelParameter mParam in inventorMParams) { if (mParam.Name.Contains("d0")) { mParam.Expression = "width"; } else if (mParam.Name.Contains("d1")) { mParam.Expression = "height"; } } LogTrace("Dimensions with user parameter values created, starting extrude operation"); //oSketch.DimensionConstraints.AddTwoPointDistance(oPoints[0], oPoints[1], DimensionOrientationEnum.kAlignedDim, "width", true); Profile oProfile = oSketch.Profiles.AddForSolid(); ExtrudeDefinition oExtrudeDef = oPartComDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, PartFeatureOperationEnum.kJoinOperation); oExtrudeDef.SetDistanceExtent(oPartComDef.Parameters.UserParameters.AddByExpression("length", "length", UnitsTypeEnum.kMillimeterLengthUnits), PartFeatureExtentDirectionEnum.kPositiveExtentDirection); ExtrudeFeature oExtrude = oPartComDef.Features.ExtrudeFeatures.Add(oExtrudeDef); //oExtrude.FeatureDimensions[1].Parameter.Name = "length"; LogTrace("Extrude operation finished"); XmlDocument xmlDoc = new XmlDocument(); string currentDir = System.IO.Directory.GetCurrentDirectory(); string projectDir = Directory.GetParent(currentDir).Parent.FullName; LogTrace("Reading XML input file from " + projectDir); xmlDoc.Load(System.IO.Path.Combine(projectDir, "React-BIM-output.xml")); //xmlDoc.Load("C:\\webapps\\IpartCreator\\React-BIM-output.xml"); XmlNodeList memberNodeList = xmlDoc.GetElementsByTagName("Member"); XmlNodeList partNumberNodeList = xmlDoc.GetElementsByTagName("PartNumber"); XmlNodeList widthNodeList = xmlDoc.GetElementsByTagName("width"); XmlNodeList heightNodeList = xmlDoc.GetElementsByTagName("height"); XmlNodeList lengthNodeList = xmlDoc.GetElementsByTagName("length"); LogTrace("XML tag values imported"); LogTrace("Creating iPart"); iPartFactory oFactory = oPartComDef.CreateFactory(); Worksheet oWS = oFactory.ExcelWorkSheet; Workbook oWB = (Workbook)oWS.Parent; LogTrace("Generating Excel file for iPart"); oWS.Cells[1, 1] = "Member<defaultRow>1</defaultRow><filename></filename>"; oWS.Cells[1, 2] = "Part Number [Project]"; oWS.Cells[1, 3] = "width"; oWS.Cells[1, 4] = "height"; oWS.Cells[1, 5] = "length"; for (int i = 0; i < memberNodeList.Count; i++) { oWS.Cells[(i + 2), 1] = memberNodeList[i].InnerText; oWS.Cells[(i + 2), 2] = partNumberNodeList[i].InnerText; oWS.Cells[(i + 2), 3] = widthNodeList[i].InnerText; oWS.Cells[(i + 2), 4] = heightNodeList[i].InnerText; oWS.Cells[(i + 2), 5] = lengthNodeList[i].InnerText; } oWB.Save(); oWB.Close(); LogTrace("Excel created"); oPartDoc.Update(); string iPartPath = projectDir + "/results/bimipart.ipt"; int iNumRows = oFactory.TableRows.Count; LogTrace("Saving iPart to " + iPartPath); oPartDoc.SaveAs(iPartPath, false); LogTrace("Opening new assembly template"); AssemblyDocument oAssyDoc = (AssemblyDocument)inventorApplication.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject, inventorApplication.FileManager.GetTemplateFile(DocumentTypeEnum.kAssemblyDocumentObject), true); AssemblyComponentDefinition oAssyComDef = oAssyDoc.ComponentDefinition; ComponentOccurrences oAssyCompOccs = oAssyComDef.Occurrences; LogTrace("Creating Matrix"); Matrix oPos = oTG.CreateMatrix(); int oStep = 0; int iRow; LogTrace("Placing iPart members to assembly"); for (iRow = 1; iRow <= iNumRows; iRow++) { oStep = oStep + 150; oPos.SetTranslation(oTG.CreateVector(oStep, oStep, 0), false); ComponentOccurrence oOcc = oAssyCompOccs.AddiPartMember(iPartPath, oPos, iRow); } string assyPath = projectDir + "/results/bimassy.iam"; LogTrace("Saving Assembly file to " + assyPath); oAssyDoc.SaveAs(assyPath, false); }
private void circleSticker(ref PartDocument pDoc, double heigth, double width, double R, string txt = "", double thickness = 0.1) { PartComponentDefinition compDef = pDoc.ComponentDefinition; heigth /= 10; width /= 10; thickness /= 10; PlanarSketch ps = compDef.Sketches.Add(compDef.WorkPlanes[2]); //SketchEntity origin = ps.AddByProjectingEntity(compDef.WorkPoints[1]); double alfa = alfaFromL(heigth, R); Point2d startPt = m_TG.CreatePoint2d(); SketchArc arc = ps.SketchArcs.AddByCenterStartSweepAngle(startPt, R, 3.1415926 / 2 - alfa / 2, alfa); //ObjectCollection objs = invApp.TransientObjects.CreateObjectCollection(); //objs.Add(arc); //ps.RotateSketchObjects(objs, arc.CenterSketchPoint.Geometry, 1,RemoveConstraints:true); //arc = (SketchArc)en[1]; //ps.GeometricConstraints.AddVerticalAlign((SketchPoint)origin, arc.CenterSketchPoint); ObjectCollection objCol = invApp.TransientObjects.CreateObjectCollection(); objCol.Add(arc); SketchEntitiesEnumerator sArc = ps.OffsetSketchEntitiesUsingDistance(objCol, thickness, true); SketchArc arc2 = (SketchArc)sArc[1]; ps.SketchLines.AddByTwoPoints(arc2.StartSketchPoint, arc.StartSketchPoint); ps.SketchLines.AddByTwoPoints(arc2.EndSketchPoint, arc.EndSketchPoint); Profile pr = ps.Profiles.AddForSolid(); ExtrudeDefinition extDef = compDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(pr, PartFeatureOperationEnum.kNewBodyOperation); extDef.SetDistanceExtent(width / 2, PartFeatureExtentDirectionEnum.kNegativeExtentDirection); extDef.SetDistanceExtentTwo(width / 2); ExtrudeFeature extr = compDef.Features.ExtrudeFeatures.Add(extDef); extr.Appearance = InvDoc.u.createColor(pDoc, "white_", "белый_", 255, 255, 255); if (txt != "") { ps = compDef.Sketches.Add(compDef.WorkPlanes[3]); Inventor.TextBox tb = ps.TextBoxes.AddByRectangle(pts(-heigth, -width), pts(heigth, width), txt); tb.HorizontalJustification = HorizontalTextAlignmentEnum.kAlignTextCenter; tb.VerticalJustification = VerticalTextAlignmentEnum.kAlignTextMiddle; tb.SingleLineText = false; tb.Rotation = Math.PI; if (mirror) { tb.Rotation = Math.PI; } if (this.radioButton1.Checked == false) { //ObjectCollection col = invApp.TransientObjects.CreateObjectCollection(); //col.Add(tb); //ps.RotateSketchObjects(col, pt, Math.PI / 4); tb.Rotation -= Math.PI / 2; } Face face2 = null; foreach (Face f in compDef.SurfaceBodies[1].Faces) { if (f.SurfaceType == SurfaceTypeEnum.kCylinderSurface) { double val = Math.Round(((Cylinder)f.Geometry).Radius, 3) * 100; val = Math.Round(val, 0); if /*((int)val == (int)((R + thickness)*100))*/ (InvDoc.u.eq(val, (R + thickness) * 100)) { face2 = f; break; } } } EmbossFeature emb = compDef.Features.EmbossFeatures.AddEmbossFromFace(ps.Profiles.AddForSolid(false, ps.TextBoxes), 0.0005, PartFeatureExtentDirectionEnum.kNegativeExtentDirection, WrapFace: face2); emb.Appearance = InvDoc.u.createColor(pDoc, "black_", "черный_", 0, 0, 0); } }