public VerticalPrismalSurface(IPolyline @base, Interval zRange, bool isClosed = false)
        {
            if (zRange.IsEmpty)
            {
                throw new ArgumentException("z range should not be empty", "zRange");
            }

            _base     = @base;
            _zRange   = zRange;
            _isClosed = isClosed;

            if (isClosed)
            {
                if ([email protected])
                {
                    throw new ArgumentException("Closed prism has to have closed base");
                }

                _closedBase         = (IClosedPolyline)@base;
                _isCounterclockwise = _closedBase.SignedArea() > 0;
            }

            _vertices = new VertexCollection(this);
            _edges    = new EdgeCollection(this);
            _faces    = new FaceCollection(this);

            _undirectedComparer = new UndirectedEdgeComparerImpl(this);
        }
Example #2
0
        public static void createFillet(PartDocument oDoc)
        {
            SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oDoc.ComponentDefinition;

            SheetMetalFeatures sFeatures = (SheetMetalFeatures)oCompDef.Features;

            foreach (Edge oEdge in oCompDef.SurfaceBodies[1].ConcaveEdges)
            {
                int tmpCount = oCompDef.SurfaceBodies[1].ConcaveEdges.Count;

                coloroEntita(oDoc, 255, 0, 0, oEdge);

                try
                {
                    EdgeCollection oBendEdges = iApp.TransientObjects.CreateEdgeCollection();

                    oBendEdges.Add(oEdge);

                    BendDefinition oBendDef = sFeatures.BendFeatures.CreateBendDefinition(oBendEdges);

                    BendFeature oBendFeature = sFeatures.BendFeatures.Add(oBendDef);

                    //if (tmpCount != oCompDef.SurfaceBodies[1].ConcaveEdges.Count)
                    //{
                    createFillet(oDoc);
                    break;
                    //}
                }
                catch { }
            }
        }
Example #3
0
        /// <summary>
        ///     Removes all edges that match <paramref name="predicate" />.
        /// </summary>
        /// <param name="vertex">The vertex.</param>
        /// <param name="predicate">
        ///     A pure delegate that takes an
        ///     <typeparamref name="TEdge" /> and returns true if the edge should
        ///     be removed.
        /// </param>
        /// <returns>
        ///     The number of edges removed.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">predicate</exception>
        public int RemoveEdge(TVertex vertex, Func <TEdge, bool> predicate)
        {
            if (!this.ContainsVertex(vertex))
            {
                return(0);
            }

            if (predicate == null)
            {
                throw new ArgumentNullException("predicate");
            }

            var edges        = this.VertexEdges[vertex];
            var edgeToRemove = new EdgeCollection <TVertex, TEdge>();

            foreach (var edge in edges)
            {
                if (predicate(edge))
                {
                    edgeToRemove.Add(edge);
                }
            }

            foreach (var edge in edgeToRemove)
            {
                edges.Remove(edge);

                if (this.EdgeList.Contains(edge))
                {
                    this.EdgeList.Remove(edge);
                }
            }

            return(edgeToRemove.Count);
        }
Example #4
0
        /// <summary>
        ///     Removes <paramref name="vertex" /> from the graph
        /// </summary>
        /// <param name="vertex">The vertex.</param>
        /// <returns>
        ///     true if <paramref name="vertex" /> was successfully removed; otherwise falSE.
        /// </returns>
        public bool RemoveVertex(TVertex vertex)
        {
            if (!this.ContainsVertex(vertex))
            {
                return(false);
            }

            // Remove all of the edges.
            this.VertexEdges[vertex].Clear();

            // iterage over edges and remove each edge touching the vertex
            var edgeToRemove = new EdgeCollection <TVertex, TEdge>();

            foreach (var entry in this.VertexEdges)
            {
                if (entry.Key.Equals(vertex))
                {
                    continue;
                }

                foreach (var edge in entry.Value)
                {
                    if (edge.Target.Equals(vertex))
                    {
                        edgeToRemove.Add(edge);
                    }
                }
                foreach (var edge in edgeToRemove)
                {
                    entry.Value.Remove(edge);
                }
            }

            return(this.VertexEdges.Remove(vertex));
        }
Example #5
0
                       Dictionary <TileGroupKey, int>) UnpackEdgeCols(this TileMapList tileMaps,
                                                                      Dictionary <TileMap, List <EdgeCollection <TileEdge> > > tileMapToAllEdgeColls)
        {
            if (tileMaps is null)
            {
                throw new ArgumentNullException(nameof(tileMaps));
            }
            if (tileMapToAllEdgeColls is null)
            {
                throw new ArgumentNullException(nameof(tileMapToAllEdgeColls));
            }

            var edgeCollMap  = new Dictionary <EdgeCollKey, EdgeCollection <TileEdge> >();
            var holeGroupMap = new Dictionary <HoleGroupKey, int>();
            var tileGroupMap = new Dictionary <TileGroupKey, int>();

            foreach (TileMap tileMap in tileMaps.Values)
            {
                List <EdgeCollection <TileEdge> > allEdgeColls = tileMapToAllEdgeColls[tileMap];
                tileGroupMap.Add(new TileGroupKey(tileMap), allEdgeColls.Count);

                for (int tileGroup = 0; tileGroup < allEdgeColls.Count; tileGroup++)
                {
                    EdgeCollection <TileEdge>         thisGroupsColl = allEdgeColls[tileGroup];
                    List <EdgeCollection <TileEdge> > splitEdgeColl  = _SplitEdgeColl(thisGroupsColl); //should hold perim in index 0 and holes in 1-inf
                    holeGroupMap.Add(new HoleGroupKey(tileMap, tileGroup), splitEdgeColl.Count);

                    for (int holeGroup = 0; holeGroup < splitEdgeColl.Count; holeGroup++)
                    {
                        edgeCollMap.Add(new EdgeCollKey(tileMap, tileGroup, holeGroup), splitEdgeColl[holeGroup]);
                    }
                }
            }
            return(edgeCollMap, holeGroupMap, tileGroupMap);
        }
        /// <summary>
        /// Augments the <see cref="VisitedGraph"/> with reversed edges.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// The graph has already been augmented.
        /// </exception>
        public void AddReversedEdges()
        {
            if (this.Augmented)
            {
                throw new InvalidOperationException("Graph already augmented");
            }
            // step 1, find edges that need reversing
            EdgeCollection notReversedEdges = new EdgeCollection();

            foreach (IEdge edge in this.VisitedGraph.Edges)
            {
                // if reversed already found, continue
                if (this.reversedEdges.Contains(edge))
                {
                    continue;
                }

                IEdge reversedEdge = this.FindReversedEdge(edge);
                if (reversedEdge != null)
                {
                    // setup edge
                    this.reversedEdges[edge] = reversedEdge;
                    // setup reversed if needed
                    if (!this.reversedEdges.Contains(reversedEdge))
                    {
                        this.reversedEdges[reversedEdge] = edge;
                    }
                    continue;
                }

                // this edge has no reverse
                notReversedEdges.Add(edge);
            }

            // step 2, go over each not reversed edge, add reverse
            foreach (IEdge edge in notReversedEdges)
            {
                if (this.reversedEdges.Contains(edge))
                {
                    continue;
                }

                // already been added
                IEdge reversedEdge = this.FindReversedEdge(edge);
                if (reversedEdge != null)
                {
                    this.reversedEdges[edge] = reversedEdge;
                    continue;
                }

                // need to create one
                reversedEdge = this.VisitedGraph.AddEdge(edge.Target, edge.Source);
                this.augmentedEgdes.Add(reversedEdge);
                this.reversedEdges[edge]         = reversedEdge;
                this.reversedEdges[reversedEdge] = edge;
                this.OnReservedEdgeAdded(new EdgeEventArgs(reversedEdge));
            }

            this.augmented = true;
        }
Example #7
0
 /// <summary>
 /// Initializes a new, empty mesh.
 /// </summary>
 public HalfEdgeMesh()
 {
     Edges     = new EdgeCollection(this);
     Faces     = new FaceCollection(this);
     HalfEdges = new HalfedgeCollection(this);
     Vertices  = new VertexCollection(this);
 }
Example #8
0
        private List <KeyValuePair <IVertex, IVertex> > SaveExistingEdges(CondensedVertex v)
        {
            List <KeyValuePair <IVertex, IVertex> > edgeTbl = new List <KeyValuePair <IVertex, IVertex> >();
            //				Dictionary<IVertex, IVertex> edgeTbl = new Dictionary<IVertex,IVertex>();

            EdgeCollection outboundEdges = this.OutEdges(v);

            foreach (IEdge e in outboundEdges)
            {
                edgeTbl.Add(new KeyValuePair <IVertex, IVertex>(e.Source, e.Target));
                //CondensedVertex srcV = (CondensedVertex)e.Source;
                //CondensedVertex targetV = (CondensedVertex)e.Target;
                //Trace.WriteLine("E: " + srcV.Name + " -> " + targetV.Name);
            }

            FilteredEdgeEnumerable inboundEdges = this.SelectEdges(new IsInEdgePredicate(v));

            //Debug.WriteLine("inboundEdges");
            foreach (IEdge e in inboundEdges)
            {
                edgeTbl.Add(new KeyValuePair <IVertex, IVertex>(e.Source, e.Target));
                //CondensedVertex srcV = (CondensedVertex)e.Source;
                //CondensedVertex targetV = (CondensedVertex)e.Target;
                //Trace.WriteLine("E: " + srcV.Name + " -> " + targetV.Name);
            }
            return(edgeTbl);
        }
Example #9
0
        /// <summary>
        /// Remove all the out-edges of vertex u for which the predicate pred
        /// returns true.
        /// </summary>
        /// <param name="u">vertex</param>
        /// <param name="pred">edge predicate</param>
        public void RemoveOutEdgeIf(IVertex u, IEdgePredicate pred)
        {
            if (u == null)
            {
                throw new ArgumentNullException("vertex u");
            }
            if (pred == null)
            {
                throw new ArgumentNullException("predicate");
            }

            EdgeCollection edges        = VertexOutEdges[u];
            EdgeCollection removedEdges = new EdgeCollection();

            foreach (IEdge e in edges)
            {
                if (pred.Test(e))
                {
                    removedEdges.Add(e);
                }
            }

            foreach (IEdge e in removedEdges)
            {
                RemoveEdge(e);
            }
        }
        /// <summary>
        /// Computes the set of eulerian trails that traverse the edge set.
        /// </summary>
        /// <remarks>
        /// This method returns a set of disjoint eulerian trails. This set
        /// of trails spans the entire set of edges.
        /// </remarks>
        /// <returns>Eulerian trail set</returns>
        public EdgeCollectionCollection Trails()
        {
            EdgeCollectionCollection trails = new EdgeCollectionCollection();

            EdgeCollection trail = new EdgeCollection();

            foreach (IEdge e in this.Circuit)
            {
                if (TemporaryEdges.Contains(e))
                {
                    // store previous trail and start new one.
                    if (trail.Count != 0)
                    {
                        trails.Add(trail);
                    }
                    // start new trail
                    trail = new EdgeCollection();
                }
                else
                {
                    trail.Add(e);
                }
            }
            if (trail.Count != 0)
            {
                trails.Add(trail);
            }

            return(trails);
        }
Example #11
0
        /// <summary>
        /// Remove the edge (u,v) from the graph.
        /// If the graph allows parallel edges this remove all occurrences of
        /// (u,v).
        /// </summary>
        /// <param name="u">source vertex</param>
        /// <param name="v">target vertex</param>
        public virtual void RemoveEdge(IVertex u, IVertex v)
        {
            if (u == null)
            {
                throw new ArgumentNullException("source vertex");
            }
            if (v == null)
            {
                throw new ArgumentNullException("targetvertex");
            }

            EdgeCollection edges = VertexOutEdges[u];
            // marking edges to remove
            EdgeCollection removedEdges = new EdgeCollection();

            foreach (IEdge e in edges)
            {
                if (e.Target == v)
                {
                    removedEdges.Add(e);
                }
            }
            //removing edges
            foreach (IEdge e in removedEdges)
            {
                edges.Remove(e);
                m_Edges.Remove(e);
            }
        }
Example #12
0
        public void OutputAllMergedActions(
            EdgePredecessorRecorderVisitor erec,
            GraphvizAlgorithm gw,
            string path)
        {
            int i = 1000;

            Console.WriteLine("All paths (merged):");
            foreach (EdgeCollection ec in erec.AllMergedPaths())
            {
                CurrentEdgePath = ec;
                gw.Write(String.Format("path-merged{1}", path, i));
                foreach (IEdge edge in ec)
                {
                    Console.WriteLine("{0}->{1}, {2}",
                                      ((NamedVertex)edge.Source).Name,
                                      ((NamedVertex)edge.Target).Name,
                                      ((NamedEdge)edge).Name
                                      );
                }
                ++i;
                Console.WriteLine();
            }
            CurrentEdgePath = null;
        }
        /// <summary>
        /// Create a merged path.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method creates an edge path that stops if an edge is not white
        /// or the edge has no more predecessors.
        /// </para>
        /// </remarks>
        /// <param name="se">end edge</param>
        /// <param name="colors">edge color dictionary</param>
        /// <returns>path to edge</returns>
        public EdgeCollection MergedPath(IEdge se, EdgeColorDictionary colors)
        {
            EdgeCollection path = new EdgeCollection();

            IEdge      ec = se;
            GraphColor c  = colors[ec];

            if (c != GraphColor.White)
            {
                return(path);
            }
            else
            {
                colors[ec] = GraphColor.Black;
            }

            path.Insert(0, ec);
            while (EdgePredecessors.Contains(ec))
            {
                IEdge e = EdgePredecessors[ec];
                c = colors[e];
                if (c != GraphColor.White)
                {
                    return(path);
                }
                else
                {
                    colors[e] = GraphColor.Black;
                }

                path.Insert(0, e);
                ec = e;
            }
            return(path);
        }
        public void CheckPredecessorLineGraph()
        {
            AdjacencyGraph g  = new AdjacencyGraph(true);
            IVertex        v1 = g.AddVertex();
            IVertex        v2 = g.AddVertex();
            IVertex        v3 = g.AddVertex();

            IEdge e12 = g.AddEdge(v1, v2);
            IEdge e23 = g.AddEdge(v2, v3);

            EdgeDoubleDictionary          weights = DijkstraShortestPathAlgorithm.UnaryWeightsFromEdgeList(g);
            DijkstraShortestPathAlgorithm dij     = new DijkstraShortestPathAlgorithm(g, weights);
            PredecessorRecorderVisitor    vis     = new PredecessorRecorderVisitor();

            dij.RegisterPredecessorRecorderHandlers(vis);

            dij.Compute(v1);

            EdgeCollection col = vis.Path(v2);

            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            col = vis.Path(v3);
            Assert.AreEqual(2, col.Count);
            Assert.AreEqual(e12, col[0]);
            Assert.AreEqual(e23, col[1]);
        }
Example #15
0
        public bool IsInteriorsConnected()
        {
            // node the edges, in case holes touch the shell
            EdgeCollection splitEdges = new EdgeCollection();

            geomGraph.ComputeSplitEdges(splitEdges);

            // form the edges into rings
            PlanarGraph graph = new PlanarGraph(new OverlayNodeFactory());

            graph.AddEdges(splitEdges);
            SetInteriorEdgesInResult(graph);
            graph.LinkResultDirectedEdges();

            ArrayList edgeRings = BuildEdgeRings(graph.EdgeEnds);

            // Mark all the edges for the edgeRings corresponding to the shells
            // of the input polygons.  Note only ONE ring gets marked for each shell.
            VisitShellInteriors(geomGraph.Geometry, graph);

            // If there are any unvisited shell edges
            // (i.e. a ring which is not a hole and which has the interior
            // of the parent area on the RHS)
            // this means that one or more holes must have split the interior of the
            // polygon into at least two pieces.  The polygon is thus invalid.
            return(!HasUnvisitedShellEdge(edgeRings));
        }
Example #16
0
 public override void ComputeIntersections(EdgeCollection edges0,
                                           EdgeCollection edges1, SegmentIntersector si)
 {
     Add(edges0, edges0);
     Add(edges1, edges1);
     ComputeIntersections(si);
 }
Example #17
0
        public GraphBase(bool isReadOnly)
        {
            IsReadOnly = isReadOnly;

            Nodes = new NodeCollection(this);
            Edges = new EdgeCollection(this);
        }
Example #18
0
        public void ClearVertex(IVertex v)
        {
            if (v == null)
            {
                throw new ArgumentNullException("v");
            }
            if (!this.ContainsVertex(v))
            {
                throw new ArgumentException("v is not part of the graph");
            }

            EdgeCollection edges = new EdgeCollection();

            foreach (IEdge e in this.VisitedGraph.OutEdges(v))
            {
                edges.Add(e);
            }
            foreach (IEdge e in this.VisitedGraph.InEdges(v))
            {
                edges.Add(e);
            }

            foreach (IEdge e in edges)
            {
                if (this.VisitedGraph.ContainsEdge(e))
                {
                    RemoveEdge(e);
                }
            }
        }
Example #19
0
 /// <summary>
 /// Initializes a new, empty mesh.
 /// </summary>
 public HalfEdgeMesh()
 {
     Edges = new EdgeCollection(this);
     Faces = new FaceCollection(this);
     HalfEdges = new HalfedgeCollection(this);
     Vertices = new VertexCollection(this);
 }
Example #20
0
 public void SetGraph(VertexCollection<String> okVertices, EdgeCollection<String> okEdges, AttributesDictionary<bool> okDialogAttributes, AttributesDictionary<string> okDraphAttributes)
 {
     vertices = okVertices;
     edges = okEdges;
     dialogAttributes = okDialogAttributes;
     graphAttributes = okDraphAttributes;
 }
Example #21
0
        /// <summary>
        /// Superimposes ONE hole group's ledge groups.
        /// There isn't much else to say, so check out that disgusting number of input parameters.
        /// Hopefully nobody on earth ever looks at this except me.
        /// </summary>
        /// <param name="ledgeCollMap"></param>
        /// <param name="ledgeGroupMap"></param>
        /// <param name="baseTileMap"></param>
        /// <param name="superTileMap"></param>
        /// <param name="preTileMap"></param>
        /// <param name="tileGroup"></param>
        /// <param name="holeGroup"></param>
        /// <returns></returns>
        private static (Dictionary <LedgeCollKey, EdgeCollection <TileEdge> >, Dictionary <LedgeGroupKey, int>) _SuperimposeHoleGroup(
            IDictionary <LedgeCollKey, EdgeCollection <TileEdge> > ledgeCollMap,
            IDictionary <LedgeGroupKey, int> ledgeGroupMap,
            TileMap baseTileMap,
            TileMap superTileMap,
            TileMap preTileMap,
            int tileGroup,
            int holeGroup)
        {
            var ledgeCollMapClone  = new Dictionary <LedgeCollKey, EdgeCollection <TileEdge> >(ledgeCollMap);
            var ledgeGroupMapClone = new Dictionary <LedgeGroupKey, int>(ledgeGroupMap);

            int superLedgeGroup = 0; //Once superimposed, # of ledge groups CAN change
            int maxLedgeGroups  = ledgeGroupMap[new LedgeGroupKey(baseTileMap, tileGroup, holeGroup, preTileMap)];

            for (int ledgeGroup = 0; ledgeGroup < maxLedgeGroups; ledgeGroup++)
            {
                EdgeCollection <TileEdge> ledgeColl   = ledgeCollMap[new LedgeCollKey(baseTileMap, tileGroup, holeGroup, preTileMap, ledgeGroup)];
                EdgeCollection <TileEdge> validLedges = _BuildHoleGroupValidLedges(ledgeColl, preTileMap, superTileMap);

                while (validLedges.Count > 0)
                { //repeatedly GetOrderedGroup() on valid_ledges until no ledges are left behind
                    EdgeCollection <TileEdge> orderedLedges = validLedges.GetOrderedCollection();
                    var validSet = new HashSet <TileEdge>(validLedges);
                    validSet.ExceptWith(orderedLedges);
                    validLedges = new EdgeCollection <TileEdge>(validSet);
                    ledgeCollMapClone.Add(new LedgeCollKey(baseTileMap, tileGroup, holeGroup, superTileMap, superLedgeGroup), orderedLedges);
                    superLedgeGroup++;
                }
            }
            ledgeGroupMapClone.Add(new LedgeGroupKey(baseTileMap, tileGroup, holeGroup, superTileMap), superLedgeGroup);
            return(ledgeCollMapClone, ledgeGroupMapClone);
        }
Example #22
0
        private void CreateAllRoundFillet()
        {
            PartDocument oPartDocument;

            oPartDocument = (PartDocument)m_inventorApplication.ActiveDocument;

            PartComponentDefinition oPartComDef;

            oPartComDef = oPartDocument.ComponentDefinition;

            PlanarSketch oSketch;

            oSketch = oPartComDef.Sketches.Add(oPartComDef.WorkPlanes[3]);

            oSketch.SketchLines.AddAsTwoPointRectangle(m_inventorApplication.TransientGeometry.CreatePoint2d(-6, -4), m_inventorApplication.TransientGeometry.CreatePoint2d(6, 4));

            Profile oProfile;

            oProfile = oSketch.Profiles.AddForSolid();

            ExtrudeDefinition oExtrudeDef;

            oExtrudeDef = oPartComDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, PartFeatureOperationEnum.kJoinOperation);
            oExtrudeDef.SetDistanceExtent(5, PartFeatureExtentDirectionEnum.kSymmetricExtentDirection);
            ExtrudeFeature oExtrude;

            oExtrude = oPartComDef.Features.ExtrudeFeatures.Add(oExtrudeDef);

            EdgeCollection oEdges = null;

            FilletFeature oFillet;

            oFillet = oPartComDef.Features.FilletFeatures.AddSimple(oEdges, 1, false, true, true, false, true, false);
        }
Example #23
0
        /// <summary>
        /// Tests all actions for adjacencygraph and filtered graph.
        /// </summary>
        public void Test()
        {
            // The all action algorithms
            AdjacencyGraph g = GraphProvider.Fsm();

            Console.WriteLine("Graph: {0} vertices, {1} edges, {2} eulerian trails",
                              g.VerticesCount,
                              g.EdgesCount,
                              EulerianTrailAlgorithm.ComputeEulerianPathCount(g)
                              );

            // do layout
            EulerianTrailAlgorithm euler = CreateEulerianTrail(g);
            EdgeCollection         temps = euler.AddTemporaryEdges(g);

            Console.WriteLine("Added {0} temporary edges", temps.Count);
            foreach (NamedEdge ne in temps)
            {
                ne.Name = "temporary";
            }
            euler.Compute();
            euler.RemoveTemporaryEdges(g);

            Console.WriteLine("Circuit: {0} edges",
                              euler.Circuit.Count);
            foreach (NamedEdge e in euler.Circuit)
            {
                Console.WriteLine("{0}->{1} ({2})",
                                  (NamedVertex)e.Source,
                                  (NamedVertex)e.Target,
                                  e.Name
                                  );
            }


            Console.WriteLine("Trails:");
            foreach (EdgeCollection ec in euler.Trails(
                         Traversal.FirstVertexIf(g.Vertices, new NameEqualPredicate("S0")))
                     )
            {
                foreach (IEdge edge in ec)
                {
                    Console.WriteLine("{0}->{1}, {2}",
                                      ((NamedVertex)edge.Source).Name,
                                      ((NamedVertex)edge.Target).Name,
                                      ((NamedEdge)edge).Name
                                      );
                }
                Console.WriteLine();
            }


            Console.WriteLine("Testing AdjacencyGraph");
            TestAllActions(GraphProvider.Fsm(), @"../EdgeDfs");

            // testing on filtered graph
            Console.WriteLine("Testing FilteredVertexAndEdgeListGraph");
            TestAllActions(GraphProvider.FilteredFsm(), @"../FilteredEdgeDfs");
        }
Example #24
0
        private void CreatePart_Click(object sender, EventArgs e)
        {
            if (inventor == null)
            {
                MessageBox.Show("No inventor instance detected", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            PartDocument doc = inventor.Documents.Add(DocumentTypeEnum.kPartDocumentObject, null, true) as PartDocument;

            doc.PropertySets["{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"]["Author"].Value = "Vladyslav Romanchuk";

            //User-defined property
            doc.PropertySets["{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"].Add("Parts R Us", "Supplier");
            PartComponentDefinition partDefinition = (PartComponentDefinition)doc.ComponentDefinition;

            // Create a 2D sketch on the X-Y plane.
            PlanarSketch      sketch1 = (PlanarSketch)partDefinition.Sketches.Add(partDefinition.WorkPlanes[3]);
            TransientGeometry tg      = inventor.TransientGeometry;

            Point2d[] points = new Point2d[5] {
                tg.CreatePoint2d(0, 0), tg.CreatePoint2d(0, 20), tg.CreatePoint2d(20, 20), tg.CreatePoint2d(20, -10), tg.CreatePoint2d(10, -10)
            };
            SketchLine[] lines = new SketchLine[5];
            lines[0] = sketch1.SketchLines.AddByTwoPoints(points[0], points[1]);
            for (int i = 1; i < lines.Length - 1; i++)
            {
                lines[i] = sketch1.SketchLines.AddByTwoPoints(lines[i - 1].EndSketchPoint, points[i + 1]);
            }
            sketch1.SketchArcs.AddByCenterStartEndPoint(tg.CreatePoint2d(10, 0), lines[3].EndSketchPoint, lines[0].StartSketchPoint, false);

            //Extrude
            Profile           profile           = sketch1.Profiles.AddForSolid();
            ExtrudeDefinition extrudeDefinition = partDefinition.Features.ExtrudeFeatures.CreateExtrudeDefinition(profile, PartFeatureOperationEnum.kNewBodyOperation);

            extrudeDefinition.SetDistanceExtent(6, PartFeatureExtentDirectionEnum.kSymmetricExtentDirection);
            ExtrudeFeature extrude = (ExtrudeFeature)partDefinition.Features.ExtrudeFeatures.Add(extrudeDefinition);

            //second scatch
            Face topCap = extrude.EndFaces[1];

            sketch1 = partDefinition.Sketches.Add(topCap, false);

            Point2d      center = sketch1.ModelToSketchSpace(tg.CreatePoint(2.5, 1.5, 1.5));
            SketchCircle Circle = sketch1.SketchCircles.AddByCenterRadius(center, 1);

            profile           = sketch1.Profiles.AddForSolid(true, null, null);
            extrudeDefinition = partDefinition.Features.ExtrudeFeatures.CreateExtrudeDefinition(profile, PartFeatureOperationEnum.kJoinOperation);
            extrudeDefinition.SetDistanceExtent(4, PartFeatureExtentDirectionEnum.kSymmetricExtentDirection);
            extrude = (ExtrudeFeature)partDefinition.Features.ExtrudeFeatures.Add(extrudeDefinition);
            Edges          cylinderEdges = extrude.SideFaces[1].Edges;
            EdgeCollection filletEdges   = inventor.TransientObjects.CreateEdgeCollection(null);

            //foreach (var el in cylinderEdges)
            //    filletEdges.Add(el);
            filletEdges.Add(cylinderEdges[2]);
            //adding fillet
            partDefinition.Features.FilletFeatures.AddSimple(filletEdges, 0.25, false, false, false, false, false, true);
            //doc.SaveAs("D:\\SaveTest2.ipt", false);
        }
Example #25
0
 public GraphEventArgs(VertexCollection<String> vertices, EdgeCollection<String> edges, AttributesDictionary<bool> dialogAttributes, AttributesDictionary<string> graphAttributes)
 {
     Type = Types.GraphGenerated;
     Vertices = vertices;
     Edges = edges;
     DialogAttributes = dialogAttributes;
     GraphAttributes = graphAttributes;
 }
Example #26
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="edges"></param>
 public EdgeRecorderVisitor(EdgeCollection edges)
 {
     if (edges == null)
     {
         throw new ArgumentNullException("edges");
     }
     this.edges = edges;
 }
Example #27
0
 private void Add(EdgeCollection edges, object edgeSet)
 {
     for (IEdgeEnumerator i = edges.GetEnumerator(); i.MoveNext();)
     {
         Edge edge = i.Current;
         Add(edge, edgeSet);
     }
 }
Example #28
0
		private void InsertUniqueEdges(EdgeCollection edges)
		{
			for (IEdgeEnumerator i = edges.GetEnumerator(); i.MoveNext(); )
			{
				Edge e = i.Current;
				InsertUniqueEdge(e);
			}
		}
Example #29
0
 private void Add(EdgeCollection edges)
 {
     for (IEdgeEnumerator i = edges.GetEnumerator(); i.MoveNext();)
     {
         Edge edge = i.Current;
         // edge is its own group
         Add(edge, edge);
     }
 }
Example #30
0
        public RelateComputer(GeometryGraph[] arg)
        {
            li            = new RobustLineIntersector();
            ptLocator     = new PointLocator();
            nodes         = new NodeMap(new RelateNodeFactory());
            isolatedEdges = new EdgeCollection();

            this.arg = arg;
        }
Example #31
0
        //function to draw shaft with all features
        public static void Shaft()
        {
            partDef = var_es.part_doc.ComponentDefinition;
            tg      = var_es.InventorApp.TransientGeometry;
            sketch  = partDef.Sketches.Add(partDef.WorkPlanes[3]);
            Edges   = default(EdgeCollection);
            Edges   = var_es.InventorApp.TransientObjects.CreateEdgeCollection();
            S_Face  = null;
            E_Face  = null;
            Side_F  = null;
            int i = 0, j = 1;

            foreach (var part in var_es.list)
            {
                S_Face = null;
                E_Face = null;
                var obj = part;
                if (obj != null)
                {
                    obj.Create_BR(tg, ref sketch, Edges, ref S_Face, ref E_Face, ref partDef);
                }
                try
                {
                    if (var_es.chamfer_list.Count != 0)
                    {
                        S_Face = obj.Start_face;
                        E_Face = obj.End_face;
                        if (part is Pol)
                        {
                            Side_F = obj.Side_faces;
                        }

                        Edges = var_es.InventorApp.TransientObjects.CreateEdgeCollection();
                        if (var_es.chamfer_list[i] != null)
                        {
                            Create feature = var_es.chamfer_list[i];
                            feature.Create_BR(tg, ref sketch, Edges, ref S_Face, ref E_Face, ref partDef);
                        }
                        Edges  = var_es.InventorApp.TransientObjects.CreateEdgeCollection();
                        S_Face = obj.Start_face;
                        E_Face = obj.End_face;
                        if (var_es.chamfer_list[j] != null)
                        {
                            Create feature = var_es.chamfer_list[j];
                            feature.Create_BR(tg, ref sketch, Edges, ref S_Face, ref E_Face, ref partDef);
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                i += 2;
                j += 2;
            }
        }
    public override void OnInspectorGUI()
    {
        edgeCollection = target as EdgeCollection;

        if (ReferenceEquals(edgeCollection, null))
        {
            return;
        }

        if (edgeCollection.Graph is { IsLocked : true })
        public TransformedPolysurface(IPolysurface localSurface, RotoTranslation3 localToGlobal)
        {
            _localSurface  = localSurface;
            _localToGlobal = localToGlobal;

            _vertexCollection = new VertexCollection(this);
            _edgeCollection   = new EdgeCollection(this);
            _faceCollection   = new FaceCollection(this);

            _undirectedComparer = new UndirectedEdgeComparerImpl(this);
        }
        /// <summary>
        /// Cadデータをコピーする
        /// </summary>
        /// <param name="src"></param>
        public void CopyData(CadLogicBase src)
        {
            //Console.WriteLine("-------CadLogicBase CopyData-------");
            if (src == this)
            {
                Console.WriteLine("Why? another me exists!");
                //System.Diagnostics.Debug.Assert(false);
                return;
            }

            // CadモードもUndo/Redo対象に入れる
            _CadMode = src._CadMode;
            // CadObj
            SerializedCadObjBuff = src.SerializedCadObjBuff;
            // LoopList
            LoopList.Clear();
            foreach (Loop srcLoop in src.LoopList)
            {
                Loop loop = new Loop(srcLoop);
                LoopList.Add(loop);
            }
            //check
            //foreach (EdgeCollection work in EdgeCollectionList)
            //{
            //    Console.WriteLine("  prev:No {0}  cnt {1}",  work.No, work.EdgeIds.Count);
            //}
            //foreach (EdgeCollection work in src.EdgeCollectionList)
            //{
            //    Console.WriteLine("  src:No {0}  cnt {1}", work.No, work.EdgeIds.Count);
            //}
            EdgeCollectionList.Clear();
            foreach (EdgeCollection srcEdge in src.EdgeCollectionList)
            {
                EdgeCollection edge = new EdgeCollection();
                edge.CP(srcEdge);
                EdgeCollectionList.Add(edge);
            }
            //check
            //foreach (EdgeCollection work in EdgeCollectionList)
            //{
            //    Console.WriteLine("  setted:No {0}  cnt {1}", work.No, work.EdgeIds.Count);
            //}

            // edit
            EditPts.Clear();
            foreach (CVector2D pp in src.EditPts)
            {
                EditPts.Add(pp);
            }
            // edit
            EditVertexIds.Clear();
            foreach (uint id_v in src.EditVertexIds)
            {
                EditVertexIds.Add(id_v);
            }
            // edit
            EditEdgeIds.Clear();
            foreach (uint id_e in src.EditEdgeIds)
            {
                EditEdgeIds.Add(id_e);
            }

            IncidentPortNo = src.IncidentPortNo;
            //SelectedMediaIndex = src.SelectedMediaIndex;
            for (int i = 0; i < src.Medias.Length; i++)
            {
                Medias[i].SetP(src.Medias[i].P);
                Medias[i].SetQ(src.Medias[i].Q);
            }
            //Console.WriteLine("-------CadLogicBase CopyData end----------");
        }
        /// <summary>
        /// Ver1.2.0.0形式の図面ファイルから読み込み(Ver1.2.0.0→Ver1.3.0.0の変換あり)
        /// </summary>
        /// <param name="in_filename"></param>
        /// <param name="isBackupFile">バックアップファイル?</param>
        /// <param name="out_cad2d">格納先Cadオブジェクトのリファレンス</param>
        /// <param name="out_LoopList">ループ情報のリスト</param>
        /// <param name="out_edgeCollectionList">ポートのエッジコレクションのリスト</param>
        /// <param name="out_incidentPortNo">入射ポート番号</param>
        /// <param name="out_medias">媒質情報リストのリファレンス(比誘電率、比透磁率だけセットされる)</param>
        /// <returns></returns>
        public static bool LoadFromFile_Ver_1_2(
            string in_filename,
            out bool isBackupFile,
            ref CCadObj2D out_cad2d,
            ref IList<CadLogic.Loop> out_LoopList,
            ref IList<EdgeCollection> out_edgeCollectionList,
            out int out_incidentPortNo,
            ref MediaInfo[] out_medias
            )
        {
            bool success = false;

            ////////////////////////////////////////////////////////
            // 出力データの初期化

            // バックアップファイル?
            isBackupFile = false;
            // 図面のクリア
            out_cad2d.Clear();
            // ループ情報リストの初期化
            out_LoopList.Clear();
            // 入射ポートの初期化
            out_incidentPortNo = 1;
            // ポートのエッジコレクションのリストを初期化
            out_edgeCollectionList.Clear();
            // 媒質の比誘電率、比透磁率の逆数の初期化
            foreach (MediaInfo media in out_medias)
            {
                // 比透磁率の逆数
                media.SetP(new double[,]
                    {
                        {1.0, 0.0, 0.0},
                        {0.0, 1.0, 0.0},
                        {0.0, 0.0, 1.0}
                    });
                // 比誘電率
                media.SetQ(new double[,]
                    {
                        {1.0, 0.0, 0.0},
                        {0.0, 1.0, 0.0},
                        {0.0, 0.0, 1.0}
                    });
            }

            ////////////////////////////////////////////////////////
            // バックアップファイルの作成
            string filename = "";
            if (in_filename.IndexOf(Ver1_2_Backup_Suffix) >= 0)
            {
                isBackupFile = true;
                MessageBox.Show("このファイルはバックアップファイルです。このファイルを上書き保存しないようご注意ください。",
                    "旧データ形式からの変換", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 入力ファイル名をそのまま利用
                filename = in_filename;
            }
            else
            {
                // 指定されたCadファイルとその入出力データをリネームする
                string basename = Path.GetDirectoryName(in_filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(in_filename);
                string inputfilename = basename + Constants.FemInputExt;
                string outputfilename = basename + Constants.FemOutputExt;
                string indexfilename = outputfilename + Constants.FemOutputIndexExt;
                //ReadOnlyにするのを止める
                ////FEM入出力データは移動しない(Ver1.2のアプリで再計算すると落ちるので止めます:データ削除でtry catchしていないのが原因だと思われる)
                //string[] tagtfilenames = { in_filename };
                // 全ファイルを移動する
                string[] tagtfilenames = { in_filename, inputfilename, outputfilename, indexfilename };
                foreach (string tagtfilename in tagtfilenames)
                {
                    string fname = Path.GetFileNameWithoutExtension(tagtfilename);
                    string ext = Path.GetExtension(tagtfilename);
                    if (fname != Path.GetFileNameWithoutExtension(fname)) // .out.idxの場合、ファイル名に.outまで入るので小細工する
                    {
                        string ext2 = Path.GetExtension(fname);
                        string fname2 = Path.GetFileNameWithoutExtension(fname);
                        ext = ext2 + ext;
                        fname = fname2;
                    }
                    string tagtbasename = Path.GetDirectoryName(tagtfilename) + Path.DirectorySeparatorChar + fname;
                    string backupFilename = tagtbasename + Ver1_2_Backup_Suffix + ext;
                    if (File.Exists(tagtfilename))
                    {
                        if (!File.Exists(backupFilename))
                        {
                            // 対象ファイルが存在し、かつバックアップファイルが存在しないとき
                            //バックアップファイルの作成
                            //MyUtilLib.MyUtil.MoveFileWithReadOnly(tagtfilename, backupFilename);
                            try
                            {
                                // そのまま移動(更新時刻等の再設定が面倒なのでコピーでなく移動する)
                                File.Move(tagtfilename, backupFilename);

                                // コピーとして戻す
                                File.Copy(backupFilename, tagtfilename);
                            }
                            catch (Exception exception)
                            {
                                System.Diagnostics.Debug.WriteLine(exception.Message + " " + exception.StackTrace);
                                MessageBox.Show(exception.Message);
                            }
                        }
                        else
                        {
                            // 対象ファイルは存在し、バックアップが存在するとき
                            // バックアップを作成できない
                            MessageBox.Show("すでに別のバックアップファイルがあるので、バックアップを作成できません。このファイルを上書き保存しないようご注意ください。",
                                "旧データ形式からの変換", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }

                // バックアップファイルに移動したので、バックアップファイルから読み込む
                filename = basename + Ver1_2_Backup_Suffix + Constants.CadExt;
            }

            // Ver1.2.0.0形式のファイルの読み込み
            Size maxDiv;
            bool[,] areaSelection;
            int[,] areaToMediaIndex;
            IList<CadDatFile_Ver_1_2.Edge_Ver_1_2> edgeList_Ver_1_2;
            bool[,] yBoundarySelection;
            bool[,] xBoundarySelection;
            int incidentPortNo_Ver_1_2;
            MediaInfo[] medias_Ver_1_2;

            bool loadSuccess = false;
            loadSuccess = CadDatFile_Ver_1_2.LoadFromFile_Ver_1_2(
                filename, out maxDiv, out areaSelection, out areaToMediaIndex,
                out edgeList_Ver_1_2, out yBoundarySelection, out xBoundarySelection,
                out incidentPortNo_Ver_1_2, out medias_Ver_1_2
                );
            if (!loadSuccess)
            {
                return success;
            }

            /////////////////////////////////////////////////////////////////////////////////
            // 本バージョンへのデータ変換
            /////////////////////////////////////////////////////////////////////////////////

            /////////////////////////////////////////////////////////////////////////////////
            // そのまま使用できる情報
            out_incidentPortNo = incidentPortNo_Ver_1_2;

            /////////////////////////////////////////////////////////////////////////////////
            // 変換が必要な情報
            // Medias --> インデックスを1加算
            // AreaToMediaIndex --> インデックスを1加算
            // AreaSelection, AreaToMediaIndex  --> loop
            // EdgeVer1_2 --> EdgeCollection

            //////////////////////////
            // 媒質情報は、Ver1.2→Ver1.3で媒質インデックスが1つずれる(導体が追加されたため)
            for (int oldMediaIndex = 0; oldMediaIndex < medias_Ver_1_2.Length; oldMediaIndex++)
            {
                if (oldMediaIndex + 1 < out_medias.Length)
                {
                    int mediaIndex = oldMediaIndex + 1;  //インデックスを1加算
                    out_medias[mediaIndex].SetP(medias_Ver_1_2[oldMediaIndex].P);
                    out_medias[mediaIndex].SetQ(medias_Ver_1_2[oldMediaIndex].Q);
                }
            }
            for (int y = 0; y < maxDiv.Height; y++)
            {
                for (int x = 0; x < maxDiv.Width; x++)
                {
                    areaToMediaIndex[y, x]++; //インデックスを1加算
                }
            }

            ///////////////////////////
            // 変換準備
            /*
            // 領域選択情報を媒質情報にマージする(非選択の場合もインデックスは0が設定されているがこれを-1に変更)
            for (int y = 0; y < maxDiv.Height; y++)
            {
                for (int x = 0; x < maxDiv.Width; x++)
                {
                    if (!areaSelection[y, x])
                    {
                        // エリアが選択されていない
                        areaToMediaIndex[y, x] = -1; // 未指定に設定する
                    }
                }
            }
             */
            // 非選択部分は導体媒質を設定する
            for (int y = 0; y < maxDiv.Height; y++)
            {
                for (int x = 0; x < maxDiv.Width; x++)
                {
                    if (!areaSelection[y, x])
                    {
                        // エリアが選択されていない
                        areaToMediaIndex[y, x] = CadLogic.MetalMediaIndex; // 導体を指定する
                    }
                }
            }

            // ループの取得
            IList<DelFEM4NetCom.Pair<int, IList<Point>>> loopList = getLoopList(maxDiv, areaToMediaIndex);

            // ループをエッジに変換
            IList<IList<CadDatFile_Ver_1_2.Edge_Ver_1_2>> loopEdgeListList = getLoopEdgeList(loopList);

            // ポート境界のエッジリスト分、エッジコレクションを先に作成する(複数のループにまたがる場合があるため)
            foreach (CadDatFile_Ver_1_2.Edge_Ver_1_2 portEdge in edgeList_Ver_1_2)
            {
                EdgeCollection edgeCollection = new EdgeCollection();
                edgeCollection.No = portEdge.No;
                out_edgeCollectionList.Add(edgeCollection);
            }

            var newLoopEdgeListList = new List<IList<CadDatFile_Ver_1_2.Edge_Ver_1_2>>();
            // ループ数分チェック
            foreach (IList<CadDatFile_Ver_1_2.Edge_Ver_1_2> loopEdgeList in loopEdgeListList)
            {
                // 1つのループ
                var newLoopEdgeList = new List<CadDatFile_Ver_1_2.Edge_Ver_1_2>();
                foreach (CadDatFile_Ver_1_2.Edge_Ver_1_2 loopEdge in loopEdgeList)
                {
                    // 1つのエッジ

                    // ポート境界を含んでいれば分解する
                    // 頂点リスト
                    IList<Point> vertexPts = new List<Point>();
                    // 頂点にポートが対応していれば、ポート番号を格納
                    // 既定値は -1
                    IList<int> toPortNo = new List<int>();

                    // エッジの最初の頂点を追加
                    vertexPts.Add(loopEdge.Points[0]);
                    toPortNo.Add(-1);

                    // ポート境界のエッジリストを走査
                    foreach (CadDatFile_Ver_1_2.Edge_Ver_1_2 portEdge in edgeList_Ver_1_2)
                    {
                        // contains?
                        Point minPt;
                        Point maxPt;
                        if (loopEdge.Contains(portEdge, out minPt, out maxPt))
                        {
                            // ポート境界が含まれていた
                            // ポート境界の頂点を追加
                            //vertexPts.Add(portEdge.Points[0]); // 始点
                            //vertexPts.Add(portEdge.Points[1]); // 終点
                            vertexPts.Add(minPt); // 始点
                            vertexPts.Add(maxPt); // 終点
                            // ポート番号を頂点にあわせて追加
                            toPortNo.Add(portEdge.No);
                            toPortNo.Add(portEdge.No);
                        }
                        else if (loopEdge.GetSimpleSwap().Contains(portEdge, out minPt, out maxPt))
                        {
                            // ポート境界の頂点を追加
                            //vertexPts.Add(portEdge.Points[1]);  // swap 終点
                            //vertexPts.Add(portEdge.Points[0]);  // swap 始点
                            vertexPts.Add(maxPt);  // swap 終点
                            vertexPts.Add(minPt);  // swap 始点
                            // ポート番号を頂点にあわせて追加
                            toPortNo.Add(portEdge.No);
                            toPortNo.Add(portEdge.No);
                        }
                    }
                    // 最後の頂点を追加
                    vertexPts.Add(loopEdge.Points[1]);
                    toPortNo.Add(-1);

                    // 頂点を元にしてエッジを再構築
                    for (int ino = 0; ino < vertexPts.Count - 1; ino++)
                    {
                        CadDatFile_Ver_1_2.Edge_Ver_1_2 work = new CadDatFile_Ver_1_2.Edge_Ver_1_2();
                        // ポート番号があれば格納
                        if (toPortNo[ino] != -1)
                        {
                            work.No = toPortNo[ino];
                        }
                        else
                        {
                            work.No = 0;
                        }
                        // 辺の始点、終点
                        work.Points[0] = vertexPts[ino];
                        work.Points[1] = vertexPts[ino + 1];
                        // Deltaの計算&格納
                        Point p1 = work.Points[0];
                        Point p2 = work.Points[1];
                        work.Delta = CadDatFile_Ver_1_2.Edge_Ver_1_2.CalcDelta(p1, p2);

                        // 空チェック
                        if (work.IsEmpty())
                        {
                            // 空の場合追加しない
                        }
                        else
                        {
                            // 追加
                            newLoopEdgeList.Add(work);
                        }
                    }
                    // 1つのエッジ再構築終了

                } // エッジ

                // 1つのループのエッジリストをリストに追加
                newLoopEdgeListList.Add(newLoopEdgeList);
            } // ループ

            ///////////////////////////////////////////////////////////////////
            // version1.3.0.0のデータ構造に反映する
            bool errorCCadObj = false;

            // ループ領域を作成
            //uint baseLoopId = 0;
            for (int loopIndex = 0; loopIndex < loopList.Count; loopIndex++)
            {
                System.Diagnostics.Debug.WriteLine("loopIndex: {0}", loopIndex);
                DelFEM4NetCom.Pair<int, IList<Point>> loop = loopList[loopIndex];
                // 媒質インデックス
                int mediaIndex = loop.First;
                // ループを構成する頂点
                IList<Point> pts = loop.Second;

                IList<CVector2D> pps = new List<CVector2D>();
                /*
                foreach (Point pt in pts)
                {
                    double xx = pt.X - maxDiv.Width * 0.5;
                    double yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                    pps.Add(new CVector2D(xx, yy));
                }
                 */
                // このループのエッジリストを取得する
                IList<CadDatFile_Ver_1_2.Edge_Ver_1_2> loopEdgeList = newLoopEdgeListList[loopIndex];

                // エッジのリストインデックス→エッジコレクションのリストのインデックス変換マップ
                IList<int> loopEdgeIndexToEdgeCollectionIndex = new List<int>();

                // OpenGlの頂点リストを作成
                for (int loopEdgeIndex = 0; loopEdgeIndex < loopEdgeList.Count; loopEdgeIndex++)
                {
                    // エッジ
                    CadDatFile_Ver_1_2.Edge_Ver_1_2 work = loopEdgeList[loopEdgeIndex];

                    ////////////////////////////////
                    // OpenGlの頂点作成
                    double xx;
                    double yy;
                    Point pt;
                    pt = work.Points[0]; //始点を追加していく
                    xx = pt.X - maxDiv.Width * 0.5;
                    yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                    pps.Add(new CVector2D(xx, yy));
                    System.Diagnostics.Debug.WriteLine("pps[{0}]: {1}, {2}", pps.Count - 1, pps[pps.Count - 1].x, pps[pps.Count - 1].y);

                    // check: 終点は次のエッジの始点のはず
                    if (loopEdgeIndex < loopEdgeList.Count - 1)
                    {
                        CadDatFile_Ver_1_2.Edge_Ver_1_2 next = loopEdgeList[loopEdgeIndex + 1];
                        System.Diagnostics.Debug.Assert(work.Points[1].Equals(next.Points[0]));
                    }

                    /* ループの最後の点は追加しない
                    if (loopEdgeIndex == loopEdgeList.Count - 1)
                    {
                        // 最後だけ終点を追加
                        pt = work.Points[1];
                        xx = pt.X - maxDiv.Width * 0.5;
                        yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                        pps.Add(new CVector2D(xx, yy));
                    }
                    */

                    int edgeCollectionIndex = -1;
                    if (work.No != 0)
                    {
                        ////////////////////////////////////////////////////////
                        // ポート情報がある場合
                        // check
                        {
                            EdgeCollection edgeCollection = out_edgeCollectionList[work.No - 1];
                            System.Diagnostics.Debug.Assert(work.No == edgeCollection.No);
                        }
                        // エッジコレクションリストのインデックスをセット
                        edgeCollectionIndex = work.No - 1;
                    }
                    // エッジのリストインデックス→エッジコレクションのリストのインデックス変換マップ(ポートがない場合も-1で追加する)
                    loopEdgeIndexToEdgeCollectionIndex.Add(edgeCollectionIndex);
                } // loopEdgeIndex

                uint id_l = 0;
                // 多角形でループを作成するのを止める
                //uint id_l = out_cad2d.AddPolygon(pps, baseLoopId).id_l_add;
                // 自力でループ作成
                System.Diagnostics.Debug.WriteLine("makeLoop: loopIndex: {0}", loopIndex);
                id_l = CadLogic.makeLoop(out_cad2d, pps, out_LoopList, false);
                if (id_l == 0)
                {
                    // 領域分割でできた領域は、現状取り込みを実装していません。
                    MessageBox.Show("領域の追加に失敗しました。");
                    errorCCadObj = true;
                }
                else
                {
                    //////////////////////////////////////////////////////////////////////
                    // 辺と頂点を取得
                    IList<uint> vIdList = null;
                    IList<uint> eIdList = null;
                    CadLogic.GetEdgeVertexListOfLoop(out_cad2d, id_l, out vIdList, out eIdList);
                    // 元々の辺のインデックスに対して生成された辺のIDのリストを要素とするリスト
                    IList<IList<uint>> generatedEIdsList = new List<IList<uint>>();
                    // ループ作成時に辺が分割された場合も考慮
                    int eIdIndexOfs = 0;
                    System.Diagnostics.Debug.WriteLine("pps[0]: {0},{1}", pps[0].x, pps[0].y);
                    {
                        Edge_Ver_1_2 loopEdge0 = loopEdgeList[0];
                        CVector2D loopEdge0_pp_v1;
                        CVector2D loopEdge0_pp_v2;
                        {
                            double xx;
                            double yy;
                            Point pt;
                            pt = loopEdge0.Points[0];
                            xx = pt.X - maxDiv.Width * 0.5;
                            yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                            loopEdge0_pp_v1 = new CVector2D(xx, yy);
                            pt = loopEdge0.Points[1];
                            xx = pt.X - maxDiv.Width * 0.5;
                            yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                            loopEdge0_pp_v2 = new CVector2D(xx, yy);
                        }
                        System.Diagnostics.Debug.WriteLine("loopEdge0_pp_v1: {0},{1} loopEdge0_pp_v2: {2},{3}", loopEdge0_pp_v1.x, loopEdge0_pp_v1.y, loopEdge0_pp_v2.x, loopEdge0_pp_v2.y);
                        for (int eIdIndexSearch = 0; eIdIndexSearch < eIdList.Count; eIdIndexSearch++)
                        {
                            uint id_e = eIdList[eIdIndexSearch];
                            bool isIncluding = CadLogic.isEdgeIncludingEdge(out_cad2d, loopEdge0_pp_v1, loopEdge0_pp_v2, id_e);
                            if (isIncluding)
                            {
                                eIdIndexOfs = eIdIndexSearch;
                                break;
                            }
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("eIdIndexOfs:{0}", eIdIndexOfs);

                    for (int loopEdgeIndex = 0; loopEdgeIndex < loopEdgeList.Count; loopEdgeIndex++)
                    {
                        IList<uint> generatedEIds = new List<uint>();
                        Edge_Ver_1_2 loopEdge = loopEdgeList[loopEdgeIndex];
                        CVector2D loopEdge_pp_v1;
                        CVector2D loopEdge_pp_v2;
                        {
                            double xx;
                            double yy;
                            Point pt;
                            pt = loopEdge.Points[0];
                            xx = pt.X - maxDiv.Width * 0.5;
                            yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                            loopEdge_pp_v1 = new CVector2D(xx, yy);
                            pt = loopEdge.Points[1];
                            xx = pt.X - maxDiv.Width * 0.5;
                            yy = maxDiv.Height - pt.Y - maxDiv.Height * 0.5;
                            loopEdge_pp_v2 = new CVector2D(xx, yy);
                        }
                        System.Diagnostics.Debug.WriteLine("  loopEdgeIndex:{0}", loopEdgeIndex);
                        System.Diagnostics.Debug.WriteLine("    loopEdge_pp_v1: {0},{1} loopEdge0_pp_v2: {2},{3}", loopEdge_pp_v1.x, loopEdge_pp_v1.y, loopEdge_pp_v2.x, loopEdge_pp_v2.y);
                        for (int eIdIndex = 0; eIdIndex < eIdList.Count; eIdIndex++)
                        {
                            uint id_e = eIdList[(eIdIndex + eIdIndexOfs) % eIdList.Count]; // 1つずらして取得
                            //System.Diagnostics.Debug.WriteLine("            {0} id_e:{1}", (eIdIndex + eIdIndexOfs) % eIdList.Count, id_e);
                            bool isIncluding = CadLogic.isEdgeIncludingEdge(out_cad2d, loopEdge_pp_v1, loopEdge_pp_v2, id_e);
                            if (!isIncluding)
                            {
                                continue;
                            }
                            generatedEIds.Add(id_e);
                            // check
                            {
                                uint id_v1 = 0;
                                uint id_v2 = 0;
                                CadLogic.getVertexIdsOfEdgeId(out_cad2d, id_e, out id_v1, out id_v2);
                                CVector2D pp_v1 = out_cad2d.GetVertexCoord(id_v1);
                                CVector2D pp_v2 = out_cad2d.GetVertexCoord(id_v2);
                                System.Diagnostics.Debug.WriteLine("    eId: {0}, pp_v1: {1},{2} pp_v2: {3},{4}", id_e, pp_v1.x, pp_v1.y, pp_v2.x, pp_v2.y);
                            }
                        }
                        generatedEIdsList.Add(generatedEIds);
                    }

                    ///////////////////////////////////////////////////////////////////////
                    // エッジコレクションにポート境界に対応する辺のIDをセットする
                    //IList<EdgeCollection> workEdgeCollectionList = new List<EdgeCollection>();  // ここで辺のIDをセットしたコレクションを辺の色付けのために一時保管する
                    for (int loopEdgeIndex = 0; loopEdgeIndex < loopEdgeList.Count; loopEdgeIndex++)
                    {
                        int edgeCollectionIndex = loopEdgeIndexToEdgeCollectionIndex[loopEdgeIndex];
                        if (edgeCollectionIndex != -1)
                        {
                            //
                            EdgeCollection edgeCollection = out_edgeCollectionList[edgeCollectionIndex];
                            IList<uint> generatedEIds = generatedEIdsList[loopEdgeIndex];
                            foreach (uint id_e in generatedEIds)
                            {
                                // 辺のIDをエッジコレクションにセット
                                // 辺の連続性はここではチェックしない(ばらばらで追加されるので)
                                bool chkFlg = false;
                                if (!edgeCollection.ContainsEdgeId(id_e))
                                {
                                    bool ret = edgeCollection.AddEdgeId(id_e, out_cad2d, chkFlg);
                                }
                            }

                            // 一時保管
                            //workEdgeCollectionList.Add(edgeCollection);
                        }
                    }
                    ////////////////////////////////////////////////////////////////////////
                    // 最初のループならばそのIdを記録する
                    //if (baseLoopId == 0)
                    //{
                    //    baseLoopId = id_l;
                    //}
                    // ループの情報を追加する
                    out_LoopList.Add(new CadLogic.Loop(id_l, mediaIndex));

                    // まだ処理が完全でないので下記は処理しない
                    // ループの内側にあるループを子ループに設定する
                    //CadLogic.reconstructLoopsInsideLoopAsChild(out_cad2d, id_l, ref out_LoopList, ref out_edgeCollectionList, out_medias, ref out_incidentPortNo);

                    ////////////////////////////////////////////////////////////////////////
                    // Cadオブジェクトの色をセットする
                    // ループとその辺、頂点の色をセット
                    MediaInfo media = out_medias[mediaIndex];
                    Color backColor = media.BackColor;
                    CadLogic.SetupColorOfCadObjectsForOneLoop(out_cad2d, id_l, backColor);
                    // ポートの色をセットする
                    //CadLogic.SetupColorOfPortEdgeCollection(out_cad2d, workEdgeCollectionList, incidentPortNo_Ver_1_2);
                } // if id_l != 0
            } // loopIndex

            // 番号順に並び替え
            ((List<EdgeCollection>)out_edgeCollectionList).Sort();
            // エッジコレクションの辺IDリストをソートする
            foreach (EdgeCollection workEdgeCollection in out_edgeCollectionList)
            {
                bool ret = workEdgeCollection.SortEdgeIds(out_cad2d);
            }

            // ポートの色をセットする
            CadLogic.SetupColorOfPortEdgeCollection(out_cad2d, out_edgeCollectionList, out_incidentPortNo);

            /////////////////////////////////////////////
            // 外側の導体媒質ループ削除処理
            //
            // 外側の導体媒質ループを取得する
            IList<CadLogic.Loop> delLoopList = new List<CadLogic.Loop>();
            foreach (CadLogic.Loop loop in out_LoopList)
            {
                if (loop.MediaIndex == CadLogic.MetalMediaIndex) // 導体の場合のみ実行
                {
                    // 外側の判定 --->他のループと共有していない辺が存在する
                    IList<uint> vIdList = null;
                    IList<uint> eIdList = null;
                    CadLogic.GetEdgeVertexListOfLoop(out_cad2d, loop.LoopId, out vIdList, out eIdList);

                    bool notSharedEdgeExists = false;
                    foreach (uint eId in eIdList)
                    {
                        if (CadLogic.isEdgeSharedByLoops(out_cad2d, eId))
                        {
                            // 辺を2つのループで共有している
                        }
                        else
                        {
                            // 辺を共有していない
                            notSharedEdgeExists = true;
                            break;
                        }
                    }
                    if (notSharedEdgeExists)
                    {
                        delLoopList.Add(loop);
                    }
                }
            }
            // 外側の導体媒質ループを削除
            foreach (CadLogic.Loop deltarget in delLoopList)
            {
                CadLogic.delLoop(out_cad2d, deltarget.LoopId, ref out_LoopList, ref out_edgeCollectionList, out_medias, ref out_incidentPortNo);
            }

            if (errorCCadObj)
            {
                success = false;
            }
            else
            {
                success = true;
            }
            return success;
        }
 /// <summary>
 /// Creates a new GeometryGraph.
 /// </summary>
 public GeometryGraph()
 {
     this.nodes = new NodeCollection(this);
     this.edges = new EdgeCollection(this);
     this.rootCluster = new Cluster();
 }
        /// <summary>
        /// 図面情報を読み込む
        /// </summary>
        /// <returns></returns>
        public static bool LoadFromFile(
            string filename,
            out string appVersion,
            out string useUtility,
            ref CCadObj2D editCad2D,
            ref IList<CadLogic.Loop> loopList,
            ref IList<EdgeCollection> edgeCollectionList,
            out int incidentPortNo,
            ref MediaInfo[] medias
            )
        {
            bool success = false;

            ////////////////////////////////////////////////////////
            // 出力データの初期化

            // アプリケーションのバージョン番号
            appVersion = "";
            // ユーティリティ名
            useUtility = "";

            // 図面のクリア
            editCad2D.Clear();
            //// ベースループIDを初期化
            //baseLoopId = 0;
            // ループ情報リストの初期化
            loopList.Clear();
            // 入射ポートの初期化
            incidentPortNo = 1;
            // ポートのエッジコレクションのリストを初期化
            edgeCollectionList.Clear();
            // 媒質の比誘電率、比透磁率の逆数の初期化
            foreach (MediaInfo media in medias)
            {
                // 比透磁率の逆数
                media.SetP(new double[,]
                    {
                        {1.0, 0.0, 0.0},
                        {0.0, 1.0, 0.0},
                        {0.0, 0.0, 1.0}
                    });
                // 比誘電率
                media.SetQ(new double[,]
                    {
                        {1.0, 0.0, 0.0},
                        {0.0, 1.0, 0.0},
                        {0.0, 0.0, 1.0}
                    });
            }

            try
            {
                // Cadオブジェクトデータファイル
                string basename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename);
                string cadObjFilename = basename + Constants.CadObjExt;

                if (File.Exists(cadObjFilename))
                {
                    // Cadオブジェクトデータを外部ファイルから読み込む
                    using (CSerializer fin = new CSerializer(cadObjFilename, true))
                    {
                        editCad2D.Serialize(fin);
                    }
                }
                else
                {
                    MessageBox.Show("CadObjデータファイルがありません");
                    return success;
                }

                using (StreamReader sr = new StreamReader(filename))
                {
                    string line;
                    string[] tokens;
                    const char delimiter = ',';
                    int cnt = 0;

                    // アプリケーションのバージョン番号
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("アプリケーションのバージョン情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "AppVersion")
                    {
                        MessageBox.Show("アプリケーションのバージョン情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    appVersion = tokens[1];

                    // ユーティリティ名
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("ユーティリティ情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "UseUtility")
                    {
                        MessageBox.Show("ユーティリティ情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    useUtility = tokens[1];
                    if (useUtility != CadLogic.UseUtility)
                    {
                        MessageBox.Show("ユーティリティ情報が本アプリケーションのバージョンのものと一致しません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }

                    // ベースループID
                    //line = sr.ReadLine();
                    //if (line == null)
                    //{
                    //    MessageBox.Show("ベースループIDがありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return success;
                    //}
                    //tokens = line.Split(delimiter);
                    //if (tokens.Length != 2 || tokens[0] != "BaseLoopId")
                    //{
                    //    MessageBox.Show("ベースループIDがありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return success;
                    //}
                    //baseLoopId = uint.Parse(tokens[1]);

                    // ループのリスト
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("ループ一覧がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "LoopList")
                    {
                        MessageBox.Show("ループ一覧がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    cnt = int.Parse(tokens[1]);
                    for (int i = 0; i < cnt; i++)
                    {
                        line = sr.ReadLine();
                        if (line == null)
                        {
                            MessageBox.Show("ループ情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return success;
                        }
                        tokens = line.Split(delimiter);
                        if (tokens.Length != 4 || tokens[0] != "Loop")
                        {
                            MessageBox.Show("ループ情報が不正です", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return success;
                        }
                        int countNo = int.Parse(tokens[1]);
                        uint loopId = uint.Parse(tokens[2]);
                        int mediaIndex = int.Parse(tokens[3]);
                        System.Diagnostics.Debug.Assert(countNo == i + 1);

                        CadLogic.Loop loop = new CadLogicBase.Loop(loopId, mediaIndex);
                        loopList.Add(loop);
                    }

                    // ポートのエッジコレクションのリスト
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("ポート一覧がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "EdgeCollectionList")
                    {
                        MessageBox.Show("ポート一覧がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return success;
                    }
                    cnt = int.Parse(tokens[1]);
                    for (int i = 0; i < cnt; i++)
                    {
                        line = sr.ReadLine();
                        if (line == null)
                        {
                            MessageBox.Show("ポート情報がありません", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return success;
                        }
                        tokens = line.Split(delimiter);
                        if (tokens.Length < (4 + 1) || tokens[0] != "EdgeCollection")
                        {
                            MessageBox.Show("ポート情報が不正です", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return success;
                        }
                        int countNo = int.Parse(tokens[1]);
                        int portNo = int.Parse(tokens[2]);
                        int eIdCnt = int.Parse(tokens[3]);
                        System.Diagnostics.Debug.Assert(countNo == i + 1);
                        System.Diagnostics.Debug.Assert(eIdCnt != 0 && eIdCnt == (tokens.Length - 4));

                        EdgeCollection edgeCollection = new EdgeCollection();
                        edgeCollection.No = portNo;
                        for (int tokenIndex = 4; tokenIndex < tokens.Length; tokenIndex++)
                        {
                            uint eId = uint.Parse(tokens[tokenIndex]);
                            if (!edgeCollection.ContainsEdgeId(eId))
                            {
                                bool ret = edgeCollection.AddEdgeId(eId, editCad2D);
                            }
                        }
                        edgeCollectionList.Add(edgeCollection);
                    }

                    // 入射ポート番号
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("入射ポート番号がありません");
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "IncidentPortNo")
                    {
                        MessageBox.Show("入射ポート番号がありません");
                        return success;
                    }
                    incidentPortNo = int.Parse(tokens[1]);

                    // 媒質情報
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        MessageBox.Show("媒質情報がありません");
                        return success;
                    }
                    tokens = line.Split(delimiter);
                    if (tokens.Length != 2 || tokens[0] != "Medias")
                    {
                        MessageBox.Show("媒質情報がありません");
                        return success;
                    }
                    cnt = int.Parse(tokens[1]);
                    for (int i = 0; i < cnt; i++)
                    {
                        line = sr.ReadLine();
                        if (line == null)
                        {
                            MessageBox.Show("媒質情報が不正です");
                            return success;
                        }
                        tokens = line.Split(delimiter);
                        if (tokens.Length != 1 + 9 + 9)
                        {
                            MessageBox.Show("媒質情報が不正です");
                            return success;
                        }
                        int mediaIndex = int.Parse(tokens[0]);
                        System.Diagnostics.Debug.Assert(mediaIndex == i);
                        if (i >= medias.Length)
                        {
                            //読み飛ばす
                            continue;
                        }
                        double[,] p = new double[3, 3];
                        for (int m = 0; m < p.GetLength(0); m++)
                        {
                            for (int n = 0; n < p.GetLength(1); n++)
                            {
                                p[m, n] = double.Parse(tokens[1 + m * p.GetLength(1) + n]);
                            }
                        }
                            medias[i].SetP(p);

                        double[,] q = new double[3, 3];
                        for (int m = 0; m < q.GetLength(0); m++)
                        {
                            for (int n = 0; n < q.GetLength(1); n++)
                            {
                                q[m, n] = double.Parse(tokens[1 + 9 + m * q.GetLength(1) + n]);
                            }
                        }
                        medias[i].SetQ(q);
                    }
                }

                // 番号順に並び替え
                ((List<EdgeCollection>)edgeCollectionList).Sort();

                ////////////////////////////////////////////////////////////////////////
                // Cadオブジェクトの色をセットする
                // ループとその辺、頂点の色をセット
                foreach (CadLogic.Loop loop in loopList)
                {
                    uint id_l = loop.LoopId;
                    int mediaIndex = loop.MediaIndex;
                    MediaInfo media = medias[mediaIndex];
                    Color backColor = media.BackColor;
                    CadLogic.SetupColorOfCadObjectsForOneLoop(editCad2D, id_l, backColor);
                }
                // ポートの色をセットする
                CadLogic.SetupColorOfPortEdgeCollection(editCad2D, edgeCollectionList, incidentPortNo);

                success = true;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message + " " + exception.StackTrace);
                MessageBox.Show(exception.Message);
            }

            return success;
        }