Ejemplo n.º 1
0
        /// <summary>
        /// Assumes that the tools are non overlapping sheets and that the sheets fully
        /// overlap the target. The target should be cut into N+1 parts of there are N
        /// tools. They
        /// </summary>
        /// <param name="target"></param>
        /// <param name="tools"></param>
        /// <returns></returns>
        public static IEnumerable <IBody2> CutBySheets(this IBody2 target, IEnumerable <IBody2> tools)
        {
            var targets = new List <IBody2>()
            {
                target.CopyTs()
            };

            foreach (var tool in tools)
            {
                targets = targets.SelectMany
                              (tgt =>
                {
                    var result = tgt.Cut(tool);
                    if (result.Error != 0)
                    {
                        return new[] { tgt }
                    }
                    ;
                    //throw new Exception("Tool was unable to cut");
                    return(result.Bodies);
                })
                          .ToList();
            }
            return(targets);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Perform Add, Cut, Intersect operations on solid bodies.
        /// </summary>
        /// <param name="body"></param>
        /// <param name="type"></param>
        /// <param name="tool"></param>
        /// <returns></returns>
        public static OperationsResult OperationsTs(this IBody2 body, swBodyOperationType_e type, IBody2 tool)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
            if (tool == null)
            {
                throw new ArgumentNullException(nameof(tool));
            }

            tool = tool.CopyTs();
            body = body.CopyTs();

            int error;
            var objects = (object[])body.Operations2((int)type, tool, out error);

            if (objects == null)
            {
                return(new OperationsResult(error, new IBody2[] {}));
            }

            var bodies = error == 0 ?  objects.Cast <IBody2>().ToArray() : new IBody2[] {};

            return(new OperationsResult(error, bodies));
        }
 /// <summary>
 /// Adds tracking ids to a body faces and edges. This is not the best way to
 /// do this in a repeatable way but works quickly.
 /// </summary>
 /// <param name="macroFeatureData"></param>
 /// <param name="body"></param>
 public static int AddIdsToBody(this IMacroFeatureData macroFeatureData, IBody2 body, int i = 1)
 {
     if (body == null)
     {
         throw new ArgumentNullException(nameof(body));
     }
     {
         object FacesNeedId;
         object EdgesNeedId;
         macroFeatureData.GetEntitiesNeedUserId((object)body, out FacesNeedId, out EdgesNeedId);
         var edgesNeedId = (object[])EdgesNeedId;
         var facesNeedId = (object[])FacesNeedId;
         var empty       = new object[] {};
         foreach (var edge in edgesNeedId ?? empty)
         {
             if (!macroFeatureData.SetEdgeUserId((Edge)edge, i, 0))
             {
                 throw new Exception("SetUserIdFailed");
             }
             i++;
         }
         foreach (var face in facesNeedId ?? empty)
         {
             if (!macroFeatureData.SetFaceUserId((Face2)face, i, 0))
             {
                 throw new Exception("SetUserIdFailed");
             }
             i++;
         }
     }
     return(i);
 }
Ejemplo n.º 4
0
        //private const string FILE_PATH = @"D:\body.dat";

        public static void ExportBodyToFile(string FILE_PATH)
        {
            ISldWorks app = PStandAlone.GetSolidWorks();

            app.Visible = true;

            IModelDoc2 swModel;

            swModel = app.IActiveDoc2;

            if (swModel != null)
            {
                IBody2 body = (Body2)swModel.ISelectionManager.GetSelectedObject6(1, -1);

                if (body != null)
                {
                    SaveBodyToFile(body, FILE_PATH);
                }
                else
                {
                    throw new Exception("Please select body to export");
                }
            }
            else
            {
                throw new Exception("Please open the model");
            }
        }
        public void ShowPreview(IPartDoc part, object inputObj, bool concentric, double step, double extraRadius)
        {
            HidePreview(part);

            try
            {
                var cylParams = GetCylinderParameters(part, inputObj, concentric, step, extraRadius);
                m_TempBody = CreateCylindricalStock(cylParams);
            }
            catch
            {
            }

            if (m_TempBody != null)
            {
                const int COLORREF_YELLOW = 65535;

                m_TempBody.Display3(part, COLORREF_YELLOW,
                                    (int)swTempBodySelectOptions_e.swTempBodySelectOptionNone);

                m_TempBody.MaterialPropertyValues2 = new double[] { 1, 1, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 };

                (part as IModelDoc2).GraphicsRedraw2();
            }
        }
Ejemplo n.º 6
0
        private IBody2[] GetViewBodies(IView view)
        {
            IEnumerable <IBody2> bodies = null;

            if (view.IsFlatPatternView())
            {
                var visComps = view.GetVisibleComponents() as object[];

                if (visComps == null || !visComps.Any())
                {
                    throw new NullReferenceException("No components in this view");
                }

                var faces = view.GetVisibleEntities2(visComps.First() as Component2,
                                                     (int)swViewEntityType_e.swViewEntityType_Face) as object[];

                bodies = new IBody2[]
                {
                    (faces.FirstOrDefault() as IFace2).IGetBody()
                };
            }
            else
            {
                bodies = (view.Bodies as object[]).Cast <IBody2>().ToArray();
            }

            return(bodies.ToArray());
        }
Ejemplo n.º 7
0
        protected override MacroFeatureRebuildResult OnRebuild(ISldWorks app, IModelDoc2 model, IFeature feature)
        {
            //use extension methods of IModeler to create a box body
            IBody2 tempBody = app.IGetModeler().CreateBox(new Point(0, 0, 0), new Vector(1, 0, 0), 0.1, 0.1, 0.1);

            return(MacroFeatureRebuildResult.FromBody(tempBody, feature.GetDefinition() as IMacroFeatureData, false));
        }
Ejemplo n.º 8
0
        public void Main()
        {
            PartDoc part = swApp.ActiveDoc as PartDoc;

            if (part != null)
            {
                IFace2 face = (part as IModelDoc2).ISelectionManager.GetSelectedObject6(1, -1) as IFace2;

                if (face != null && face.IGetSurface().IsSphere())
                {
                    double[] sphereParams = face.IGetSurface().SphereParams as double[];

                    IModeler modeler = swApp.IGetModeler();

                    ISurface sphereSurf = modeler.CreateSphericalSurface2(
                        new double[] { sphereParams[0], sphereParams[1], sphereParams[2] },
                        new double[] { 0, 0, 1 },
                        new double[] { 1, 0, 0 }, sphereParams[3]) as ISurface;

                    m_PreviewBody = sphereSurf.CreateTrimmedSheet4(new ICurve[] { null }, true) as IBody2;

                    m_PreviewBody.Display3(part, ToColorRef(255, 255, 0), (int)swTempBodySelectOptions_e.swTempBodySelectOptionNone);

                    part.ClearSelectionsNotify += new DPartDocEvents_ClearSelectionsNotifyEventHandler(OnClearSelections);
                }
                else
                {
                    swApp.SendMsgToUser("Please select spherical surface");
                }
            }
            else
            {
                swApp.SendMsgToUser("Please open part document");
            }
        }
        private void OnPageClosing(swPropertyManagerPageCloseReasons_e reason, SwEx.PMPage.Base.ClosingArg arg)
        {
            if (reason == swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Okay)
            {
                IBody2 body = null;

                Exception err = null;

                try
                {
                    var cylParams = m_Model.GetCylinderParameters(m_CurrentPart, m_CurrentParameters.Direction,
                                                                  m_CurrentParameters.ConcenticWithCylindricalFace,
                                                                  m_CurrentParameters.StockStep, m_CurrentParameters.ExtraRadius);

                    body = m_Model.CreateCylindricalStock(cylParams);
                }
                catch (Exception ex)
                {
                    err = ex;
                }

                if (body == null)
                {
                    arg.Cancel       = true;
                    arg.ErrorTitle   = "Cylindrical Stock Error";
                    arg.ErrorMessage = err?.Message;
                }
            }
        }
Ejemplo n.º 10
0
        public static void DisplayTs(this IBody2 body, IModelDoc2 doc = null, Color?c = null, swTempBodySelectOptions_e opt = swTempBodySelectOptions_e.swTempBodySelectOptionNone)
        {
            doc = doc ?? (IModelDoc2)SwAddinBase.Active.SwApp.ActiveDoc;
            c   = c ?? Color.Yellow;
            var colorref = ColorTranslator.ToWin32(c.Value);

            body.Display3(doc, colorref, (int)opt);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get the edges formed by intersection both bodies together. The bodies are first copied
        /// before intersecting so that the input bodies are not modified.
        /// </summary>
        /// <param name="toolBody"></param>
        /// <param name="cuttingPlane"></param>
        /// <returns></returns>
        public static List <IEdge> GetIntersectionEdgesNonDestructive(this IBody2 toolBody, IBody2 cuttingPlane)
        {
            toolBody     = (IBody2)toolBody.Copy();
            cuttingPlane = (IBody2)cuttingPlane.Copy();
            var enumerable = ((object[])toolBody.GetIntersectionEdges(cuttingPlane)).Cast <IEdge>().ToList();

            return(enumerable);
        }
Ejemplo n.º 12
0
 public static IDisposable HideBodyUndoable(this IBody2 body)
 {
     body.HideBody(true);
     return(Disposable.Create(() =>
     {
         body.HideBody(false);
     }));
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Return the bounding box of the solid renderable.
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public static Range3Single GetBodyBoxTs(this IBody2 body)
        {
            var box = (double[])body.GetBodyBox();

            return(new Range3Single(
                       new Vector3((float)box[0], (float)box[1], (float)box[2]),
                       new Vector3((float)box[3], (float)box[4], (float)box[5])));
        }
Ejemplo n.º 14
0
 public RayIntersection(IBody2 body, int rayIndex, swRayPtsResults_e intersectionType, Vector3 hitPoint, Vector3 normals)
 {
     Body             = body;
     RayIndex         = rayIndex;
     IntersectionType = intersectionType;
     HitPoint         = hitPoint;
     Normals          = normals;
 }
 public void HidePreview(IPartDoc part)
 {
     if (m_TempBody != null)
     {
         m_TempBody.Hide(part);
         m_TempBody = null;
         GC.Collect();
     }
 }
Ejemplo n.º 16
0
 public BodyMaterials(IBody2 body)
 {
     _Body = body;
     if (body.MaterialPropertyValues2 == null || body.MaterialPropertyValues2.CastArray <double>().Length == 0)
     {
         body.MaterialPropertyValues2 = InitMat();
     }
     Color = Color.Black;
 }
Ejemplo n.º 17
0
        public void PreviewOffset(IEnumerable <ISketchSegment> segs, double offset,
                                  double innerRadius, double outerRadius, bool reverse)
        {
            HidePreview();
            m_PreviewOffsetFilletBody = CreateOffset(segs, offset, innerRadius, outerRadius, reverse);

            m_PreviewOffsetFilletBody.Display3(m_Model, ConvertColor(KnownColor.Yellow),
                                               (int)swTempBodySelectOptions_e.swTempBodySelectOptionNone);
        }
Ejemplo n.º 18
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                Marshal.ReleaseComObject(m_TempBody);
            }

            m_TempBody = null;
        }
Ejemplo n.º 19
0
        //NOTE: keeping the pointer in this class only so it can be properly disposed

        internal SwTempBody(IBody2 body) : base(null, null)
        {
            if (!body.IsTemporaryBody())
            {
                throw new ArgumentException("Body is not temp");
            }

            m_TempBody = body;
        }
Ejemplo n.º 20
0
        //NOTE: keeping the pointer in this class only so it can be properly disposed
        internal SwTempBody(IBody2 body, ISwApplication app) : base(null, null, app)
        {
            if (!body.IsTemporaryBody())
            {
                throw new ArgumentException("Body is not temp");
            }

            m_TempBody  = body;
            m_MathUtils = app.Sw.IGetMathUtility();
        }
Ejemplo n.º 21
0
        public static MeshBuilder <VERTEX> GetBodyMeshBuilder(this IBody2 swBody2, MaterialBuilder docMaterial, bool improvedQuality = true)
        {
            var mesh = new MeshBuilder <VERTEX>();

            var bodyMat = swBody2.GetMaterialBuilder() ?? docMaterial;

            //网格化
            var swTessellation = (Tessellation)swBody2.GetTessellation(null);
            {
                swTessellation.NeedFaceFacetMap = true;
                swTessellation.NeedVertexParams = true;
                swTessellation.NeedVertexNormal = true;
                swTessellation.ImprovedQuality  = improvedQuality;
                // How to handle matches across common edges
                swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology;
                // Do it
                bool bResult = swTessellation.Tessellate();
            }

            var face = (Face2)swBody2.GetFirstFace();

            while ((face != null))
            {
                var faceMaterial = face.GetMaterialBuilder();
                var prim         = mesh.UsePrimitive(faceMaterial ?? bodyMat);

                int[] vFacetId = (int[])swTessellation.GetFaceFacets(face);

                //Should always be three fins per facet
                for (int i = 0; i < vFacetId.Length; i++)
                {
                    int[]         vFinId = (int[])swTessellation.GetFacetFins(vFacetId[i]);
                    List <VERTEX> points = new List <VERTEX>();
                    for (int j = 0; j < 3; j++)
                    {
                        int[] vVertexId = (int[])swTessellation.GetFinVertices(vFinId[j]);
                        //Should always be two vertices per fin
                        double[] vVertex1 = (double[])swTessellation.GetVertexPoint(vVertexId[0]);
                        double[] vVertex2 = (double[])swTessellation.GetVertexPoint(vVertexId[1]);

                        points.Add(new VERTEX(
                                       (float)vVertex1[0], (float)vVertex1[1], (float)vVertex1[2]
                                       ));
                        points.Add(new VERTEX(
                                       (float)vVertex2[0], (float)vVertex2[1], (float)vVertex2[2]
                                       ));
                    }
                    prim.AddTriangle(points[0], points[2], points[4]);
                }

                face = (Face2)face.GetNextFace();
            }

            return(mesh);
        }
Ejemplo n.º 22
0
 private IBody2 ConvertToTempIfNeeded(IBody2 body)
 {
     if (body.IsTemporaryBody())
     {
         return(body);
     }
     else
     {
         return(body.ICopy());
     }
 }
Ejemplo n.º 23
0
        public static T SaveAsIges <T>(this IBody2 body, bool hidden, Func <Stream, T> selector)
        {
            T r = default(T);

            SaveAsIges
                (body,
                stream =>
            {
                r = selector(stream);
            }, hidden);
            return(r);
        }
Ejemplo n.º 24
0
        private void GetExtremePoints(IBody2 body, double[] dir, out double[] pt1, out double[] pt2)
        {
            double x;
            double y;
            double z;

            body.GetExtremePoint(dir[0], dir[1], dir[2], out x, out y, out z);
            pt1 = new double[] { x, y, z };

            body.GetExtremePoint(-dir[0], -dir[1], -dir[2], out x, out y, out z);
            pt2 = new double[] { x, y, z };
        }
Ejemplo n.º 25
0
        public static void DisplayTs([NotNull] this IBody2 body, IModelDoc2 doc = null, Color?c = null, swTempBodySelectOptions_e opt = swTempBodySelectOptions_e.swTempBodySelectOptionNone)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
            doc = doc ?? (IModelDoc2)SwAddinBase.Active.SwApp.ActiveDoc;
            c   = c ?? Color.Yellow;
            var colorref = ColorTranslator.ToWin32(c.Value);

            body.Display3(doc, colorref, (int)opt);
        }
Ejemplo n.º 26
0
        public static bool hitMainBodyBefore(double[] rayOrigin, double[] rayDirection, double[] hitPointToCompareTo)
        {
            List <IBody2> bodies = new List <IBody2>();

            object vBodyInfo;

            object[] componentBodies = (object[])mainBody.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);
            for (int i = 0; i < componentBodies.Length; i++)
            {
                IBody2 tempBody = ((Body2)componentBodies[i]).ICopy();
                tempBody.ApplyTransform(mainBody.Transform2);
                bodies.Add(tempBody);
            }

            int numIntersectionsFound = (int)swDoc.RayIntersections((object)bodies.ToArray(),
                                                                    (object)rayOrigin,
                                                                    (object)rayDirection,
                                                                    (int)(swRayPtsOpts_e.swRayPtsOptsTOPOLS | swRayPtsOpts_e.swRayPtsOptsNORMALS | swRayPtsOpts_e.swRayPtsOptsENTRY_EXIT),
                                                                    (double).0000001,
                                                                    (double).0000001);

            double[] horrifyingReturn = (double[])swDoc.GetRayIntersectionsPoints();

            if (numIntersectionsFound == 0)
            {
                return(false);
            }

            int lengthOfOneReturn = 9;

            for (int i = 0; i < numIntersectionsFound; i++)
            {
                byte intersectionType = (byte)horrifyingReturn[i * lengthOfOneReturn + 2];

                if ((intersectionType & (byte)swRayPtsResults_e.swRayPtsResultsENTER) == 0)
                {
                    // we need it to be just entry rays
                    continue;
                }

                double x = horrifyingReturn[i * lengthOfOneReturn + 3];
                double y = horrifyingReturn[i * lengthOfOneReturn + 4];
                double z = horrifyingReturn[i * lengthOfOneReturn + 5];

                if (distanceAlongRay(rayOrigin, new double[] { x, y, z }) < distanceAlongRay(rayOrigin, hitPointToCompareTo))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 27
0
        public static void SaveAsIges(this IBody2 body, string igesFile, bool hidden = false)
        {
            SldWorks app = SwAddinBase.Active.SwApp;

            var doc = app.CreateHiddenDocument(hidden: hidden);

            doc.Extension.SetUserPreferenceInteger
                ((int)(swUserPreferenceIntegerValue_e.swUnitSystem)
                , 0
                , ((int)(swUnitSystem_e.swUnitSystem_MKS)));

            try
            {
                var partDoc = (PartDoc)doc;

                partDoc.CreateFeatureFromBody3(body, false, 0);

                int errorsi   = 0;
                int warningsi = 0;

                app.ActivateDoc3
                    (doc.GetTitle(), false, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errorsi);


                // http://help.solidworks.com/2013/english/api/sldworksapi/SolidWorks.Interop.sldworks~SolidWorks.Interop.sldworks.IModelDocExtension~SaveAs.html
                // Note the doc says:
                // To save as an IGES, STL, or STEP file, the document to convert must be the active document. Before calling this method:
                // Call ISldWorks::ActivateDoc3 to make the document to convert the active document.
                // Call ISldWorks::ActiveDoc to get the active document.

                var status = doc // Note that this does not return the correct doc if the doc is hidden
                             .Extension
                             .SaveAs
                                 (igesFile
                                 , (int)swSaveAsVersion_e.swSaveAsCurrentVersion
                                 , (int)swSaveAsOptions_e.swSaveAsOptions_Silent
                                 , null
                                 , ref errorsi
                                 , ref warningsi
                                 );

                if (!status)
                {
                    throw new Exception($"Failed to save {igesFile}. Got error bitmask {errorsi}");
                }
            }
            finally
            {
                app.QuitDoc(doc.GetTitle());
            }
        }
Ejemplo n.º 28
0
        public CylinderParams GetBoundingCylinder(IBody2 body, double[] dir)
        {
            double[] xAxis = new double[] { 1, 0, 0 };
            double[] yAxis = new double[] { 0, 1, 0 };
            double[] zAxis = new double[] { 0, 0, 1 };

            bool           isAligned      = m_MathHelper.ArrayEqual(dir, yAxis);
            IMathTransform alignTransform = null;

            if (!isAligned)
            {
                alignTransform = m_MathHelper.GetTransformBetweenVectorsAroundPoint(
                    dir, yAxis, new double[] { 0, 0, 0 });

                IBody2 bodyCopy = body.ICopy();

                bodyCopy.ApplyTransform(alignTransform as MathTransform);

                body = bodyCopy;
            }

            double[] rootPt;
            double[] endPt;
            GetExtremePoints(body, yAxis, out rootPt, out endPt);

            double height = Math.Abs(endPt[1] - rootPt[1]);

            dir = new double[] { 0, endPt[1] - rootPt[1], 0 };

            List <double[]> perPoints = GetPerimeterPoints(body, xAxis, zAxis);
            List <Point>    points    = new List <Point>();

            foreach (double[] pt in perPoints)
            {
                points.Add(new Point(pt[0], pt[2]));
            }

            Circle cir = SmallestEnclosingCircle.MakeCircle(points);

            double[] circCenter = new double[] { cir.c.x, rootPt[1], cir.c.y };

            if (!isAligned)
            {
                circCenter = m_MathHelper.TransformPoint(circCenter, alignTransform.IInverse());
                dir        = m_MathHelper.TransformVector(dir, alignTransform.IInverse());
            }

            double radius = cir.r;

            return(new CylinderParams(height, circCenter, dir, radius));
        }
        public static IBody2[] SplitBodies(IModeler modeler, IBody2 body, SampleMacroFeatureDataBase database)
        {
            var box    = body.GetBodyBoxTs();
            var center = box.Center;
            var axisX  = Vector3.UnitX;

            // Find the point to cut the object
            center.X = (double)(database.Alpha * box.P0.X + (1 - database.Alpha) * box.P1.X);
            var sheet = modeler.CreateSheet(center, axisX, box.MaxDim * 2);

            var cutResult = body.Cut(sheet);

            return(cutResult.Error == 0 ? cutResult.Bodies : null);
        }
Ejemplo n.º 30
0
        public static ITessellation GetTess(IBody2 body, IFace2[] faceList)
        {
            var tess = (ITessellation)body.GetTessellation(faceList);

            tess.NeedFaceFacetMap      = true;
            tess.NeedVertexParams      = true;
            tess.NeedVertexNormal      = true;
            tess.ImprovedQuality       = true;
            tess.NeedEdgeFinMap        = true;
            tess.CurveChordTolerance   = 0.001 / 10;
            tess.SurfacePlaneTolerance = 0.001 / 10;
            tess.MatchType             = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology;
            tess.Tessellate();
            return(tess);
        }
 public static void SetManipulatorPositionToBodyCenter(ISldWorks sldWorks, TriadManipulatorTs manipulator, IBody2 body, IModelDoc2 model)
 {
     var box = body.GetBodyBoxTs();
     manipulator.Origin = (MathPoint) ((IMathUtility) sldWorks.GetMathUtility()).CreatePoint(box.Center.ToDoubles());
     manipulator.UpdatePosition();
 }
        private static IBody2[] RoundTrip(IBody2 cutBody)
        {
            var faces = cutBody.GetFaces().CastArray<IFace2>();
            var sheets = faces
                .Select(face => BSplineFace.Create(face).ToSheetBody())
                .AssertAllSome()
                .ToArray();

            //foreach (var sheet in sheets)
            //{
            //    yielder(sheet.DisplayUndoable(modelDoc));
            //}


            var error = (int) swSheetSewingError_e.swSewingOk;
            var body = Modeler
                .CreateBodiesFromSheets2(sheets, (int) swSheetSewingOption_e.swSewToSolid, 1e-5, ref error)
                .CastArray<IBody2>();
            return body;
        }