protected override bool OnMouseMove(ScreenPoint cursorPos, Line cursorRay, MouseButtons button)
        {
            if (button != MouseButtons.None)
            {
                return(false);
            }

            IDocObject preselection = InteractionContext.Preselection;
            DesignEdge designEdge   = preselection as DesignEdge;

            if (designEdge == null) // selection filtering is not applied if you (pre)select in the tree
            {
                return(false);
            }

            Circle edgeCircle = (Circle)designEdge.Shape.Geometry;

            CurveSegment innerCurve = CurveSegment.Create(Circle.Create(edgeCircle.Frame, apiGroove.InnerDiameter / 2));
            CurveSegment outerCurve = CurveSegment.Create(Circle.Create(edgeCircle.Frame, apiGroove.OuterDiameter / 2));

            var style = new GraphicStyle {
                LineColor = Color.DarkGray,
                LineWidth = 2
            };
            Graphic centerLine = Graphic.Create(style, new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurve) });

            style = new GraphicStyle {
                LineColor = Color.White,
                LineWidth = 4
            };
            Graphic highlightLine = Graphic.Create(style, new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurve) });

            Rendering = Graphic.Create(style, null, new[] { highlightLine, centerLine });
            return(false); // if we return true, the preselection won't update
        }
Beispiel #2
0
        public static void GetGraphics(ToolPath toolPath, out Graphic curveGraphic, out Graphic arrowGraphic)
        {
            IList <CurveSegment> cutterCurves;
            IList <CurveSegment> rapidCurves;
            IList <CurveSegment> arrowCurves;

            toolPath.GetCurves(out cutterCurves, out rapidCurves, out arrowCurves);

            var style = new GraphicStyle {
                LineWidth = 2
            };
            Graphic cutterGraphic = Graphic.Create(style, cutterCurves.Select(c => CurvePrimitive.Create(c)).ToArray());

            style = new GraphicStyle {
                LineWidth = 1
            };
            Graphic rapidGraphic = Graphic.Create(style, rapidCurves.Select(c => CurvePrimitive.Create(c)).ToArray());

            curveGraphic = Graphic.Create(null, null, new[] { cutterGraphic, rapidGraphic });

            style = new GraphicStyle {
                LineColor = Color.Black,
                FillColor = Color.Gray,
                //  IsFlatOn = true,
                LineWidth = 1
            };
            //arrowGraphic = Graphic.Create(style, arrowCurves.Select(c => {
            //    var point = c.StartPoint;
            //    var tangent = (c.EndPoint - c.StartPoint).Direction;
            //    var frame = Frame.Create(point, tangent);
            //    return ArrowPrimitive.Create(frame, 20, 10);
            //}).ToArray());
            arrowGraphic = null;
        }
        protected override bool OnMouseMove(ScreenPoint cursorPos, Line cursorRay, MouseButtons button)
        {
            if (button != MouseButtons.None)
            {
                return(false);
            }

            IDocObject preselection = InteractionContext.Preselection;
            DesignFace designFace   = preselection as DesignFace;

            if (designFace == null) // selection filtering is not applied if you (pre)select in the tree
            {
                return(false);
            }

            CurveSegment innerCurve, outerCurveA, outerCurveB;

            CreateThreadCurves(designFace.Shape, pitch, angle, positionOffset, out innerCurve, out outerCurveA, out outerCurveB);
            var primitives = new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurveA), CurvePrimitive.Create(outerCurveB) };

            var style = new GraphicStyle {
                LineColor = Color.DarkGray,
                LineWidth = 2
            };
            Graphic centerLine = Graphic.Create(style, primitives);

            style = new GraphicStyle {
                LineColor = Color.White,
                LineWidth = 4
            };
            Graphic highlightLine = Graphic.Create(style, primitives);

            Rendering = Graphic.Create(style, null, new[] { highlightLine, centerLine });
            return(false); // if we return true, the preselection won't update
        }
Beispiel #4
0
        private void ChangeStyleType(object sender, EventArgs e)
        {
            if (namesBox.Visible)
            {
                selection = namesBox.SelectedItem as GraphicStyle;
            }

            if (selection != null)
            {
                if (allowEvents)
                {
                    selection.StyleType = (StyleType)styleTypeBox.SelectedIndex;
                }

                switch (selection.StyleType)
                {
                case StyleType.Character:
                    spaceAfterSpinner.Enabled  = false;
                    spaceBeforeSpinner.Enabled = false;
                    spacingSpinner.Enabled     = false;
                    break;

                case StyleType.Paragraph:
                case StyleType.Heading:
                    spaceAfterSpinner.Enabled  = true;
                    spaceBeforeSpinner.Enabled = true;
                    spacingSpinner.Enabled     = true;
                    break;
                }
            }
        }
Beispiel #5
0
        public void SetGraphics()
        {
            double time = Math.Max(this.time, 0);

            time = Math.Min(time, totalTime);

            if (!TryGetLocationFromTime(time, out index, out ratio))
            {
                throw new IndexOutOfRangeException();
            }

            Point location = Interpolation.Interpolate(locations[index].Point, locations[index + 1].Point, ratio);

            Primitive toolPrimitive = toolPath.CuttingTool.GetPrimitive();
            Color     color         = toolPathObj.Color;

            color = Color.FromArgb(255 - (255 - color.R) / 2, 255 - (255 - color.G) / 2, 255 - (255 - color.B) / 2);

            GraphicStyle style = new GraphicStyle {
                EnableDepthBuffer = true,
                FillColor         = color,
                LineColor         = color
            };

            Rendering  = Graphic.Create(style, new[] { toolPrimitive }, null, Matrix.CreateMapping(toolPath.Csys) * Matrix.CreateTranslation(location.Vector));
            StatusText = string.Format(Resources.AnimationToolMesage, time, totalTime, time / totalTime * 100);
        }
Beispiel #6
0
 private void ChangeStyleListSelection(object sender, EventArgs e)
 {
     if (allowEvents && namesBox.Visible)
     {
         selection = namesBox.SelectedItem as GraphicStyle;
         ShowSelection();
     }
 }
Beispiel #7
0
        public static Graphic GetGraphic(double p, double q, double circleAngle, Vector inverseOffset)
        {
            var graphics = new List <Graphic>();

            int    bandCount = 2;
            int    iSteps = bandCount * 32; //32
            int    jSteps = 34;             //34
            double uStep = 2 * Math.PI / iSteps;
            double vStep = 2 * Math.PI / jSteps;
            bool   uSwap = false, vSwap = false;

            for (int j = 0; j < jSteps; j++)
            {
                double v = 2 * Math.PI * j / jSteps;

                for (int i = 0; i < iSteps; i++)
                {
                    double u = 2 * Math.PI * i / iSteps;

                    Direction n00, n10, n11, n01;
                    Point     p00 = Lawson.Evaluate(PointUV.Create(u, v), p, q, circleAngle, inverseOffset, true, out n00);
                    Point     p10 = Lawson.Evaluate(PointUV.Create(u + uStep, v), p, q, circleAngle, inverseOffset, true, out n10);
                    Point     p11 = Lawson.Evaluate(PointUV.Create(u + uStep, v + vStep), p, q, circleAngle, inverseOffset, true, out n11);
                    Point     p01 = Lawson.Evaluate(PointUV.Create(u, v + vStep), p, q, circleAngle, inverseOffset, true, out n01);

                    var facetVertices = new List <FacetVertex>();
                    facetVertices.Add(new FacetVertex(p00, n00));
                    facetVertices.Add(new FacetVertex(p10, n10));
                    facetVertices.Add(new FacetVertex(p11, n11));
                    facetVertices.Add(new FacetVertex(p01, n01));

                    var facets = new List <Facet>();
                    facets.Add(new Facet(0, 1, 2));
                    facets.Add(new Facet(0, 2, 3));

                    HSBColor hsbFill = new HSBColor(Window.ActiveWindow.ActiveLayer.GetColor(null));
                    hsbFill.H = (float)(u / 2 / Math.PI * 360);
                    hsbFill.A = vSwap ? 127 : 255;

                    HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                    hsbLine.H = (float)(u / 2 / Math.PI * 360);

                    var style = new GraphicStyle {
                        EnableDepthBuffer = true,
                        LineColor         = hsbLine.Color,
                        LineWidth         = 1,
                        FillColor         = hsbFill.Color
                    };

                    graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));

                    uSwap = !uSwap;
                }
                vSwap = !vSwap;
            }

            return(Graphic.Create(null, null, graphics));
        }
Beispiel #8
0
        public static Graphic GetGraphic()
        {
            var graphics = new List <Graphic>();

            int    iSteps = 64;          //32
            int    jSteps = 64;          //34
            double uStep = (double)1 / iSteps;
            double vStep = (double)2 * Math.PI / jSteps;
            bool   uSwap = false, vSwap = false;

            for (int i = 0; i < iSteps; i++)
            {
                double u = (double)i * uStep;

                for (int j = 0; j < jSteps; j++)
                {
                    double v = (double)j * vStep;

                    Direction n00, n10, n11, n01;
                    Point     p00 = BoySurface.Evaluate(Complex.CreatePolar(u, v), out n00);
                    Point     p10 = BoySurface.Evaluate(Complex.CreatePolar(u + uStep, v), out n10);
                    Point     p11 = BoySurface.Evaluate(Complex.CreatePolar(u + uStep, v + vStep), out n11);
                    Point     p01 = BoySurface.Evaluate(Complex.CreatePolar(u, v + vStep), out n01);

                    var facetVertices = new List <FacetVertex>();
                    facetVertices.Add(new FacetVertex(p00, n00));
                    facetVertices.Add(new FacetVertex(p10, n10));
                    facetVertices.Add(new FacetVertex(p11, n11));
                    facetVertices.Add(new FacetVertex(p01, n01));

                    var facets = new List <Facet>();
                    facets.Add(new Facet(0, 1, 2));
                    facets.Add(new Facet(0, 2, 3));

                    HSBColor hsbFill = new HSBColor(Window.ActiveWindow.ActiveLayer.GetColor(null));
                    hsbFill.H = (float)(u / 2 / Math.PI * 360);
                    hsbFill.A = vSwap ? 127 : 255;

                    HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                    hsbLine.H = (float)(u / 2 / Math.PI * 360);

                    var style = new GraphicStyle {
                        EnableDepthBuffer = true,
                        LineColor         = hsbLine.Color,
                        LineWidth         = 1,
                        FillColor         = hsbFill.Color
                    };

                    graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));

                    vSwap = !vSwap;
                }
                uSwap = !uSwap;
            }

            return(Graphic.Create(null, null, graphics));
        }
        //protected override void OnUpdate(Command command)
        //{

        /*
         * if (first)
         * {
         *  directory = Directory.GetCurrentDirectory();
         *  first = false;
         * }
         */
        //Window window = Window.ActiveWindow;
        //command.IsEnabled = window != null && SelectionAllBodies(window);
        //}
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            if (File.Exists(directory))
            {
                // Instance common functions class
                InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

                // Variables
                Window   window   = Window.ActiveWindow;
                Document doc      = window.Document;
                Part     rootPart = doc.MainPart;

                // Dialogue variables
                string filePath;
                double depth;

                // Get save location & tree depth via user input
                using (var dialogue = new UI.VolumeAssessorForm())
                {
                    if (dialogue.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                    var partToGraphic    = new Dictionary <Part, Graphic>();

                    var style = new GraphicStyle
                    {
                        EnableDepthBuffer = true
                    };

                    filePath = dialogue.FileName;
                    depth    = dialogue.Depth;
                }

                if (window == null)
                {
                    return;
                }

                // To pass args to python script
                var scriptParams = new Dictionary <string, object>();
                scriptParams.Add("d", depth);
                scriptParams.Add("filepath", filePath);

                // Run the script w/ args
                SpaceClaim.Api.V18.Application.RunScript(directory, scriptParams);

                // show txt output
                Process.Start(filePath);
            }
            else
            {
                MessageBox.Show("ERROR: Script not found.");
            }
        }
Beispiel #10
0
        void UpdateRendering(CancellationToken token)
        {
            if (iDesFace == null)
            {
                return;
            }

            Face    face = iDesFace.Master.Shape;
            Graphic curveGraphic, arrowGraphic;

            GetGraphics(ToolPath, out curveGraphic, out arrowGraphic);
            GraphicStyle style;

            Color transparentColor       = Color.FromArgb(44, color);
            Color selectedColor          = Color.FromArgb(transparentColor.A, transparentColor.R / 2, transparentColor.G / 2, transparentColor.B / 2);
            Color prehighlightColor      = Color.FromArgb(transparentColor.A, 255 - (255 - transparentColor.R) / 2, 255 - (255 - transparentColor.G) / 2, 255 - (255 - transparentColor.B) / 2);
            Color curveColor             = Color.FromArgb(255, selectedColor);
            Color curvePrehighlightColor = Color.FromArgb(255, prehighlightColor);

            //style = new GraphicStyle {
            //    IsPrimarySelection = true,
            //    FillColor = selectedColor
            //};
            //Graphic selected = Graphic.Create(style, null, shadedGraphic); //visible);  //TBD David fixes bug

            //style = new GraphicStyle {
            //    IsPrimarySelection = false,
            //    IsPreselection = true,
            //    FillColor = prehighlightColor
            //};
            //Graphic prehighlighted = Graphic.Create(style, null, selected);

            // curves
            style = new GraphicStyle {
                LineColor = curveColor,
                FillColor = curveColor
            };
            Graphic selectedCurves = Graphic.Create(style, null, curveGraphic);
            Graphic selectedArrows = Graphic.Create(style, null, arrowGraphic);

            style = new GraphicStyle {
                IsPreselection = true,
                LineColor      = curvePrehighlightColor,
                FillColor      = curvePrehighlightColor,
                LineWidth      = 3
            };
            Graphic prehighlightedCurves = Graphic.Create(style, null, curveGraphic);
            Graphic prehighlightedArrows = Graphic.Create(style, null, arrowGraphic);

            style = new GraphicStyle {
                EnableDepthBuffer = true,
            };

            //    Rendering = Graphic.Create(style, null, new[] { prehighlighted, prehighlightedShell, selectedShell });
            Rendering = Graphic.Create(style, null, new[] { prehighlightedCurves, selectedCurves });
        }
Beispiel #11
0
        protected override bool OnMouseMove(System.Drawing.Point cursorPos, Line cursorRay, MouseButtons button)
        {
#if false
            IDocObject preselection = InteractionContext.Preselection;
            DesignFace desFace      = null;

            Profile existingProfile = Profile.GetWrapper(preselection as CustomObject);
            if (existingProfile != null)
            {
                desFace = existingProfile.Face;
            }
            if (desFace == null)
            {
                desFace = preselection as DesignFace;
            }
            if (desFace == null)             // selection filtering is not applied if you (pre)select in the tree
            {
                return(false);
            }

            Face face  = desFace.Shape;
            var  plane = face.GetGeometry <Plane>();

            Point point;
            if (!plane.TryIntersectLine(cursorRay, out point))
            {
                return(false);                // plane is side-on
            }
            Fin    fin;
            double offset = GetOffset(face, plane, point, out fin);

            var style = new GraphicStyle
            {
                LineColor = Color.DodgerBlue,
                LineWidth = 3
            };
            Graphic datumGraphic = Graphic.Create(style, CurvePrimitive.Create(fin.Edge));

            if (existingProfile != null)
            {
                Rendering = datumGraphic;
            }
            else
            {
                style = new GraphicStyle
                {
                    LineColor = Color.Gray
                };
                Rendering = Graphic.Create(style, null, Profile.GetGraphic(0.5, 1, Math.PI / 2, Vector.Create(0.5, 0, 0)), datumGraphic);
            }
#endif

            return(false);            // if we return true, the preselection won't update
        }
        //protected override void OnUpdate(Command command)
        //{

        /*
         * if (first)
         * {
         *  directory = Directory.GetCurrentDirectory();
         *  first = false;
         * }
         */
        //Window window = Window.ActiveWindow;
        //command.IsEnabled = window != null && SelectionAllBodies(window);
        //}
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            if (File.Exists(directory))
            {
                // Instance common functions class
                InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

                // Variables
                Window   window   = Window.ActiveWindow;
                Document doc      = window.Document;
                Part     rootPart = doc.MainPart;

                // Dialogue variables
                bool planes;
                bool cut;

                // Get whether to include planes and cuts via user input
                using (var dialogue = new UI.MeshTallyCheckerForm())
                {
                    if (dialogue.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                    var partToGraphic    = new Dictionary <Part, Graphic>();

                    var style = new GraphicStyle
                    {
                        EnableDepthBuffer = true
                    };

                    planes = dialogue.Plane;
                    cut    = dialogue.Cut;
                }

                if (window == null)
                {
                    return;
                }

                // To pass args to python script
                var scriptParams = new Dictionary <string, object>();
                scriptParams.Add("planes", planes);
                scriptParams.Add("cut", cut);

                // Run the script
                SpaceClaim.Api.V18.Application.RunScript(directory, scriptParams);
            }
            else
            {
                MessageBox.Show("ERROR: Script not found.");
            }
        }
Beispiel #13
0
        //protected override void OnUpdate(Command command)
        //{

        /*
         * if (first)
         * {
         *  directory = Directory.GetCurrentDirectory();
         *  first = false;
         * }
         */
        //Window window = Window.ActiveWindow;
        //command.IsEnabled = window != null && SelectionAllBodies(window);
        //}
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            if (File.Exists(directory))
            {
                // Instance common functions class
                InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

                // Variables
                Window   window   = Window.ActiveWindow;
                Document doc      = window.Document;
                Part     rootPart = doc.MainPart;

                // Dialogue variables
                int iterations;
                int maxfaces;

                // Get iterations & max faces via user input
                using (var dialogue = new UI.VoidGeneratorForm())
                {
                    if (dialogue.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                    var partToGraphic    = new Dictionary <Part, Graphic>();

                    var style = new GraphicStyle
                    {
                        EnableDepthBuffer = true
                    };

                    iterations = dialogue.Iterations;
                    maxfaces   = dialogue.MaxFaces;
                }
                if (window == null)
                {
                    return;
                }

                // To pass args to python script
                var scriptParams = new Dictionary <string, object>();
                scriptParams.Add("iter", iterations);
                scriptParams.Add("mf", maxfaces);

                // Run the script
                SpaceClaim.Api.V18.Application.RunScript(directory, scriptParams);
                MessageBox.Show("Script called successfully");
            }
            else
            {
                MessageBox.Show("ERROR: Script not found.");
            }
        }
        void UpdateRendering(CancellationToken token)
        {
            Body         body    = desFace.Shape.Body;
            Graphic      nucleus = GetGraphics(positions, radius);
            Graphic      shell   = GetGraphics(positions, IdealRadius);
            GraphicStyle style;
            int          shellAlpha = 22;

            Color selectedColor          = Color.FromArgb(color.R / 2, color.G / 2, color.B / 2);
            Color prehighlightColor      = Color.FromArgb(255 - (255 - color.R) / 2, 255 - (255 - color.G) / 2, 255 - (255 - color.B) / 2);
            Color shellColor             = Color.FromArgb(shellAlpha, selectedColor);
            Color shellPrehighlightColor = Color.FromArgb(shellAlpha, prehighlightColor);

            // nucleus
            style = new GraphicStyle {
                IsPrimarySelection = false,
                IsPreselection     = false,
                FillColor          = color
            };
            Graphic visible = Graphic.Create(style, null, nucleus);

            style = new GraphicStyle {
                IsPrimarySelection = true,
                FillColor          = selectedColor
            };
            Graphic selected = Graphic.Create(style, null, visible);

            style = new GraphicStyle {
                IsPreselection     = true,
                IsPrimarySelection = false,
                FillColor          = prehighlightColor
            };
            Graphic prehighlighted = Graphic.Create(style, null, selected);

            // shell
            style = new GraphicStyle {
                IsPrimarySelection = true,
                FillColor          = shellColor
            };
            Graphic selectedShell = Graphic.Create(style, null, shell);

            style = new GraphicStyle {
                IsPreselection     = true,
                IsPrimarySelection = false,
                FillColor          = shellPrehighlightColor
            };
            Graphic prehighlightedShell = Graphic.Create(style, null, selectedShell);

            style = new GraphicStyle {
                EnableDepthBuffer = true
            };

            Rendering = Graphic.Create(style, null, new[] { prehighlighted, prehighlightedShell });
        }
Beispiel #15
0
        void UpdateRendering()
        {
            Graphic shape = Graphic.Create(null, null, GetGraphics(iDesignFace, pointUV, span, position, HandleType));

            GraphicStyle style;

            Graphic halo;             // for prehighlighting

            {
                // show halo when preselected
                style = new GraphicStyle {
                    IsPreselection = true,
                    IsVisible      = true
                };
                Graphic haloWhenPreselected = Graphic.Create(style, null, shape);

                // when selected make the halo width 7 instead of 5
                style = new GraphicStyle {
                    IsPrimarySelection = true,
                    LineWidth          = 7
                };
                Graphic haloWhenSelected = Graphic.Create(style, null, haloWhenPreselected);

                // set halo color and width, but do not show
                style = new GraphicStyle {
                    IsVisible = false,
                    LineColor = Color.Pink,
                    LineWidth = 5
                };
                halo = Graphic.Create(style, null, haloWhenSelected);
            }

            // when selected make the width 3
            style = new GraphicStyle {
                IsPrimarySelection = true,
                LineWidth          = 3
            };
            Graphic whenSelected = Graphic.Create(style, null, shape);

            // set regular width and color
            style = new GraphicStyle {
                LineWidth = 1,
                LineColor = Color.Red,
                FillColor = Color.WhiteSmoke
            };
            Graphic root = Graphic.Create(style, null, halo, whenSelected);

            Rendering = root;
        }
Beispiel #16
0
        /// <summary>
        /// Create a dialog to edit multiple styles; this is for editing existing styles.
        /// </summary>
        /// <param name="styles"></param>

        public StyleDialog(List <Style> styles, Color pageColor)
        {
            Initialize();

            Text        = Resx.StyleDialog_Text;
            allowEvents = false;
            LoadStyles(styles);

            if (styles.Count > 0)
            {
                selection = new GraphicStyle(styles[0], false);
            }

            this.pageColor = pageColor;
        }
        private static Graphic BlendGraphics(Color color, Graphic nucleus, Graphic shell, double shellAlpha)
        {
            GraphicStyle style;

            style = new GraphicStyle {
                FillColor = color
            };
            Graphic selectedNucleus = Graphic.Create(style, null, nucleus);

            style = new GraphicStyle {
                FillColor = Color.FromArgb(22, color)
            };
            Graphic selectedShell = Graphic.Create(style, null, shell);

            return(Graphic.Create(null, null, new[] { selectedNucleus, selectedShell }));
        }
        protected override bool OnMouseMove(ScreenPoint cursorPos, Line cursorRay, MouseButtons button)
        {
            if (button != MouseButtons.None)
            {
                return(false);
            }

            IDocObject preselection = InteractionContext.Preselection;
            DesignFace desFace      = null;

            SphereSet existingSphereSet = SphereSet.GetWrapper(preselection as CustomObject);

            if (existingSphereSet != null)
            {
                desFace = existingSphereSet.DesFace;
            }
            if (desFace == null)
            {
                desFace = preselection as DesignFace;
            }
            if (desFace == null) // selection filtering is not applied if you (pre)select in the tree
            {
                return(false);
            }

            if (SphereSet.AllSphereSets.Where(s => s.DesFace == desFace).Count() > 0)
            {
                return(false);
            }

            Body body = desFace.Shape.Body;

            GraphicStyle style = null;

            if (existingSphereSet == null)
            {
                style = new GraphicStyle {
                    EnableDepthBuffer = true,
                    FillColor         = color
                };

                Rendering = Graphic.Create(style, null, SphereSet.GetGraphics(SphereSet.GetInitialPositions(body, count, true), radius));
            }

            return(false); // if we return true, the preselection won't update
        }
Beispiel #19
0
        /// <summary>
        /// Create a dialog to edit a single style; this is for creating new styles
        /// </summary>
        /// <param name="style"></param>

        public StyleDialog(Style style, Color pageColor)
        {
            Initialize();
            Logger.SetDesignMode(DesignMode);

            allowEvents    = false;
            this.pageColor = pageColor;

            Text = Resx.StyleDialog_NewText;
            mainTools.Visible      = false;
            loadButton.Enabled     = false;
            saveButton.Enabled     = false;
            newStyleButton.Enabled = false;
            reorderButton.Enabled  = false;
            deleteButton.Enabled   = false;

            selection = new GraphicStyle(style, false);
        }
Beispiel #20
0
        /// <summary>
        /// Create a dialog to edit multiple styles; this is for editing existing styles.
        /// </summary>
        /// <param name="styles"></param>

        public StyleDialog(Theme theme, Color pageColor)
        {
            Initialize();

            allowEvents = false;

            var styles = theme.GetStyles();

            LoadStyles(styles);

            if (styles.Count > 0)
            {
                selection = new GraphicStyle(styles[0], false);
            }

            this.pageColor = pageColor;

            Text       = string.Format(Resx.StyleDialog_ThemeText, theme.Name);
            this.theme = theme;
        }
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            Window            window     = Window.ActiveWindow;
            var               allBodies  = new List <IDesignBody>();
            Document          doc        = window.Document;
            Part              rootPart   = doc.MainPart;
            Part              pipesPart  = Part.Create(doc, "Simplified Pipes");
            Part              brokenPipe = Part.Create(doc, "Broken Pipe");
            int               i;
            List <DesignBody> allDesignBodies    = new List <DesignBody>();
            List <DesignBody> brokenDesignBodies = new List <DesignBody>();
            List <double>     radii = new List <double>();
            List <Color>      chosen_colour;
            Component         brokenComponent = Component.Create(rootPart, brokenPipe);


            //Selects the active window to work on and work on the solid bodies
            window.InteractionMode = InteractionMode.Solid;

            // -----------------------------------------------------------------
            // Get the selected IDesign bodies
            // -----------------------------------------------------------------
            var desBodies = window.ActiveContext.Selection;

            if (desBodies == null)
            {
                Debug.Fail("Unexpected case.", "Selection was not a single design body.");
                return;
            }


            // --------------------------------------------------------------
            // Open up an output file inorder to write out for testing
            // --------------------------------------------------------------
            //string outputfile = "H:/test_pipe_v2.txt";
            //using (StreamWriter sw = File.CreateText(outputfile))
            //{
            //    sw.WriteLine("OutputFile");
            //}

            //-----------------------------------------------------------------
            // Get User defined requirement from dialogue box
            //-----------------------------------------------------------------
            #region Dialogue Information
            using (var dialogue = new PipeRadiusOptions())
            {
                if (dialogue.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                var partToGraphic    = new Dictionary <Part, Graphic>();

                var style = new GraphicStyle
                {
                    EnableDepthBuffer = true
                };

                if (dialogue.standardpipe)
                {
                    Dictionary <string, List <double> > standard_pipes = StandardPipeDia.getStandardPipeDia();
                    radii     = standard_pipes[dialogue.get_standard_dia + dialogue.get_schedule_num];
                    pipesPart = Part.Create(doc, "Simplified Pipes DN" + dialogue.get_standard_dia + "/" + dialogue.get_schedule_num);
                }
                else if (dialogue.userdefined)
                {
                    radii.Add((double)dialogue.outRadius / 100.0);

                    if (dialogue.hollow)
                    {
                        radii.Add((double)dialogue.inRadius / 100.0);
                        pipesPart = Part.Create(doc, "Simplified Pipes OD=" + dialogue.outRadius.ToString() + " - ID=" + dialogue.inRadius.ToString() + " cm");
                    }
                    else
                    {
                        pipesPart = Part.Create(doc, "Simplified Pipes OD=" + dialogue.outRadius.ToString() + " cm");
                    }
                }
                else
                {
                    pipesPart = Part.Create(doc, "Simplified Pipes");
                }

                chosen_colour = process_colour(dialogue.get_colour);
            }
            #endregion
            Component newComponent = Component.Create(rootPart, pipesPart);


            // --------------------------------------------------------------------
            //
            // --------------------------------------------------------------------
            foreach (IDesignBody desBody in desBodies)
            {
                //try to simplify
                try
                {
                    DesignBody desBodyMaster = desBody.Master;
                    Body       currentBody   = desBodyMaster.Shape;

                    List <SpaceClaim.Api.V18.Geometry.Point> pointsList = new List <SpaceClaim.Api.V18.Geometry.Point>();
                    List <Circle> circleList = new List <Circle>();
                    List <Face>   faceList   = new List <Face>();
                    List <Plane>  planeList  = new List <Plane>();

                    //Find the end planes of the pipe
                    List <Face> endFaces = findendFaces(currentBody);

                    //                    foreach (Face endFace in endFaces)
                    //                    {
                    //                        DatumPlane newPlane = DatumPlane.Create(rootPart, "end Plane", endFace.GetGeometry<Plane>());
                    //                        FileWriter(outputfile, "plane");
                    //                    }

                    // ---------------------------------------------------------------
                    // If no user defined radii are given work out inner (if present)
                    //  and outer radii of the pipe
                    // ---------------------------------------------------------------
                    try
                    {
                        // If we are just using the pipe radii
                        if (!radii.Any())
                        {
                            radii = findRadii(endFaces.First());
                        }
                    }
                    catch
                    {
                        #region Dialogue Information
                        using (var dialogue = new Pipes_Radius())
                        {
                            if (dialogue.ShowDialog() != DialogResult.OK)
                            {
                                return;
                            }

                            var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                            var partToGraphic    = new Dictionary <Part, Graphic>();

                            var style = new GraphicStyle
                            {
                                EnableDepthBuffer = true
                            };

                            radii.Add((double)dialogue.outRadius);

                            if (dialogue.hollow)
                            {
                                radii.Add((double)dialogue.inRadius);
                            }
                        }
                        #endregion
                        //                        FileWriter(outputfile, "Unable to find radii ");
                    }


                    //Start from the first end face in list and work along recording faces, circles and points
                    findcircles(endFaces.First(), endFaces.Last(), out pointsList, out circleList, out faceList);

                    //FileWriter(outputfile, "number of points");
                    //FileWriter(outputfile, "Number of points "+pointsList.Count().ToString());

//                    foreach (Point point in pointsList)
//                    {
//                        DatumPoint newPoint = DatumPoint.Create(rootPart, "Point", point);
//                    }

                    //For each toriodal face in the pipe create a new "inter" plane which can be used to cut the new cylindrical bodies
                    //This also moves each of the points found at the end of the cylinders to a new position
                    for (i = 0; i < faceList.Count; i++)
                    {
                        if (faceList[i].GetGeometry <Torus>() != null)
                        {
                            Plane firstplane;
                            Plane secondplane;
                            bool  isreversedfirst;
                            bool  isreversedsecond;
                            int   round = 2;
                            if (i == 0)
                            {
                                //FileWriter(outputfile, "Got Here --");

                                //Create a plane on one side of the tori from the circle and work out if the dirZ is reversed or not
                                firstplane      = endFaces.First().GetGeometry <Plane>();
                                isreversedfirst = endFaces.First().IsReversed;
                                //DatumPlane newPlane = DatumPlane.Create(rootPart, "first Plane", firstplane);

                                //Create a plane on the other side of the tori from the circle and work out if the dirZ is reversed or not
                                Vector directionCylsecond;
                                secondplane = createPlane(circleList[i + 1], pointsList[i + 1], pointsList[i + 2], round, out isreversedsecond, out directionCylsecond);

                                //Move the cylinder points by the torus radius inorder to draw over the torus
                                pointsList[i + 1] = pointsList[i + 1] + directionCylsecond.Direction.UnitVector * (faceList[i].GetGeometry <Torus>().MajorRadius + faceList[i].GetGeometry <Torus>().MinorRadius + 0.1);
                            }
                            else if (i == faceList.Count)
                            {
                                //FileWriter(outputfile, "Got Here \\");
                                //Create a plane on one side of the tori from the circle and work out if the dirZ is reversed or not
                                Vector directionCylfirst;
                                firstplane = createPlane(circleList[i], pointsList[i], pointsList[i - 1], round, out isreversedfirst, out directionCylfirst);

                                //Create a plane on the other side of the tori from the circle and work out if the dirZ is reversed or not
                                secondplane      = endFaces.Last().GetGeometry <Plane>();
                                isreversedsecond = endFaces.Last().IsReversed;

                                //Move the cylinder points by the torus radius inorder to draw over the torus
                                pointsList[i] = pointsList[i] + directionCylfirst.Direction.UnitVector * (faceList[i].GetGeometry <Torus>().MajorRadius + faceList[i].GetGeometry <Torus>().MinorRadius + 0.1);
                            }
                            else
                            {
                                //Create a plane on one side of the tori from the circle and work out if the dirZ is reversed or not
                                Vector directionCylfirst;
                                firstplane = createPlane(circleList[i], pointsList[i], pointsList[i - 1], round, out isreversedfirst, out directionCylfirst);

                                //Create a plane on the other side of the tori from the circle and work out if the dirZ is reversed or not
                                Vector directionCylsecond;
                                secondplane = createPlane(circleList[i + 1], pointsList[i + 1], pointsList[i + 2], round, out isreversedsecond, out directionCylsecond);

                                //Move the cylinder points by the torus radius inorder to draw over the torus
                                pointsList[i]     = pointsList[i] + directionCylfirst.Direction.UnitVector * (faceList[i].GetGeometry <Torus>().MajorRadius + faceList[i].GetGeometry <Torus>().MinorRadius + 0.1);
                                pointsList[i + 1] = pointsList[i + 1] + directionCylsecond.Direction.UnitVector * (faceList[i].GetGeometry <Torus>().MajorRadius + faceList[i].GetGeometry <Torus>().MinorRadius + 0.1);
                            }
                            double   angle = 0;
                            Vector3D unitvector;
                            SpaceClaim.Api.V18.Geometry.Point pointonintesect;
                            Plane interPlane = CreateInterPlane(firstplane, secondplane, isreversedfirst, isreversedsecond, out angle, out unitvector, out pointonintesect);
                            planeList.Add(interPlane);
                        }
                        else
                        {
                            planeList.Add(null);
                        }
                    }

                    //foreach (Point point in pointsList)
                    //{
                    //    DatumPoint newPoint = DatumPoint.Create(rootPart, "Point", point);
                    //}

                    //Draw out the new cylinders for each radii
                    //Loop over each of the faces
                    for (i = 0; i < faceList.Count(); i++)
                    {
                        //if the face is not a torus or it is the first or last face we need to draw it out
                        if (faceList[i].GetGeometry <Torus>() == null || i == 0 || i == faceList.Count() - 1)
                        {
                            //List of the bodies for each cylinder (maybe an inner and outer cylinder
                            List <Body> keepBodies = new List <Body>();

                            //for each of the pipe radii we will draw out a cylinder and split it on the relevant planes
                            foreach (Double pipeRadius in radii)
                            {
                                //Create cylinder
                                Body keepBody = createCylinder(faceList[i], endFaces.First(), endFaces.Last(), pipeRadius, i, faceList.Count(), pointsList[i + 1], pointsList[i]);

                                //keepBody = newBody;

                                //split cylinder on one of the relevant planes
                                if (i > 0 && planeList[i - 1] != null)
                                {
                                    keepBody = splitcylinder(keepBody, planeList[i - 1], circleList[i].Frame.Origin);
                                }

                                //Perform only if there is a torus at either end of the pipe
                                if ((i == 0 || i == faceList.Count() - 1) && faceList[i].GetGeometry <Torus>() != null)
                                {
                                    if (i == 0)
                                    {
                                        keepBody = splitcylinder(keepBody, planeList[i], circleList[i].Frame.Origin);
                                    }
                                    if (i == faceList.Count() - 1)
                                    {
                                        keepBody = splitcylinder(keepBody, planeList[i], circleList[i + 1].Frame.Origin);
                                    }
                                }

                                //split cylinder on second of the relevant planes
                                if (i < planeList.Count - 1 && planeList[i + 1] != null)
                                {
                                    keepBody = splitcylinder(keepBody, planeList[i + 1], circleList[i + 1].Frame.Origin);
                                }
                                keepBodies.Add(keepBody);
                            }

                            //transform the body back to its original position (if in a component)
                            Matrix reverseTrans = desBody.TransformToMaster.Inverse;

                            //FileWriter(outputfile, "Loop " + i + " of " + (faceList.Count() - 1).ToString());
                            //Draw out bodies
                            allDesignBodies.AddRange(drawnbodies(keepBodies, reverseTrans, pipesPart, chosen_colour));
                        }
                    }
                }

                //catch if we cannot simplify the pipe
                catch
                {
                    Body   brokenBody   = desBody.Master.Shape.Copy();
                    Matrix reverseTrans = desBody.TransformToMaster.Inverse;
                    brokenBody.Transform(reverseTrans);
                    brokenDesignBodies.Add(DesignBody.Create(brokenPipe, "Broken Pipe", brokenBody));
                }
            }

            var allbodies = pipesPart.Bodies;
            //FileWriter(outputfile, "Number of Bodies in part: " + allbodies.Count);
        }
Beispiel #22
0
        public static ICollection <Graphic> GetGraphics(IDesignFace iDesignFace, PointUV pointUV, double span, double position, HandleTypeEnum handleType)
        {
            Debug.Assert(iDesignFace != null);

            Window activeWindow = Window.ActiveWindow;
            var    graphics     = new List <Graphic>();

            var primitives = new List <Primitive>();

            SurfaceEvaluation eval   = iDesignFace.Shape.Geometry.Evaluate(pointUV);
            Point             point  = eval.Point;
            Direction         normal = eval.Normal;

            double pixelSize      = activeWindow.ActiveContext.GetPixelSize(point);
            double shaftDiameter  = 4 * pixelSize;
            double handleDiameter = 8 * pixelSize;
            double handleHeight   = 4 * pixelSize;

            Point  startPoint          = point - (normal * (span * (position + 1) / 2 - handleHeight));
            Point  endPoint            = startPoint + normal * (span + 2 * handleHeight);
            Vector handleHalfThickness = normal * handleHeight / 2;

            bool isDrawingAll = handleType == HandleTypeEnum.All;
            var  mesh         = new List <Primitive>();
            var  style        = new GraphicStyle
            {
                EnableDepthBuffer = true,
                LineColor         = Color.DimGray,
                LineWidth         = 1,
                FillColor         = Color.DimGray
            };

            switch (handleType)
            {
            case HandleTypeEnum.All:
            case HandleTypeEnum.Shaft:
                mesh.AddRange(ShapeHelper.CreateCylinderMesh(startPoint, endPoint, shaftDiameter, 8));
                graphics.Add(Graphic.Create(style, mesh));

                if (isDrawingAll)
                {
                    goto case HandleTypeEnum.Base;
                }
                else
                {
                    break;
                }

            case HandleTypeEnum.Base:
                mesh.AddRange(ShapeHelper.CreateCylinderMesh(point - handleHalfThickness, point + handleHalfThickness, handleDiameter, 12));
                style.LineColor = Color.DodgerBlue;
                style.FillColor = Color.DodgerBlue;
                graphics.Add(Graphic.Create(style, mesh));

                if (isDrawingAll)
                {
                    goto case HandleTypeEnum.Start;
                }
                else
                {
                    break;
                }

            case HandleTypeEnum.Start:
                mesh.AddRange(ShapeHelper.CreateCylinderMesh(startPoint - handleHalfThickness, startPoint + handleHalfThickness, handleDiameter, 12));
                style.LineColor = Color.DarkViolet;
                style.FillColor = Color.DarkViolet;
                graphics.Add(Graphic.Create(style, mesh));

                if (isDrawingAll)
                {
                    goto case HandleTypeEnum.End;
                }
                else
                {
                    break;
                }

            case HandleTypeEnum.End:
                mesh.AddRange(ShapeHelper.CreateCylinderMesh(endPoint - handleHalfThickness, endPoint + handleHalfThickness, handleDiameter, 12));
                style.LineColor = Color.DarkViolet;
                style.FillColor = Color.DarkViolet;
                graphics.Add(Graphic.Create(style, mesh));

                break;
            }

            return(graphics);
        }
Beispiel #23
0
        //protected override void OnUpdate(Command command)
        //{

        /*
         * if (first)
         * {
         *  directory = Directory.GetCurrentDirectory();
         *  first = false;
         * }
         */
        //Window window = Window.ActiveWindow;
        //command.IsEnabled = window != null && SelectionAllBodies(window);
        //}
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            if (File.Exists(directory))
            {
                // Instance common functions class
                InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

                // Variables
                Window   window   = Window.ActiveWindow;
                Document doc      = window.Document;
                Part     rootPart = doc.MainPart;

                int meshes = 0;
                foreach (IPart part in WalkParts(rootPart))
                {
                    Part partMaster = part.Master;
                    if (GetPartName(partMaster).Equals("MESH"))
                    {
                        meshes = part.Bodies.Count;
                    }
                }

                // Dialogue variables
                string filePath;

                // mesh tally save location user input
                using (var dialogue = new SaveFileDialog())
                {
                    dialogue.FileName        = "meshcard.txt";
                    dialogue.DefaultExt      = "txt";
                    dialogue.Filter          = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    dialogue.FilterIndex     = 2;
                    dialogue.OverwritePrompt = true;

                    if (dialogue.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                    var partToGraphic    = new Dictionary <Part, Graphic>();

                    var style = new GraphicStyle
                    {
                        EnableDepthBuffer = true
                    };

                    filePath = dialogue.FileName;
                }

                var    scriptParams = new Dictionary <string, object>();
                string particleType = "n";
                int    tallyNum     = 14;
                double xRes         = 1.0;
                double yRes         = 1.0;
                double zRes         = 1.0;
                int    i            = 0;

                // get mesh properties via user input
                while (i < meshes)
                {
                    using (var dialogue = new UI.MeshTallyWriterForm2())
                    {
                        if (dialogue.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }

                        var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                        var partToGraphic    = new Dictionary <Part, Graphic>();

                        var style = new GraphicStyle
                        {
                            EnableDepthBuffer = true
                        };

                        particleType = dialogue.ParticleSelection;
                        tallyNum     = dialogue.TallyNumber;
                        xRes         = dialogue.XResolution;
                        yRes         = dialogue.YResolution;
                        zRes         = dialogue.ZResolution;

                        scriptParams.Add("tallynum" + i.ToString(), tallyNum);
                        scriptParams.Add("particle" + i.ToString(), particleType);
                        scriptParams.Add("xres" + i.ToString(), xRes);
                        scriptParams.Add("yres" + i.ToString(), yRes);
                        scriptParams.Add("zres" + i.ToString(), zRes);

                        i++;
                    }
                }

                if (window == null)
                {
                    return;
                }

                scriptParams.Add("filepath", filePath);
                scriptParams.Add("meshquant", meshes);

                // Run the script w/ args
                SpaceClaim.Api.V18.Application.RunScript(directory, scriptParams);
            }
            else
            {
                MessageBox.Show("ERROR: Script not found.");
            }
        }
        //private Point GetFivePointNurbsAverage(int[,] indices) {
        //    var knots = new Knot[] {
        //                new Knot(0, 4),
        //                new Knot(1, 4)
        //            };
        //    var controlPoints = new ControlPoint[] {
        //                new ControlPoint(Point.Create(tabAngles[indices[0,0]][indices[0,1]], GetSpanAt(indices[0,0], indices[0,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[1,0]][indices[1,1]], GetSpanAt(indices[1,0], indices[1,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[2,0]][indices[2,1]], GetSpanAt(indices[2,0], indices[2,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[3,0]][indices[3,1]], GetSpanAt(indices[3,0], indices[3,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[4,0]][indices[4,1]], GetSpanAt(indices[4,0], indices[4,1]),0), 1)
        //            };
        //    NurbsData data = new NurbsData(5, false, false, knots);
        //    NurbsCurve curve = NurbsCurve.CreateFromControlPoints(data, controlPoints);
        //    Point midpoint = curve.Evaluate(0.5).Point;
        //    return midpoint;
        //}
        //private Circle GetTabFromPoints(bool swap, int i, int j, int iOther) {
        //    Point p0 = points[i,j];
        //    Point p1 = points[i,j + 1];
        //    Point pn = (new Point[] { points[iOther,j], points[iOther,j + 1] }).Average();
        //    Direction normal = Vector.Cross(p0 - pn, p1 - pn).Direction;
        //    return Tabs.GetCircularTabCircle(p0, p1, normal, tabAngles[i,j], swap);
        //}
        //private double GetSpanAt(int i, int j) {
        //    return (vParameters[i][j + 1] - vParameters[i][j] + Math.PI * 2) % (Math.PI * 2);
        //}
        public Graphic GetGraphic()
        {
            var graphics = new List<Graphic>();

            int iSteps = points.GetLength(0);
            int jSteps = points.GetLength(1);

            bool swap = false;
            for (int i = 0; i < iSteps - 1; i++) {
                var facetVertices = new List<FacetVertex>();
                var facets = new List<Facet>();
                var tabMeshes = new List<MeshPrimitive>();
                var porcupineCurves = new List<CurvePrimitive>();
                for (int j = 0; j < jSteps - 1; j++) {
                    int facetOffset = facetVertices.Count;
                    // Main ring
                    Point p00 = points[i, j];
                    Point p01 = points[i, j + 1];
                    Point p10 = points[i + 1, j];
                    Point p11 = points[i + 1, j + 1];

                    Vector n0 = Vector.Cross(p00 - p01, p00 - p10);
                    Vector n1 = Vector.Cross(p11 - p10, p11 - p01);
                    Direction n = (n0 + n1).Direction;

                    facetVertices.Add(new FacetVertex(p00, n));
                    facetVertices.Add(new FacetVertex(p01, n));
                    facetVertices.Add(new FacetVertex(p10, n));
                    facetVertices.Add(new FacetVertex(p11, n));

                    if ((p00 - p11).Magnitude < (p10 - p01).Magnitude) {
                        facets.Add(new Facet(0 + facetOffset, 1 + facetOffset, 3 + facetOffset));
                        facets.Add(new Facet(0 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    }
                    else {
                        facets.Add(new Facet(0 + facetOffset, 2 + facetOffset, 1 + facetOffset));
                        facets.Add(new Facet(1 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    }

                    tabMeshes.Add(MeshPrimitive.Create(facetVertices, facets));

                    Point basePoint = points[i, j];
                    Point endPoint = basePoint + Gradient(basePoint) / 10;
                    if (basePoint != endPoint)
                        porcupineCurves.Add(CurvePrimitive.Create(CurveSegment.Create(basePoint, endPoint)));

                    swap = !swap;
                }

                HSBColor hsbFill = new HSBColor(255, (float) i / iSteps * 360, 122, 88);
                HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                hsbLine.H = (float) i / iSteps * 360;

                var style = new GraphicStyle {
                    EnableDepthBuffer = true,
                    LineColor = hsbLine.Color,
                    LineWidth = 1,
                    FillColor = hsbFill.Color,

                    EnableCulling = false
                };

                //		graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));
                foreach (MeshPrimitive mesh in tabMeshes)
                    graphics.Add(Graphic.Create(style, mesh));

                foreach (CurvePrimitive curve in porcupineCurves)
                    graphics.Add(Graphic.Create(style, curve));

            }

            return Graphic.Create(null, null, graphics);
        }
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            /*
             * Lost Particle Location Highlighter
             * Prompt user to select the MCNP output file which contains lost particle locations
             * Read in file and store locations
             * Highlight the point/plane which the particle loss occurs
             */

            // Instance common functions class
            InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

            // Variables
            Window window = Window.ActiveWindow;

            window.SetTool(new ToolClass());
            Document doc        = window.Document;
            Part     rootPart   = doc.MainPart;
            Part     lostPart   = Part.Create(doc, "Lost Particles");
            Part     vectorPart = Part.Create(doc, "Vector Lines");
            Part     curvePart  = Part.Create(doc, "Lost Particle Curves");

            Component lp2c = Component.Create(rootPart, curvePart);

            string filepath;
            bool   showVectors;
            bool   fileLocated = false;
            bool   maxParticlesBool;
            double maxParicles;

            int  particleCounter     = 0;
            int  particleLineCounter = 0;
            bool stopParticles       = false;
            bool stopLines           = false;

            string[] lines = null;

            string lostParticleIndicator = "x,y,z coordinates:";
            string vectorIndicator       = "u,v,w direction cosines:";

            char[] delimeterChars   = { ' ', '\t' };
            char[] secondDelimChars = { '+', '-' };

            int    pointCounter = 1;
            int    lineCounter  = 1;
            string pointName;
            string vectorName;
            string chosenColour;

            Point currentPoint = Point.Create(0, 0, 0);
            Point vectorPoint  = Point.Create(0, 0, 0);

            List <double> xValues         = new List <double>();
            List <double> yValues         = new List <double>();
            List <double> zValues         = new List <double>();
            List <Point>  vectorPointList = new List <Point>();
            List <Point>  pointList       = new List <Point>();
            List <Line>   lineList        = new List <Line>();

            // Bring up windows form

            using (var dialogue = new UI.LostParticlesForm())
            {
                if (dialogue.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                var partToGraphic    = new Dictionary <Part, Graphic>();

                var style = new GraphicStyle
                {
                    EnableDepthBuffer = true
                };

                filepath         = dialogue.FileName;
                showVectors      = dialogue.ShowVectors;
                maxParticlesBool = dialogue.MaxParticleBool;
                maxParicles      = dialogue.MaxParticle;
                chosenColour     = dialogue.ColourSelection;
            }

            if (window == null)
            {
                return;
            }

            //Debug.WriteLine(filepath);

            try
            {
                lines       = File.ReadAllLines(filepath);
                fileLocated = true;
            }
            catch
            {
                MessageBox.Show("File Could Not Be Located");
                //SpaceClaim.Api.V18.Application.Exit();
            }

            // Get x,y,z coordinates of lost particle points
            //-------------------------------------------------------------

            if (fileLocated)
            {
                // Check if MCNP output or text file
                if (lines[0].Contains("Code Name & Version") || lines[0].Contains(lostParticleIndicator) || lines[0].Contains(vectorIndicator))
                {
                    //Debug.WriteLine("MCNP File");
                    // MCNP File
                    foreach (string line in lines)
                    {
                        if (line.Contains(lostParticleIndicator))
                        {
                            //Debug.WriteLine(line);
                            if (!stopParticles)
                            {
                                string[] tempWords = line.Split(delimeterChars, StringSplitOptions.RemoveEmptyEntries);

                                // Convert API values in metres to cm for SpaceClaim
                                currentPoint = Point.Create(Convert.ToDouble(tempWords[2]) / 100, Convert.ToDouble(tempWords[3]) / 100, Convert.ToDouble(tempWords[4]) / 100);
                                pointList.Add(currentPoint);

                                particleCounter++;

                                if (particleCounter >= maxParicles && maxParticlesBool)
                                {
                                    stopParticles = true;
                                }
                            }
                        }

                        else if (line.Contains(vectorIndicator))
                        {
                            string[] tempWords = line.Split(delimeterChars, StringSplitOptions.RemoveEmptyEntries);

                            //Debug.WriteLine(tempWords[3] + "  " + tempWords[4] + "  " + tempWords[5]);

                            Point     origin    = Point.Create(0, 0, 0);
                            Direction direction = Direction.Create(Convert.ToDouble(tempWords[3]), Convert.ToDouble(tempWords[4]), Convert.ToDouble(tempWords[5]));
                            vectorPoint = Point.Create(currentPoint.X + Convert.ToDouble(tempWords[3]) / 1, currentPoint.Y + Convert.ToDouble(tempWords[4]) / 1, currentPoint.Z + Convert.ToDouble(tempWords[5]) / 1);

                            if (showVectors && !stopLines)
                            {
                                vectorName = "Lost Particle " + lineCounter.ToString() + " Vector";
                                LineSegment   lineSeg  = new LineSegment(currentPoint, vectorPoint);
                                ITrimmedCurve shape    = CurveSegment.Create(lineSeg);
                                DesignCurve   desCurve = DesignCurve.Create(vectorPart, shape);
                                desCurve.Name = vectorName;
                                desCurve.SetColor(null, Color.Blue);
                                lineCounter++;
                                particleLineCounter++;

                                if (particleLineCounter >= maxParicles && maxParticlesBool)
                                {
                                    stopLines = true;
                                }
                            }

                            //Line vectorLine = Line.CreateThroughPoints(currentPoint, origin);
                            Line vectorLine = Line.CreateThroughPoints(currentPoint, vectorPoint);



                            //Line vectorLine = Line.Create(currentPoint, direction);
                            lineList.Add(vectorLine);
                        }

                        #region Old Code

                        /*
                         * else if (lostParticleBool)
                         * {
                         *
                         *  if (line.Contains(endLostParticleIndicator))
                         *  {
                         *      //string patternOne = @"(\-|\d)\d*\.\d+";
                         *      string patternOne = @"(?<=\d)(\+|\-)";
                         *      string[] tempWords = prevLine.Split(delimeterChars, StringSplitOptions.RemoveEmptyEntries);
                         *      string[] xWords = Regex.Split(tempWords[2], patternOne);
                         *      string[] yWords = Regex.Split(tempWords[3], patternOne);
                         *      string[] zWords = Regex.Split(tempWords[4], patternOne);
                         *      //Debug.WriteLine(xWords[0]);
                         *      //Debug.WriteLine(yWords[0]);
                         *
                         *      string xFinal = xWords[0] + "E" + xWords[1] + xWords[2];
                         *      string yFinal = yWords[0] + "E" + yWords[1] + yWords[2];
                         *      string zFinal = zWords[0] + "E" + zWords[1] + zWords[2];
                         *
                         *      Debug.WriteLine(xFinal);
                         *      Debug.WriteLine(yFinal);
                         *      Debug.WriteLine(zFinal);
                         *
                         *      /*
                         *      foreach (string word in xWords)
                         *      {
                         *          Debug.WriteLine(word);
                         *      }
                         *
                         *      Debug.WriteLine(" ");
                         *
                         *      foreach (string word in yWords)
                         *      {
                         *          Debug.WriteLine(word);
                         *      }
                         *
                         *
                         *      xValues.Add(Convert.ToDouble(xFinal));
                         *      yValues.Add(Convert.ToDouble(yFinal));
                         *      zValues.Add(Convert.ToDouble(zFinal));
                         *
                         *  }
                         *
                         * //prevLine = line;
                         * }
                         */

                        #endregion
                    }

                    //Debug.WriteLine(pointList.Count);

                    // Use values and highlight the positions in SpaceClaim
                    //---------------------------------------------------------------
                    foreach (Point point in pointList)
                    {
                        pointName = "Lost Particle " + pointCounter.ToString();
                        window.ActiveTool.CreateIndicator(point);
                        //DatumPoint.Create(lostPart, pointName, point);
                        var           pc     = PointCurve.Create(point);
                        ITrimmedCurve shapey = CurveSegment.Create(pc);
                        DesignCurve   dcurve = DesignCurve.Create(curvePart, shapey);
                        if (chosenColour == "Blue")
                        {
                            dcurve.SetColor(null, Color.Blue);
                        }
                        else if (chosenColour == "Red")
                        {
                            dcurve.SetColor(null, Color.Red);
                        }
                        else if (chosenColour == "Green")
                        {
                            dcurve.SetColor(null, Color.Green);
                        }
                        else if (chosenColour == "Orange")
                        {
                            dcurve.SetColor(null, Color.Orange);
                        }
                        else if (chosenColour == "Black")
                        {
                            dcurve.SetColor(null, Color.Black);
                        }
                        else if (chosenColour == "Yellow")
                        {
                            dcurve.SetColor(null, Color.Yellow);
                        }
                        else if (chosenColour == "Salmon Pink")
                        {
                            dcurve.SetColor(null, Color.Salmon);
                        }
                        pointCounter++;
                    }


                    if (showVectors)
                    {
                        /*
                         * foreach (Line line in lineList)
                         * {
                         *  vectorName = "Lost Particle " + lineCounter + " Vector";
                         *  DatumLine dLine = DatumLine.Create(vectorPart, vectorName, line);
                         *  lineCounter++;
                         * }
                         */
                        Component vectorComponent = Component.Create(rootPart, vectorPart);
                    }

                    //Component lostParticleComponent = Component.Create(rootPart, lostPart);
                }
                else
                {
                    // Text file

                    /*
                     * foreach (string line in lines)
                     * {
                     *  Debug.Write(String.Format("{0}\n",line));
                     * }
                     */
                    bool firstLine = true;
                    int  length    = 0;

                    foreach (string line in lines)
                    {
                        if (line.Length != 0)
                        {
                            string[] tempWords = line.Split(delimeterChars, StringSplitOptions.RemoveEmptyEntries);
                            if (firstLine)
                            {
                                firstLine = false;
                                length    = tempWords.Length;
                            }

                            if (length > 3)
                            {
                                currentPoint = Point.Create(Convert.ToDouble(tempWords[0]) / 100, Convert.ToDouble(tempWords[1]) / 100, Convert.ToDouble(tempWords[2]) / 100);
                                pointList.Add(currentPoint);
                                particleCounter++;

                                Point     origin    = Point.Create(0, 0, 0);
                                Direction direction = Direction.Create(Convert.ToDouble(tempWords[3]), Convert.ToDouble(tempWords[4]), Convert.ToDouble(tempWords[5]));
                                vectorPoint = Point.Create(currentPoint.X + Convert.ToDouble(tempWords[3]) / 1, currentPoint.Y + Convert.ToDouble(tempWords[4]) / 1, currentPoint.Z + Convert.ToDouble(tempWords[5]) / 1);

                                if (showVectors)
                                {
                                    vectorName = "Lost Particle " + lineCounter.ToString() + " Vector";
                                    LineSegment   lineSeg  = new LineSegment(currentPoint, vectorPoint);
                                    ITrimmedCurve shape    = CurveSegment.Create(lineSeg);
                                    DesignCurve   desCurve = DesignCurve.Create(vectorPart, shape);
                                    desCurve.Name = vectorName;
                                    desCurve.SetColor(null, Color.Blue);
                                    lineCounter++;
                                    particleLineCounter++;
                                }

                                //Line vectorLine = Line.CreateThroughPoints(currentPoint, origin);
                                Line vectorLine = Line.CreateThroughPoints(currentPoint, vectorPoint);



                                //Line vectorLine = Line.Create(currentPoint, direction);
                                lineList.Add(vectorLine);
                            }
                            else if (length <= 3)
                            {
                                try
                                {
                                    currentPoint = Point.Create(Convert.ToDouble(tempWords[0]) / 100, Convert.ToDouble(tempWords[1]) / 100, Convert.ToDouble(tempWords[2]) / 100);
                                    pointList.Add(currentPoint);
                                    particleCounter++;
                                }
                                catch
                                {
                                }
                            }
                        }
                    }

                    foreach (Point point in pointList)
                    {
                        pointName = "Lost Particle " + pointCounter.ToString();
                        window.ActiveTool.CreateIndicator(point);
                        //DatumPoint.Create(lostPart, pointName, point);
                        var           pc     = PointCurve.Create(point);
                        ITrimmedCurve shapey = CurveSegment.Create(pc);
                        DesignCurve   dcurve = DesignCurve.Create(curvePart, shapey);
                        if (chosenColour == "Blue")
                        {
                            dcurve.SetColor(null, Color.Blue);
                        }
                        else if (chosenColour == "Red")
                        {
                            dcurve.SetColor(null, Color.Red);
                        }
                        else if (chosenColour == "Green")
                        {
                            dcurve.SetColor(null, Color.Green);
                        }
                        else if (chosenColour == "Orange")
                        {
                            dcurve.SetColor(null, Color.Orange);
                        }
                        else if (chosenColour == "Black")
                        {
                            dcurve.SetColor(null, Color.Black);
                        }
                        else if (chosenColour == "Yellow")
                        {
                            dcurve.SetColor(null, Color.Yellow);
                        }
                        else if (chosenColour == "Salmon Pink")
                        {
                            dcurve.SetColor(null, Color.Salmon);
                        }
                        pointCounter++;
                    }

                    if (showVectors)
                    {
                        Component vectorComponent = Component.Create(rootPart, vectorPart);
                    }

                    //Component lostParticleComponent = Component.Create(rootPart, lostPart);
                }
            }
        }
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            /*
             * Provide dialogue box and user inputs what they want to locate
             * These selections are Tori, Small Holes or Small Volumes
             * For Small Volumes and Holes the user will need to input a value
             * Each will be handled seperately and find matching bodies in all part design bodies
             * All will be then added to a final selection list for the user
             */

            // Instance common functions class
            InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

            // Variables
            Window window = Window.ActiveWindow;

            window.SetTool(new ToolClass());
            Document           doc          = window.Document;
            Part               rootPart     = doc.MainPart;
            InteractionContext interContext = window.ActiveContext;

            List <IDesignBody>        selectionBodies  = new List <IDesignBody>();
            List <IDesignBody>        matchingBodies   = new List <IDesignBody>();
            List <Face>               facesList        = new List <Face>();
            List <IDesignFace>        iFacesList       = new List <IDesignFace>();
            List <IDesignFace>        ifinalFacesList  = new List <IDesignFace>();
            ICollection <IDesignFace> IcollectionFaces = null;

            double minradius;
            double minVolume;
            double minFace;

            bool findCone   = false;
            bool findTori   = false;
            bool findHoles  = false;
            bool findVolume = false;
            bool findFace   = false;

#pragma warning disable CS0219 // The variable 'faceCounter' is assigned but its value is never used
            int faceCounter = 0;
#pragma warning restore CS0219 // The variable 'faceCounter' is assigned but its value is never used


#pragma warning disable CS0219 // The variable 'intMode' is assigned but its value is never used
            InteractionMode intMode = InteractionMode.Solid;
#pragma warning restore CS0219 // The variable 'intMode' is assigned but its value is never used



            if (window == null)
            {
                return;
            }

            #region Dialogue

            // Create dialogue box
            using (var dialogue = new UI.BodySelectForm())
            {
                if (dialogue.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                var partToGraphic    = new Dictionary <Part, Graphic>();

                var style = new GraphicStyle
                {
                    EnableDepthBuffer = true
                };

                findCone   = dialogue.LocateCone;
                findTori   = dialogue.LocateTori;
                findHoles  = dialogue.LocateHoles;
                findVolume = dialogue.LocateVolume;
                findFace   = dialogue.LocateFace;

                minradius = dialogue.minRadius;
                minVolume = dialogue.minVolume;
                minFace   = dialogue.minFace;
            }

            #endregion

            // Gather all design bodies
            //-----------------------------------------------
            selectionBodies.AddRange(FunctionsClass.GatherAllVisibleBodies(rootPart, window));

            // Check if each body fits wanted criteria
            //-----------------------------------------------
            foreach (IDesignBody iDesBod in selectionBodies)
            {
                DesignBody master = iDesBod.Master;
                Body       body   = master.Shape;

                var faces = body.Faces;
                facesList.AddRange(faces);
                var iFaces = iDesBod.Faces;
                iFacesList.AddRange(iFaces);

                Matrix masterTrans  = iDesBod.TransformToMaster;
                Matrix reverseTrans = masterTrans.Inverse;

                // If body fits volume criteria
                //----------------------------------------
                if (findVolume && body.Volume * 1e6 < minVolume)
                {
                    matchingBodies.Add(iDesBod);
                }
                else
                {
                    // If body fits tori or hole criteria
                    //----------------------------------------
                    for (int i = 0; i < iFacesList.Count; i++)
                    {
                        IDesignFace face = iFacesList[i];

                        if (face.Area * 1e4 < minFace)
                        {
                            ifinalFacesList.Clear();
                            ifinalFacesList.Add(face);
                            window.ActiveTool.CreateIndicator(ifinalFacesList);
                        }

                        if (face.Shape.GetGeometry <Cone>() != null && findCone)
                        {
                            ifinalFacesList.Clear();
                            ifinalFacesList.Add(face);
                            window.ActiveTool.CreateIndicator(ifinalFacesList);
                        }

                        if (face.Shape.GetGeometry <Torus>() != null && findTori)
                        {
                            ifinalFacesList.Clear();
                            ifinalFacesList.Add(face);
                            window.ActiveTool.CreateIndicator(ifinalFacesList);
                        }
                        else if (face.Shape.GetGeometry <Cylinder>() != null && face.Shape.GetGeometry <Cylinder>().Radius * 1e2 < minradius && findHoles)
                        {
                            //FunctionsClass.ColourFace(facesList[i], master);
                            ifinalFacesList.Clear();
                            ifinalFacesList.Add(face);
                            window.ActiveTool.CreateIndicator(ifinalFacesList);
                            var radius = face.Shape.GetGeometry <Cylinder>().Radius;

                            /*
                             * if (IsHole(face, radius))
                             * {
                             *  ifinalFacesList.Clear();
                             *  ifinalFacesList.Add(face);
                             *  window.ActiveTool.CreateIndicator(ifinalFacesList);
                             * }
                             */
                        }
                        else
                        {
                            // Set all the other face to slightly translucent
                            //FunctionsClass.SetFacetranslucent(face, master);
                        }
                    }
                }

                facesList.Clear();
                iFacesList.Clear();
            }
            //ICollection<IDocObject> bodyCollection = null;

            // For each matching body change the colour to red
            //----------------------------------------------------
            foreach (IDesignBody finalBody in matchingBodies)
            {
                //bodyCollection.Add(finalBody);
                DesignBody finalMaster = finalBody.Master;
                finalMaster.SetColor(null, Color.Red);
            }
            var point = Point.Create(1, 1, 1);
            IcollectionFaces = ifinalFacesList;

            // Also set them as selected by the user
            //----------------------------------------------------
            //interContext.Selection = bodyCollection;
        }
Beispiel #27
0
        //private Point GetFivePointNurbsAverage(int[,] indices) {
        //    var knots = new Knot[] {
        //                new Knot(0, 4),
        //                new Knot(1, 4)
        //            };

        //    var controlPoints = new ControlPoint[] {
        //                new ControlPoint(Point.Create(tabAngles[indices[0,0]][indices[0,1]], GetSpanAt(indices[0,0], indices[0,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[1,0]][indices[1,1]], GetSpanAt(indices[1,0], indices[1,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[2,0]][indices[2,1]], GetSpanAt(indices[2,0], indices[2,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[3,0]][indices[3,1]], GetSpanAt(indices[3,0], indices[3,1]),0), 1),
        //                new ControlPoint(Point.Create(tabAngles[indices[4,0]][indices[4,1]], GetSpanAt(indices[4,0], indices[4,1]),0), 1)
        //            };

        //    NurbsData data = new NurbsData(5, false, false, knots);
        //    NurbsCurve curve = NurbsCurve.CreateFromControlPoints(data, controlPoints);

        //    Point midpoint = curve.Evaluate(0.5).Point;
        //    return midpoint;
        //}

        //private Circle GetTabFromPoints(bool swap, int i, int j, int iOther) {
        //    Point p0 = points[i,j];
        //    Point p1 = points[i,j + 1];
        //    Point pn = (new Point[] { points[iOther,j], points[iOther,j + 1] }).Average();
        //    Direction normal = Vector.Cross(p0 - pn, p1 - pn).Direction;
        //    return Tabs.GetCircularTabCircle(p0, p1, normal, tabAngles[i,j], swap);
        //}

        //private double GetSpanAt(int i, int j) {
        //    return (vParameters[i][j + 1] - vParameters[i][j] + Math.PI * 2) % (Math.PI * 2);
        //}

        public Graphic GetGraphic()
        {
            var graphics = new List <Graphic>();

            int iSteps = points.GetLength(0);
            int jSteps = points.GetLength(1);

            bool swap = false;

            for (int i = 0; i < iSteps - 1; i++)
            {
                var facetVertices   = new List <FacetVertex>();
                var facets          = new List <Facet>();
                var tabMeshes       = new List <MeshPrimitive>();
                var porcupineCurves = new List <CurvePrimitive>();
                for (int j = 0; j < jSteps - 1; j++)
                {
                    int facetOffset = facetVertices.Count;
                    // Main ring
                    Point p00 = points[i, j];
                    Point p01 = points[i, j + 1];
                    Point p10 = points[i + 1, j];
                    Point p11 = points[i + 1, j + 1];

                    Vector    n0 = Vector.Cross(p00 - p01, p00 - p10);
                    Vector    n1 = Vector.Cross(p11 - p10, p11 - p01);
                    Direction n  = (n0 + n1).Direction;

                    facetVertices.Add(new FacetVertex(p00, n));
                    facetVertices.Add(new FacetVertex(p01, n));
                    facetVertices.Add(new FacetVertex(p10, n));
                    facetVertices.Add(new FacetVertex(p11, n));

                    if ((p00 - p11).Magnitude < (p10 - p01).Magnitude)
                    {
                        facets.Add(new Facet(0 + facetOffset, 1 + facetOffset, 3 + facetOffset));
                        facets.Add(new Facet(0 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    }
                    else
                    {
                        facets.Add(new Facet(0 + facetOffset, 2 + facetOffset, 1 + facetOffset));
                        facets.Add(new Facet(1 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    }

                    tabMeshes.Add(MeshPrimitive.Create(facetVertices, facets));

                    Point basePoint = points[i, j];
                    Point endPoint  = basePoint + Gradient(basePoint) / 10;
                    if (basePoint != endPoint)
                    {
                        porcupineCurves.Add(CurvePrimitive.Create(CurveSegment.Create(basePoint, endPoint)));
                    }

                    swap = !swap;
                }

                HSBColor hsbFill = new HSBColor(255, (float)i / iSteps * 360, 122, 88);
                HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                hsbLine.H = (float)i / iSteps * 360;

                var style = new GraphicStyle {
                    EnableDepthBuffer = true,
                    LineColor         = hsbLine.Color,
                    LineWidth         = 1,
                    FillColor         = hsbFill.Color,

                    EnableCulling = false
                };

                //		graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));
                foreach (MeshPrimitive mesh in tabMeshes)
                {
                    graphics.Add(Graphic.Create(style, mesh));
                }

                foreach (CurvePrimitive curve in porcupineCurves)
                {
                    graphics.Add(Graphic.Create(style, curve));
                }
            }

            return(Graphic.Create(null, null, graphics));
        }
        protected override bool OnMouseMove(System.Drawing.Point cursorPos, Line cursorRay, MouseButtons button)
        {
            #if false

            IDocObject preselection = InteractionContext.Preselection;
            DesignFace desFace = null;

            Profile existingProfile = Profile.GetWrapper(preselection as CustomObject);
            if (existingProfile != null)
                desFace = existingProfile.Face;
            if (desFace == null)
                desFace = preselection as DesignFace;
            if (desFace == null) // selection filtering is not applied if you (pre)select in the tree
                return false;

            Face face = desFace.Shape;
            var plane = face.GetGeometry<Plane>();

            Point point;
            if (!plane.TryIntersectLine(cursorRay, out point))
                return false; // plane is side-on

            Fin fin;
            double offset = GetOffset(face, plane, point, out fin);

            var style = new GraphicStyle
            {
                LineColor = Color.DodgerBlue,
                LineWidth = 3
            };
            Graphic datumGraphic = Graphic.Create(style, CurvePrimitive.Create(fin.Edge));

            if (existingProfile != null)
                Rendering = datumGraphic;
            else {
                style = new GraphicStyle
                {
                    LineColor = Color.Gray
                };
                Rendering = Graphic.Create(style, null, Profile.GetGraphic(0.5, 1, Math.PI / 2, Vector.Create(0.5, 0, 0)), datumGraphic);
            }
            #endif

            return false; // if we return true, the preselection won't update
        }
        public Graphic GetGraphic()
        {
            var graphics = new List<Graphic>();

            int iSteps = points.Count / 2;
            int jSteps = points[0].Count;

            //		Body body = Tabs.CreateCircularTab(p0, p1, normal, angle, isMale);

            bool swap = false;
            for (int i = 0; i < iSteps; i++) {
                var facetVertices = new List<FacetVertex>();
                var facets = new List<Facet>();
                var tabMeshes = new List<MeshPrimitive>();
                for (int j = 0; j < jSteps; j++) {
                    int facetOffset = facetVertices.Count;
                    // Main ring
                    Point p00 = points[i][j];
                    Point p01 = points[i][j + 1];
                    Point p10 = points[i + 1][j];
                    Point p11 = points[i + 1][j + 1];

                    //Vector n0 = Vector.Cross(p00 - p01, p00 - p10);
                    //Vector n1 = Vector.Cross(p11 - p10, p11 - p01);
                    //Direction n = (n0 + n1).Direction;

                    //facetVertices.Add(new FacetVertex(p00, n));
                    //facetVertices.Add(new FacetVertex(p01, n));
                    //facetVertices.Add(new FacetVertex(p10, n));
                    //facetVertices.Add(new FacetVertex(p11, n));

                    //if ((p00 - p11).Magnitude < (p10 - p01).Magnitude) {
                    //    facets.Add(new Facet(0 + facetOffset, 1 + facetOffset, 3 + facetOffset));
                    //    facets.Add(new Facet(0 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    //}
                    //else {
                    //    facets.Add(new Facet(0 + facetOffset, 2 + facetOffset, 1 + facetOffset));
                    //    facets.Add(new Facet(1 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    //}

                    Point pn0 = (new Point[] { points[i - 1][j], points[i - 1][j + 1] }).Average();
                    Point pn1 = (new Point[] { points[i + 2][j], points[i + 2][j + 1] }).Average();

                    Direction normal0 = Vector.Cross(p01 - pn0, p00 - pn0).Direction;
                    Direction normal1 = Vector.Cross(p10 - pn1, p11 - pn1).Direction;

                    tabMeshes.Add(Tabs.GetCircularTabMesh(p01, p00, -normal0, tabAngles[i][j], swap));
                    tabMeshes.Add(Tabs.GetCircularTabMesh(p10, p11, -normal1, tabAngles[i + 1][j], !swap));

                    swap = !swap;
                }

                HSBColor hsbFill = new HSBColor(255, (float) i / iSteps * 360, 122, 88);
                HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                hsbLine.H = (float) i / iSteps * 360;

                var style = new GraphicStyle {
                    EnableDepthBuffer = true,
                    LineColor = hsbLine.Color,
                    LineWidth = 1,
                    FillColor = hsbFill.Color,

                    EnableCulling = true
                };

                //		graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));
                foreach (MeshPrimitive mesh in tabMeshes)
                    graphics.Add(Graphic.Create(style, mesh));

            }

            return Graphic.Create(null, null, graphics);
        }
Beispiel #30
0
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            /*
             * Max Surface Tool
             * A. Burns 06/11/2017
             * Read user inuput max surfaces per body
             * Hightlight body with greater number of faces
             * Optionally can chnage the bodies colour
             * as well as highlighting
             */



            // Instance common functions class
            InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

            // Essential Variables
            Window             window       = Window.ActiveWindow;
            Document           doc          = window.Document;
            Part               rootPart     = doc.MainPart;
            InteractionContext interContext = window.ActiveContext;

            // Other Variables
            List <IDesignBody> allBodies       = new List <IDesignBody>();
            List <IDesignFace> ifinalFacesList = new List <IDesignFace>();

            window.SetTool(new ToolClass());

            int    faceCount;
            int    maxFaces;
            bool   changeColours;
            string colourString;

            using (var dialogue = new UI.MaxSurfacesForm())
            {
                if (dialogue.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                var partToGraphic    = new Dictionary <Part, Graphic>();

                var style = new GraphicStyle
                {
                    EnableDepthBuffer = true
                };

                maxFaces      = (int)dialogue.MaxSurfaces;
                changeColours = dialogue.ChangeColour;
                colourString  = dialogue.ColourSelection;
            }

            if (window == null)
            {
                return;
            }

            allBodies.AddRange(FunctionsClass.GatherAllVisibleBodies(rootPart, window));


            foreach (IDesignBody iDesBody in allBodies)
            {
                DesignBody desBody = iDesBody.Master;
                Body       body    = desBody.Shape.Copy();

                var faces  = body.Faces;
                var iFaces = iDesBody.Faces;
                // ifinalFacesList.AddRange(iDesBody.Faces);
                faceCount = faces.Count;

                if (faceCount > maxFaces)
                {
                    window.ActiveTool.CreateIndicator(iFaces);
                    if (changeColours)
                    {
                        if (colourString == "Blue")
                        {
                            desBody.SetColor(null, Color.Blue);
                        }
                        else if (colourString == "Red")
                        {
                            desBody.SetColor(null, Color.Red);
                        }
                        else if (colourString == "Green")
                        {
                            desBody.SetColor(null, Color.Green);
                        }
                        else if (colourString == "Orange")
                        {
                            desBody.SetColor(null, Color.Orange);
                        }
                        else if (colourString == "Black")
                        {
                            desBody.SetColor(null, Color.Black);
                        }
                        else if (colourString == "Yellow")
                        {
                            desBody.SetColor(null, Color.Yellow);
                        }
                        else if (colourString == "Salmon Pink")
                        {
                            desBody.SetColor(null, Color.Salmon);
                        }
                    }
                }
            }
        }
Beispiel #31
0
        public Graphic GetGraphic()
        {
            var graphics = new List <Graphic>();

            int iSteps = points.Count / 2;
            int jSteps = points[0].Count;

            //		Body body = Tabs.CreateCircularTab(p0, p1, normal, angle, isMale);

            bool swap = false;

            for (int i = 0; i < iSteps; i++)
            {
                var facetVertices = new List <FacetVertex>();
                var facets        = new List <Facet>();
                var tabMeshes     = new List <MeshPrimitive>();
                for (int j = 0; j < jSteps; j++)
                {
                    int facetOffset = facetVertices.Count;
                    // Main ring
                    Point p00 = points[i][j];
                    Point p01 = points[i][j + 1];
                    Point p10 = points[i + 1][j];
                    Point p11 = points[i + 1][j + 1];

                    //Vector n0 = Vector.Cross(p00 - p01, p00 - p10);
                    //Vector n1 = Vector.Cross(p11 - p10, p11 - p01);
                    //Direction n = (n0 + n1).Direction;

                    //facetVertices.Add(new FacetVertex(p00, n));
                    //facetVertices.Add(new FacetVertex(p01, n));
                    //facetVertices.Add(new FacetVertex(p10, n));
                    //facetVertices.Add(new FacetVertex(p11, n));

                    //if ((p00 - p11).Magnitude < (p10 - p01).Magnitude) {
                    //    facets.Add(new Facet(0 + facetOffset, 1 + facetOffset, 3 + facetOffset));
                    //    facets.Add(new Facet(0 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    //}
                    //else {
                    //    facets.Add(new Facet(0 + facetOffset, 2 + facetOffset, 1 + facetOffset));
                    //    facets.Add(new Facet(1 + facetOffset, 3 + facetOffset, 2 + facetOffset));
                    //}

                    Point pn0 = (new Point[] { points[i - 1][j], points[i - 1][j + 1] }).Average();
                    Point pn1 = (new Point[] { points[i + 2][j], points[i + 2][j + 1] }).Average();

                    Direction normal0 = Vector.Cross(p01 - pn0, p00 - pn0).Direction;
                    Direction normal1 = Vector.Cross(p10 - pn1, p11 - pn1).Direction;

                    tabMeshes.Add(Tabs.GetCircularTabMesh(p01, p00, -normal0, tabAngles[i][j], swap));
                    tabMeshes.Add(Tabs.GetCircularTabMesh(p10, p11, -normal1, tabAngles[i + 1][j], !swap));

                    swap = !swap;
                }

                HSBColor hsbFill = new HSBColor(255, (float)i / iSteps * 360, 122, 88);
                HSBColor hsbLine = new HSBColor(System.Drawing.Color.MidnightBlue);
                hsbLine.H = (float)i / iSteps * 360;

                var style = new GraphicStyle {
                    EnableDepthBuffer = true,
                    LineColor         = hsbLine.Color,
                    LineWidth         = 1,
                    FillColor         = hsbFill.Color,

                    EnableCulling = true
                };

                //		graphics.Add(Graphic.Create(style, MeshPrimitive.Create(facetVertices, facets)));
                foreach (MeshPrimitive mesh in tabMeshes)
                {
                    graphics.Add(Graphic.Create(style, mesh));
                }
            }

            return(Graphic.Create(null, null, graphics));
        }
        protected override bool OnMouseMove(ScreenPoint cursorPos, Line cursorRay, MouseButtons button)
        {
            if (button != MouseButtons.None)
                return false;

            IDocObject preselection = InteractionContext.Preselection;
            DesignFace designFace = preselection as DesignFace;
            if (designFace == null) // selection filtering is not applied if you (pre)select in the tree
                return false;

            CurveSegment innerCurve, outerCurveA, outerCurveB;
            CreateThreadCurves(designFace.Shape, pitch, angle, positionOffset, out innerCurve, out outerCurveA, out outerCurveB);
            var primitives = new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurveA), CurvePrimitive.Create(outerCurveB) };

            var style = new GraphicStyle {
                LineColor = Color.DarkGray,
                LineWidth = 2
            };
            Graphic centerLine = Graphic.Create(style, primitives);

            style = new GraphicStyle {
                LineColor = Color.White,
                LineWidth = 4
            };
            Graphic highlightLine = Graphic.Create(style, primitives);

            Rendering = Graphic.Create(style, null, new[] { highlightLine, centerLine });
            return false; // if we return true, the preselection won't update
        }
Beispiel #33
0
        //protected override void OnUpdate(Command command)
        //{

        /*
         * if (first)
         * {
         *  directory = Directory.GetCurrentDirectory();
         *  first = false;
         * }
         */
        //Window window = Window.ActiveWindow;
        //command.IsEnabled = window != null && SelectionAllBodies(window);
        //}
        protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect)
        {
            if (File.Exists(directory))
            {
                // Instance common functions class
                InstanceClasses.CommonSpaceClaimFunctions FunctionsClass = new InstanceClasses.CommonSpaceClaimFunctions();

                // Variables
                Window   window   = Window.ActiveWindow;
                Document doc      = window.Document;
                Part     rootPart = doc.MainPart;

                // Dialogue variables
                string filename;
                Color  coneclr;
                Color  nurbsclr;
                Color  onaclr;
                Color  offaclr;
                Color  procclr;

                // Get save location via user input
                //using (var dialogue = new SaveFileDialog())
                //{
                //    dialogue.FileName = "GeometryReport.txt";
                //    dialogue.DefaultExt = "txt";
                //    dialogue.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                //    dialogue.FilterIndex = 2;
                //    dialogue.OverwritePrompt = true;
                //
                //    if (dialogue.ShowDialog() != DialogResult.OK)
                //        return;
                //
                //    var nameAndRendering = new List<KeyValuePair<string, Graphic>>();
                //    var partToGraphic = new Dictionary<Part, Graphic>();
                //
                //    var style = new GraphicStyle
                //    {
                //        EnableDepthBuffer = true
                //    };
                //
                //    filePath = dialogue.FileName;
                //}

                //if (window == null)
                //    return;

                using (var form = new UI.GeometryAssessorForm())
                {
                    if (form.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var nameAndRendering = new List <KeyValuePair <string, Graphic> >();
                    var partToGraphic    = new Dictionary <Part, Graphic>();

                    var style = new GraphicStyle
                    {
                        EnableDepthBuffer = true
                    };

                    filename = form.FileName;
                    coneclr  = form.color1;
                    nurbsclr = form.color2;
                    onaclr   = form.color3;
                    offaclr  = form.color4;
                    procclr  = form.color5;
                }

                if (window == null)
                {
                    return;
                }

                // To pass args to python script
                var scriptParams = new Dictionary <string, object>();
                scriptParams.Add("filepath", filename);
                scriptParams.Add("conea", Convert.ToInt32(coneclr.A));
                scriptParams.Add("coner", Convert.ToInt32(coneclr.R));
                scriptParams.Add("coneg", Convert.ToInt32(coneclr.G));
                scriptParams.Add("coneb", Convert.ToInt32(coneclr.B));
                scriptParams.Add("nurba", Convert.ToInt32(nurbsclr.A));
                scriptParams.Add("nurbr", Convert.ToInt32(nurbsclr.R));
                scriptParams.Add("nurbg", Convert.ToInt32(nurbsclr.G));
                scriptParams.Add("nurbb", Convert.ToInt32(nurbsclr.B));
                scriptParams.Add("onaa", Convert.ToInt32(onaclr.A));
                scriptParams.Add("onar", Convert.ToInt32(onaclr.R));
                scriptParams.Add("onag", Convert.ToInt32(onaclr.G));
                scriptParams.Add("onab", Convert.ToInt32(onaclr.B));
                scriptParams.Add("offaa", Convert.ToInt32(offaclr.A));
                scriptParams.Add("offar", Convert.ToInt32(offaclr.R));
                scriptParams.Add("offag", Convert.ToInt32(offaclr.G));
                scriptParams.Add("offab", Convert.ToInt32(offaclr.B));
                scriptParams.Add("proca", Convert.ToInt32(procclr.A));
                scriptParams.Add("procr", Convert.ToInt32(procclr.R));
                scriptParams.Add("procg", Convert.ToInt32(procclr.G));
                scriptParams.Add("procb", Convert.ToInt32(procclr.B));

                // Run the script w/ args
                SpaceClaim.Api.V18.Application.RunScript(directory, scriptParams);

                // Show txt output
                Process.Start(filename);
            }

            else
            {
                MessageBox.Show("ERROR: Script not found.");
            }
        }
        protected override bool OnMouseMove(ScreenPoint cursorPos, Line cursorRay, MouseButtons button)
        {
            if (button != MouseButtons.None)
                return false;

            IDocObject preselection = InteractionContext.Preselection;
            DesignEdge designEdge = preselection as DesignEdge;
            if (designEdge == null) // selection filtering is not applied if you (pre)select in the tree
                return false;

            Circle edgeCircle = (Circle)designEdge.Shape.Geometry;

            CurveSegment innerCurve = CurveSegment.Create(Circle.Create(edgeCircle.Frame, apiGroove.InnerDiameter / 2));
            CurveSegment outerCurve = CurveSegment.Create(Circle.Create(edgeCircle.Frame, apiGroove.OuterDiameter / 2));

            var style = new GraphicStyle {
                LineColor = Color.DarkGray,
                LineWidth = 2
            };
            Graphic centerLine = Graphic.Create(style, new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurve) });

            style = new GraphicStyle {
                LineColor = Color.White,
                LineWidth = 4
            };
            Graphic highlightLine = Graphic.Create(style, new[] { CurvePrimitive.Create(innerCurve), CurvePrimitive.Create(outerCurve) });

            Rendering = Graphic.Create(style, null, new[] { highlightLine, centerLine });
            return false; // if we return true, the preselection won't update
        }
Beispiel #35
0
        void UpdateRendering()
        {
            // list of primitives to be rendered:
            var primitives = new List <Primitive> {
            };

            // line for basX, basY:
            if (tState >= 1)
            {
                Vector v1, v2;
                v1 = basX.Direction.UnitVector * ext;
                v2 = basY.Direction.UnitVector * ext;
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(pOrig, pOrig + v1)));
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(pOrig, pOrig + v2)));
            }
            if (tState >= 2)
            {
                Point  p1, p2, p3, p4;
                Vector v1, v2;
                v1 = basX.Direction.UnitVector * ext;
                v2 = basY.Direction.UnitVector * ext;
                p1 = pOrig - v1 - v2;
                p2 = pOrig - v1 + v2;
                p3 = pOrig + v1 + v2;
                p4 = pOrig + v1 - v2;
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p1, p2)));
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p2, p3)));
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p3, p4)));
                primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p4, p1)));
            }

            /*{
             *  // show frame of the sectionPlane:
             *  Point p0 = Window.ActiveContext.SectionPlane.Frame.Origin;
             *  Vector vx = Window.ActiveContext.SectionPlane.Frame.DirX.UnitVector * ext * 1.2;
             *  Vector vy = Window.ActiveContext.SectionPlane.Frame.DirY.UnitVector * ext * 0.9;
             *  primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p0, p0 + vx)));
             *  primitives.Add(CurvePrimitive.Create(CurveSegment.Create(p0, p0 + vy)));
             * }
             */

            {
                // show screen
                ScreenPoint sp1 = new ScreenPoint(10, 10);
                ScreenPoint sp2 = new ScreenPoint(Window.ActiveWindow.Size.Width - 10, Window.ActiveWindow.Size.Height - 10);
                Point       p1;
                Single      r = 1.0f;
                Line        l;
                Vector      v1;
                l = Window.ActiveContext.GetCursorRay(sp1);
                if (getPointUnderCursor(l, out p1, out v1))
                {
                    primitives.Add(PointPrimitive.Create(p1, r));
                }
                l = Window.ActiveContext.GetCursorRay(sp2);
                if (getPointUnderCursor(l, out p1, out v1))
                {
                    primitives.Add(PointPrimitive.Create(p1, r));
                }
            }

            // string msg = PlotCommands[0] + PlotCommands[1] + PlotCommands[2];
            // primitives.Add(TextPrimitive.Create(msg, LocationPoint.RightSide, pCur, 0, 0, new TextPadding(3)));

            var style = new GraphicStyle
            {
                LineColor = Color.Blue,
                FillColor = Color.Black,
                TextColor = Color.DarkGray,
                LineWidth = 2
            };

            Rendering = Graphic.Create(style, primitives);
        }
        public void SetGraphics()
        {
            double time = Math.Max(this.time, 0);
            time = Math.Min(time, totalTime);

            if (!TryGetLocationFromTime(time, out  index, out  ratio))
                throw new IndexOutOfRangeException();

            Point location = Interpolation.Interpolate(locations[index].Point, locations[index + 1].Point, ratio);

            Primitive toolPrimitive = toolPath.CuttingTool.GetPrimitive();
            Color color = toolPathObj.Color;
            color = Color.FromArgb(255 - (255 - color.R) / 2, 255 - (255 - color.G) / 2, 255 - (255 - color.B) / 2);

            GraphicStyle style = new GraphicStyle {
                EnableDepthBuffer = true,
                FillColor = color,
                LineColor = color
            };

            Rendering = Graphic.Create(style, new[] { toolPrimitive }, null, Matrix.CreateMapping(toolPath.Csys) * Matrix.CreateTranslation(location.Vector));
            StatusText = string.Format(Resources.AnimationToolMesage, time, totalTime, time / totalTime * 100);
        }