Example #1
0
        protected static bool Parallel([NotNull] Pnt p0,
                                       [NotNull] Pnt l0,
                                       [NotNull] Pnt p1,
                                       [NotNull] Pnt l1,
                                       double r2,
                                       out double tMin, out double tMax,
                                       ref NearSegment hullStartNear,
                                       ref NearSegment hullEndNear)
        {
            if (SegmentUtils.CutLineCircle(p0, l0, p1, r2, out tMin, out tMax) == false)
            {
                return(false);
            }

            hullStartNear = Near(tMin, tMax);

            double cMin, cMax;

            if (SegmentUtils.CutLineCircle(p0, l0, p1 + l1, r2, out cMin, out cMax))
            {
                hullEndNear = Near(cMin, cMax);

                tMin = Math.Min(tMin, cMin);
                tMax = Math.Max(tMax, cMax);
            }

            return(true);
        }
Example #2
0
        private Box GetBox([NotNull] BoxTile tile)
        {
            Pnt     min      = Pnt.Create(_dimension);
            Pnt     max      = Pnt.Create(_dimension);
            var     handled  = new bool[_dimension];
            var     nHandled = 0;
            BoxTile t        = tile;

            while (t.Parent != null && nHandled < _dimension)
            {
                if (!handled[t.Parent.SplitDimension])
                {
                    min[t.Parent.SplitDimension]     = t.MinInParentSplitDim;
                    max[t.Parent.SplitDimension]     = t.MaxInParentSplitDim;
                    handled[t.Parent.SplitDimension] = true;
                    nHandled++;
                }

                t = t.Parent;
            }

            if (nHandled < _dimension)
            {
                for (var iHandled = 0; iHandled < _dimension; iHandled++)
                {
                    if (!handled[iHandled])
                    {
                        min[iHandled] = _mainBox.Min[iHandled];
                        max[iHandled] = _mainBox.Max[iHandled];
                    }
                }
            }

            return(new Box(min, max));
        }
Example #3
0
        public static bool CutCurveCircle([NotNull] SegmentProxy segmentProxy,
                                          [NotNull] Pnt circleCenter,
                                          double r2, bool as3D,
                                          out IList <double[]> limits)
        {
            if (segmentProxy.IsLinear)
            {
                double tMin;
                double tMax;
                bool   cut = as3D
                                                   ? CutLineCircle3D(segmentProxy, circleCenter, r2,
                                                                     out tMin, out tMax)
                                                   : CutLineCircle2D(segmentProxy, circleCenter, r2,
                                                                     out tMin, out tMax);

                limits = new List <double[]>();
                if (cut && tMin < 1 && tMax > 0)
                {
                    limits.Add(new[] { tMin, tMax });
                }

                return(cut);
            }

            return(CutCurveCircle(segmentProxy, circleCenter, r2, out limits));
        }
Example #4
0
 public override void move(Pnt lastWorldPos, Pnt lastViewPos, Pnt dstWorld, Pnt dstView)
 {
     if (MiddleMouseIsDown)
     {
         Diagram.translate(dstWorld);
     }
 }
        //--------------------------------------------------------------------------------------------------

        public Pnt ProjectToGrid(Pnt point)
        {
            double px = 0, py = 0, pz = 0;

            V3dView.ConvertToGrid(point.X, point.Y, point.Z, ref px, ref py, ref pz);
            return(new Pnt(px, py, pz));
        }
        //--------------------------------------------------------------------------------------------------

        public bool ScreenToPoint(Pln plane, int screenX, int screenY, out Pnt resultPnt)
        {
            try
            {
                double xv = 0, yv = 0, zv = 0;
                double vx = 0, vy = 0, vz = 0;

                V3dView.Convert(screenX, screenY, ref xv, ref yv, ref zv);
                V3dView.Proj(ref vx, ref vy, ref vz);

                gp_Lin line = new gp_Lin(new Pnt(xv, yv, zv), new Dir(vx, vy, vz));
                IntAna_IntConicQuad intersection = new IntAna_IntConicQuad(line, plane, Precision.Angular(), 0, 0);

                if (intersection.IsDone() &&
                    !intersection.IsParallel() &&
                    intersection.NbPoints() > 0)
                {
                    resultPnt = intersection.Point(1);
                    return(true);
                }
            }
            catch (Exception)
            {
                Debug.Assert(false);
            }

            resultPnt = new Pnt();
            return(false);
        }
        //--------------------------------------------------------------------------------------------------

        void _FinishPivotPoint(ToolAction toolAction)
        {
            if (!(toolAction is PointAction pointAction))
            {
                return;
            }

            _Plane       = WorkspaceController.Workspace.WorkingPlane;
            _PointPlane1 = pointAction.PointOnPlane;
            _PivotPoint  = pointAction.Point;

            pointAction.Stop();
            pointAction = new PointAction(this);
            if (!WorkspaceController.StartToolAction(pointAction))
            {
                return;
            }
            pointAction.Previewed += _PreviewRadius;
            pointAction.Finished  += _FinishRadius;

            _CurrentPhase = Phase.Radius;
            StatusText    = "Select radius.";

            _ValueHudElement = WorkspaceController.HudManager?.CreateElement <ValueHudElement>(this);
            if (_ValueHudElement != null)
            {
                _ValueHudElement.Label         = "Radius:";
                _ValueHudElement.Units         = ValueUnits.Length;
                _ValueHudElement.ValueEntered += _ValueEntered;
            }

            WorkspaceController.HudManager?.SetCursor(Cursors.SetRadius);
        }
Example #8
0
        public LineHullPart(Pnt p0, Pnt p1)
        {
            _p0 = p0;
            _p1 = p1;

            _lin = new Lin2D(p0, p1);
        }
                private void WriteBox(StringBuilder s, string ctx, Box box, Box x, double f,
                                      double lineWidth = 1, string color = null)
                {
                    Pnt min = (1.0 / f) * (Pnt.Create(box.Min) - x.Min);
                    Pnt max = (1.0 / f) * (Pnt.Create(box.Max) - x.Min);

                    s.AppendFormat("{0}.save();", ctx);
                    s.AppendLine();
                    s.AppendFormat("{0}.lineWidth = {1:N0};", ctx, lineWidth);
                    s.AppendLine();
                    if (!string.IsNullOrEmpty(color))
                    {
                        s.AppendFormat("{0}.strokeStyle = '{1}';", ctx, color);
                        s.AppendLine();
                    }

                    s.AppendFormat("{0}.beginPath();", ctx);
                    s.AppendLine();
                    s.AppendFormat("{0}.moveTo({1:N1},{2:N1});", ctx, min.X, min.Y);
                    s.AppendLine();
                    s.AppendFormat("{0}.lineTo({1:N1},{2:N1});", ctx, min.X, max.Y);
                    s.AppendLine();
                    s.AppendFormat("{0}.lineTo({1:N1},{2:N1});", ctx, max.X, max.Y);
                    s.AppendLine();
                    s.AppendFormat("{0}.lineTo({1:N1},{2:N1});", ctx, max.X, min.Y);
                    s.AppendLine();
                    s.AppendFormat("{0}.lineTo({1:N1},{2:N1});", ctx, min.X, min.Y);
                    s.AppendLine();
                    s.AppendFormat("{0}.stroke();", ctx);
                    s.AppendLine();
                    s.AppendFormat("{0}.restore();", ctx);
                    s.AppendLine();
                }
        //--------------------------------------------------------------------------------------------------

        void _FinishPivotPoint(ToolAction toolAction)
        {
            if (!(toolAction is PointAction pointAction))
            {
                return;
            }

            _Point = pointAction.Point.Round();
            pointAction.Stop();

            var axisValueAction = new AxisValueAction(this, new Ax1(_Point, Dir.DZ));

            if (!WorkspaceController.StartToolAction(axisValueAction))
            {
                return;
            }
            axisValueAction.Previewed += _PreviewRadius;
            axisValueAction.Finished  += _FinishRadius;

            _CurrentPhase = Phase.Radius;
            StatusText    = "Select Radius.";

            WorkspaceController.HudManager?.RemoveElement(_Coord2DHudElement);
            _ValueHudElement = WorkspaceController.HudManager?.CreateElement <ValueHudElement>(this);
            if (_ValueHudElement != null)
            {
                _ValueHudElement.Label         = "Radius:";
                _ValueHudElement.Units         = ValueUnits.Length;
                _ValueHudElement.ValueEntered += _ValueEntered;
            }

            WorkspaceController.HudManager?.SetCursor(Cursors.SetRadius);
        }
Example #11
0
        protected override bool CutLineHull(
            double centerOffset,
            double r2, double tolerance,
            out double tMin, out double tMax,
            out NearSegment hullStartNear,
            out NearSegment hullEndNear,
            out bool coincident)
        {
            coincident = IsCoincident(tolerance, out hullStartNear, out hullEndNear);
            if (!coincident)
            {
                Pnt offset = P0s;
                if (centerOffset != 0)
                {
                    offset = P0s + centerOffset * L0Normal;
                }

                bool cut = CutLineHull2D(offset, L0, P1s, L1, r2, out tMin, out tMax,
                                         out hullStartNear, out hullEndNear);

                return(cut);
            }

            tMin = -Math.Sqrt(r2 / L0.OrigDist2());
            tMax = 1 - tMin;
            return(true);
        }
            public NeighborhoodEnumerator([NotNull] BoxTree searchingTree,
                                          [NotNull] BoxTree neighbourTree,
                                          double searchDistance, [CanBeNull] IBox common)
            {
                _searchingTree  = searchingTree;
                _neighbourTree  = neighbourTree;
                _searchDistance = searchDistance;

                Pnt min = Pnt.Create(_searchingTree._unitBox.Min);
                Pnt max = Pnt.Create(_searchingTree._unitBox.Max);

                for (var i = 0; i < min.Dimension; i++)
                {
                    min[i] = Math.Max(min[i], _neighbourTree._unitBox.Min[i]);
                    if (common != null)
                    {
                        min[i] = Math.Max(min[i], common.Min[i]);
                    }

                    min[i] -= searchDistance;

                    max[i] = Math.Min(max[i], _neighbourTree._unitBox.Max[i]);
                    if (common != null)
                    {
                        max[i] = Math.Min(max[i], common.Max[i]);
                    }

                    max[i] += searchDistance;
                }

                _common = new Box(min, max);

                Reset();
            }
Example #13
0
        public Dictionary <SourceType, double> getEffectAtPoint(Pnt point, SourceType[] stypes)
        {
            Dictionary <SourceType, double> effects = new Dictionary <SourceType, double>();

            foreach (SourceType stype in stypes)
            {
                effects[stype] = 0;
            }
            foreach (SourcePoint sp in sourcePoints.Values)
            {
                if (!effects.ContainsKey(sp.sourceType))
                {
                    continue;
                }

                double dist = Vector.GetLength(point, sp.location);
                if (dist == 0)
                {
                    continue;
                }
                double coeff = 1 / dist;
                effects[sp.sourceType] += coeff * sp.strength;
            }
            return(effects);
        }
Example #14
0
        private static IEnumerable <HullLine> GetLineHullParts(Lin2D lin, SegmentHull hull)
        {
            Pnt leftOffset = hull.LeftOffset * lin.LNormal;

            yield return(new HullLineSimple
            {
                Lin = lin.GetParallel(leftOffset), CutPart = CutPart.LeftSide
            });

            Pnt rightOffset = -hull.RightOffset * lin.LNormal;

            yield return(new HullLineSimple
            {
                Lin = lin.GetParallel(rightOffset), CutPart = CutPart.RightSide
            }
                         );

            double meanOffset = (hull.LeftOffset + hull.RightOffset) / 2;
            Pnt    capOffset  = (hull.LeftOffset - hull.RightOffset) / 2 * lin.LNormal;
            Lin2D  centerLin  = lin.GetParallel(capOffset);

            foreach (HullLine startPart in hull.StartCap.GetHullLines(
                         centerLin, meanOffset, atEnd: false))
            {
                startPart.CutPart = CutPart.StartCap;
                yield return(startPart);
            }

            foreach (HullLine endPart in hull.EndCap.GetHullLines(centerLin, meanOffset,
                                                                  atEnd: true))
            {
                endPart.CutPart = CutPart.EndCap;
                yield return(endPart);
            }
        }
Example #15
0
        public void BaryCenter()
        {
            var p1 = new Pnt(0, 2, 4);

            p1.BaryCenter(2, new Pnt(1, 2, 3), 5);
            Assert.IsTrue(p1.IsEqual(new Pnt(0.71428, 2, 3.28571), 0.00001));
        }
Example #16
0
        private void SetViewDirection(Inventor.Face FaceView)
        {
            Inventor.Camera Camera = mInvApplication.ActiveView.Camera;
            Inventor.Point  Pnt;
            Inventor.View   PlaneView = mInvApplication.ActiveView;
            //  ' Set Eye or Target
            if (FaceView.IsParamReversed)
            {
                Pnt = Camera.Eye.Copy();
                Pnt.TranslateBy(GetMidPointAtFaceNormal(ref FaceView).AsVector());
                Camera.Target = Pnt;
            }
            else
            {
                Pnt = Camera.Target.Copy();
                Pnt.TranslateBy(GetMidPointAtFaceNormal(ref FaceView).AsVector());
                Camera.Eye = Pnt;
            }

            Camera.UpVector = GetLargestEdgeUnitVector(ref FaceView);
            Camera.Fit();
            Camera.Apply();
            PlaneView.SetCurrentAsTop();
            PlaneView.SetCurrentAsHome(true);
            PlaneView.Update();
        }
        //--------------------------------------------------------------------------------------------------

        public static Pnt2d Parameters(this Pln pln, Pnt pnt)
        {
            double u = 0, v = 0;

            ElSLib.Parameters(pln, pnt, ref u, ref v);
            return(new Pnt2d(u, v));
        }
 public NullableClass(bool fill)
 {
     V1 = null;
     V2 = 1.0;
     V3 = null;
     V4 = new Pnt(1, 2, 3);
 }
Example #19
0
        public override IEnumerable <HullLine> GetHullLines(Lin2D lin, double meanOffset,
                                                            bool atEnd)
        {
            double l       = atEnd ? _length : -_length;
            Pnt    offset  = l * lin.L;
            Pnt    rOffset = -meanOffset * lin.LNormal;
            Pnt    lOffset = meanOffset * lin.LNormal;

            yield return(new HullLineLine
            {
                Lin = lin.GetParallel(offset),
                EndPart = new Lin2D(rOffset, lOffset),
            });

            if (Math.Abs(l) > 1.0e-8)
            {
                var endPart = new Lin2D(new Pnt2D(), offset);
                yield return
                    (new HullLineLine {
                    Lin = lin.GetParallel(lOffset), EndPart = endPart
                });

                yield return
                    (new HullLineLine {
                    Lin = lin.GetParallel(rOffset), EndPart = endPart
                });
            }
        }
        public static void exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat)   //输出栅格数据
        {
            string            directory        = parth.Substring(0, parth.LastIndexOf("\\"));
            string            name             = parth.Substring(parth.LastIndexOf("\\") + 1);
            IWorkspaceFactory workspaceFac     = new RasterWorkspaceFactoryClass();
            IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2;

            IRasterInfo rasterInfo  = (rasterLayer.Raster as IRawBlocks).RasterInfo;
            IPoint      originPoint = new Point();

            originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y);
            IRasterProps   rasterProps   = rasterLayer.Raster as IRasterProps;
            IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height,
                                                                                rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true) as IRasterDataset2;

            IRaster2 raster2 = rasterDataSet.CreateDefaultRaster() as IRaster2;

            IPnt pntClass = new Pnt();

            pntClass.X = rasterProps.Width;
            pntClass.Y = rasterProps.Height;
            IRasterCursor rasterCursor   = raster2.CreateCursorEx(pntClass);
            IRasterCursor inRasterCursor = (rasterLayer.Raster as IRaster2).CreateCursorEx(pntClass);

            IRasterEdit rasterEdit = raster2 as IRasterEdit;

            if (rasterEdit.CanEdit())
            {
                IPixelBlock3 pixelBlock3   = rasterCursor.PixelBlock as IPixelBlock3;
                IPixelBlock3 inPixelBlock3 = inRasterCursor.PixelBlock as IPixelBlock3;
                System.Array pixels        = (System.Array)rasterMat;
                pixelBlock3.set_PixelData(0, (System.Array)pixels);
                rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pixelBlock3);
            }
            rasterEdit.Refresh();
            IGeoDataset   inDataset   = rasterLayer.Raster as IGeoDataset;
            IGeoDataset   outDataset  = rasterDataSet as IGeoDataset;
            IExtractionOp op          = new RasterExtractionOpClass();
            var           outDataset1 = op.Raster(outDataset, inDataset);
            var           clipRaster  = (IRaster)outDataset1;
            ISaveAs       pSaveAs     = clipRaster as ISaveAs;

            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(raster2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataSet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWorkspace2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFac);
            if (File.Exists(parth))
            {
                File.Delete(parth);
            }
            workspaceFac = new RasterWorkspaceFactoryClass();
            IDataset outdataset = pSaveAs.SaveAs(name, workspaceFac.OpenFromFile(directory, 0), "IMAGINE Image");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(outdataset);
            return;
        }
Example #21
0
        public void TranslatePntPnt()
        {
            var p1 = new Pnt(1, 2, 3);

            Assert.AreEqual(new Pnt(0, 2, 4), p1.Translated(new Pnt(2, 2, 2), new Pnt(1, 2, 3)));
            p1.Translate(new Pnt(2, 2, 2), new Pnt(1, 2, 3));
            Assert.AreEqual(new Pnt(0, 2, 4), p1);
        }
Example #22
0
        //--------------------------------------------------------------------------------------------------

        public void Set(Pnt p1, Pnt p2)
        {
            _P1       = new Geom_CartesianPoint(p1);
            _P2       = new Geom_CartesianPoint(p2);
            _GeomLine = null;

            Update();
        }
Example #23
0
        private static Pnt GetPoint(WKSPointZ wks, bool as3D)
        {
            Pnt p = !as3D
                                        ? (Pnt) new Pnt2D(wks.X, wks.Y)
                                        : new Pnt3D(wks.X, wks.Y, wks.Z);

            return(p);
        }
Example #24
0
        public void Distance()
        {
            var p1 = new Pnt(1, 2, 3);
            var p2 = new Pnt(4, 5, 6);

            Assert.AreEqual(27, p1.SquareDistance(p2));
            Assert.AreEqual(Math.Sqrt(27), p1.Distance(p2));
        }
        //--------------------------------------------------------------------------------------------------

        public void RestoreViewParameters(double[] parameters)
        {
            Debug.Assert(parameters.Length == 8);
            EyePoint    = new Pnt(parameters[0], parameters[1], parameters[2]);
            TargetPoint = new Pnt(parameters[3], parameters[4], parameters[5]);
            Twist       = parameters[6];
            Scale       = parameters[7];
        }
Example #26
0
        public void MirrorPnt()
        {
            var p1 = new Pnt(1, 2, 3);

            Assert.AreEqual(new Pnt(3, 2, 1), p1.Mirrored(new Pnt(2, 2, 2)));
            p1.Mirror(new Pnt(2, 2, 2));
            Assert.AreEqual(new Pnt(3, 2, 1), p1);
        }
Example #27
0
        public void IsEqual()
        {
            var p1 = new Pnt(1, 2, 3);
            var p2 = new Pnt(4, 5, 6);

            Assert.IsTrue(p1.IsEqual(p2, 5.2));
            Assert.IsFalse(p1.IsEqual(p2, 5.18));
        }
Example #28
0
 public SourcePoint(Pnt location, SourceType sourceType, double strength, double distance, long id = 0)
 {
     this.id         = id;
     this.location   = location;
     this.sourceType = sourceType;
     this.strength   = rangesStrength[sourceType].toRange(strength);
     this.distance   = rangesStrength[sourceType].toRange(distance);
 }
Example #29
0
        //--------------------------------------------------------------------------------------------------

        public void Set(Pnt2d p, Pln plane)
        {
            Pnt pnt = new Pnt();

            ElSLib.D0(p.X, p.Y, plane, ref pnt);

            Set(pnt);
        }
Example #30
0
        public void Scale()
        {
            var p1 = new Pnt(1, 2, 3);

            Assert.AreEqual(new Pnt(0, 2, 4), p1.Scaled(new Pnt(2, 2, 2), 2));
            p1.Scale(new Pnt(2, 2, 2), 2);
            Assert.AreEqual(new Pnt(0, 2, 4), p1);
        }
Example #31
0
 /**
  * Angle (in radians) between two Pnts (treated as vectors).
  * @param p the other Pnt
  * @return the angle (in radians) between the two Pnts
  */
 public double angle(Pnt p)
 {
     return Math.Acos(this.dot(p) / (this.magnitude() * p.magnitude()));
 }
Example #32
0
 /**
  * Perpendicular bisector of two Pnts.
  * Works in any dimension.  The coefficients are returned as a Pnt of one
  * higher dimension (e.g., (A,B,C,D) for an equation of the form
  * Ax + By + Cz + D = 0).
  * @param point the other point
  * @return the coefficients of the perpendicular bisector
  */
 public Pnt bisector(Pnt point)
 {
     DimCheck(point);
     Pnt diff = this.subtract(point);
     Pnt sum = this.add(point);
     double dot = diff.dot(sum);
     return diff.extend(-dot / 2);
 }
Example #33
0
 private Vector3 Vectorfy(Pnt point)
 {
     return _transform.TransformPoint((float)point[0], _transform.position.y + 0.01f, (float)point[1]);
 }
Example #34
0
        private IEnumerable<VoronoiCell> GetCells()
        {
            var cellList = new List<VoronoiCell>();

            // Keep track of sites done; no drawing for initial triangles sites
            HashSet<Pnt> done = new HashSet<Pnt>(_initial);
            foreach (var triangle in _delaunay.Triangles)
            {
                foreach (var site in triangle)
                {
                    if (done.Contains(site)) continue;

                    done.Add(site);
                    List<Triangle> list = _delaunay.surroundingTriangles(site, triangle);
                    Pnt[] verts = new Pnt[list.Count];

                    int i = 0;
                    foreach (var tri in list) verts[i++] = tri.getCircumcenter();
                    if (verts.Length < 3) continue;

                    var cell = new VoronoiCell();
                    var first = Vectorfy(verts[0]);
                    for (int j = 2; j < verts.Length; j++) cell.Add(first, Vectorfy(verts[j - 1]), Vectorfy(verts[j]));
                    cellList.Add(cell);
                }
            }

            return cellList;
        }
Example #35
0
 /**
  * Report neighbor opposite the given vertex of triangle.
  * @param site a vertex of triangle
  * @param triangle we want the neighbor of this triangle
  * @return the neighbor opposite site in triangle; null if none
  * @throws ArgumentException if site is not in this triangle
  */
 public Triangle neighborOpposite(Pnt site, Triangle triangle)
 {
     if (!triangle.Contains(site))
         throw new ArgumentException("Bad vertex; not in triangle");
     foreach (var neighbor in triGraph.neighbors(triangle)) {
         if (!neighbor.Contains(site)) return neighbor;
     }
     return null;
 }
Example #36
0
 /**
  * Subtract.
  * @param p the other Pnt
  * @return a new Pnt = this - p
  */
 public Pnt subtract(Pnt p)
 {
     int len = DimCheck(p);
     double[] coords = new double[len];
     for (int i = 0; i < len; i++)
         coords[i] = this.coordinates[i] - p.coordinates[i];
     return new Pnt(coords);
 }
Example #37
0
 /**
  * Test if this Pnt is on a simplex.
  * @param simplex the simplex (an array of Pnts)
  * @return the simplex Pnt that "witnesses" on-ness (or null if not on)
  */
 public Pnt isOn(Pnt[] simplex)
 {
     int[] result = this.relation(simplex);
     Pnt witness = null;
     for (int i = 0; i < result.Length; i++) {
         if (result[i] == 0) witness = simplex[i];
         else if (result[i] > 0) return null;
     }
     return witness;
 }
Example #38
0
 /**
  * Test if this Pnt is outside of simplex.
  * @param simplex the simplex (an array of Pnts)
  * @return simplex Pnt that "witnesses" outsideness (or null if not outside)
  */
 public Pnt isOutside(Pnt[] simplex)
 {
     int[] result = this.relation(simplex);
     for (int i = 0; i < result.Length; i++) {
         if (result[i] > 0) return simplex[i];
     }
     return null;
 }
Example #39
0
 private void MakeDrawLine(Pnt old, Pnt newPoint)
 {
     var oldPoint = transform.TransformPoint(new Vector3((float)old[0], 0.01f, (float)old[1]));
     var newP = transform.TransformPoint(new Vector3((float)newPoint[0], 0.01f, (float)newPoint[1]));
     DrawLine(oldPoint, newP);
 }
Example #40
0
    /**
     * Relation between this Pnt and a simplex (represented as an array of
     * Pnts). Result is an array of signs, one for each vertex of the simplex,
     * indicating the relation between the vertex, the vertex's opposite facet,
     * and this Pnt.
     *
     * <pre>
     *   -1 means Pnt is on same side of facet
     *    0 means Pnt is on the facet
     *   +1 means Pnt is on opposite side of facet
     * </pre>
     *
     * @param simplex an array of Pnts representing a simplex
     * @return an array of signs showing relation between this Pnt and simplex
     * @throws ArgumentExcpetion if the simplex is degenerate
     */
    public int[] relation(Pnt[] simplex)
    {
        /* In 2D, we compute the cross of this matrix:
         *    1   1   1   1
         *    p0  a0  b0  c0
         *    p1  a1  b1  c1
         * where (a, b, c) is the simplex and p is this Pnt. The result is a
         * vector in which the first coordinate is the signed area (all signed
         * areas are off by the same constant factor) of the simplex and the
         * remaining coordinates are the *negated* signed areas for the
         * simplices in which p is substituted for each of the vertices.
         * Analogous results occur in higher dimensions.
         */
        int dim = simplex.Length - 1;
        if (this.Dimension != dim)
            throw new ArgumentException("Dimension mismatch");

        /* Create and load the matrix */
        Pnt[] matrix = new Pnt[dim+1];
        /* First row */
        double[] coords = new double[dim+2];
        for (int j = 0; j < coords.Length; j++) coords[j] = 1;
        matrix[0] = new Pnt(coords);
        /* Other rows */
        for (int i = 0; i < dim; i++) {
            coords[0] = this.coordinates[i];
            for (int j = 0; j < simplex.Length; j++)
                coords[j+1] = simplex[j].coordinates[i];
            matrix[i+1] = new Pnt(coords);
        }

        /* Compute and analyze the vector of areas/volumes/contents */
        Pnt vector = cross(matrix);
        double content = vector.coordinates[0];
        int[] result = new int[dim+1];
        for (int i = 0; i < result.Length; i++) {
            double value = vector.coordinates[i+1];
            if (Math.Abs(value) <= 1.0e-6 * Math.Abs(content)) result[i] = 0;
            else if (value < 0) result[i] = -1;
            else result[i] = 1;
        }
        if (content < 0) {
            for (int i = 0; i < result.Length; i++)
                result[i] = -result[i];
        }
        if (content == 0) {
            for (int i = 0; i < result.Length; i++)
                result[i] = Math.Abs(result[i]);
        }
        return result;
    }
Example #41
0
 /* Pnts as matrices */
 /**
  * Create a String for a matrix.
  * @param matrix the matrix (an array of Pnts)
  * @return a String represenation of the matrix
  */
 public static String toString(Pnt[] matrix)
 {
     var str = "{\n";
     for (int y = 0; y < matrix.Length; y++)
     {
         str += " " + matrix[y] + "\n";
     }
     return str + "}";
 }
Example #42
0
 /**
  * Compute the determinant of a matrix (array of Pnts).
  * This is not an efficient implementation, but should be adequate
  * for low dimension.
  * @param matrix the matrix as an array of Pnts
  * @return the determinnant of the input matrix
  * @throws ArgumentException if dimensions are wrong
  */
 public static double determinant(Pnt[] matrix)
 {
     if (matrix.Length != matrix[0].Dimension)
         throw new ArgumentException("Matrix is not square");
     bool[] columns = new bool[matrix.Length];
     for (int i = 0; i < matrix.Length; i++) columns[i] = true;
     try {return determinant(matrix, 0, columns);}
     catch (IndexOutOfRangeException e) {
         throw new ArgumentException("Matrix is wrong shape");
     }
 }
Example #43
0
 /**
  * Report triangles surrounding site in order (cw or ccw).
  * @param site we want the surrounding triangles for this site
  * @param triangle a "starting" triangle that has site as a vertex
  * @return all triangles surrounding site in order (cw or ccw)
  * @throws ArgumentException if site is not in triangle
  */
 public List<Triangle> surroundingTriangles(Pnt site, Triangle triangle)
 {
     if (!triangle.Contains(site))
         throw new ArgumentException("Site not in triangle");
     List<Triangle> list = new List<Triangle>();
     Triangle start = triangle;
     Pnt guide = triangle.getVertexButNot(site);        // Affects cw or ccw
     while (true) {
         list.AddIfNotContains(triangle);
         Triangle previous = triangle;
         triangle = neighborOpposite(guide, triangle); // Next triangle
         guide = previous.getVertexButNot(site, guide);     // Update guide
         if (triangle == start) break;
     }
     return list;
 }
Example #44
0
 /**
  * Compute generalized cross-product of the rows of a matrix.
  * The result is a Pnt perpendicular (as a vector) to each row of
  * the matrix.  This is not an efficient implementation, but should
  * be adequate for low dimension.
  * @param matrix the matrix of Pnts (one less row than the Pnt dimension)
  * @return a Pnt perpendicular to each row Pnt
  * @throws ArgumentException if matrix is wrong shape
  */
 public static Pnt cross(Pnt[] matrix)
 {
     int len = matrix.Length + 1;
     if (len != matrix[0].Dimension)
         throw new ArgumentException("Dimension mismatch");
     bool[] columns = new bool[len];
     for (int i = 0; i < len; i++) columns[i] = true;
     double[] result = new double[len];
     int sign = 1;
     try {
         for (int i = 0; i < len; i++) {
             columns[i] = false;
             result[i] = sign * determinant(matrix, 0, columns);
             columns[i] = true;
             sign = -sign;
         }
     } catch (IndexOutOfRangeException e) {
         throw new ArgumentException("Matrix is wrong shape");
     }
     return new Pnt(result);
 }
Example #45
0
 /**
  * Test if this Pnt is inside a simplex.
  * @param simplex the simplex (an arary of Pnts)
  * @return true iff this Pnt is inside simplex.
  */
 public bool isInside(Pnt[] simplex)
 {
     int[] result = this.relation(simplex);
     for (int i = 0; i < result.Length; i++) if (result[i] >= 0) return false;
     return true;
 }
Example #46
0
 /* Pnts as simplices */
 /**
  * Determine the signed content (i.e., area or volume, etc.) of a simplex.
  * @param simplex the simplex (as an array of Pnts)
  * @return the signed content of the simplex
  */
 public static double content(Pnt[] simplex)
 {
     Pnt[] matrix = new Pnt[simplex.Length];
     for (int i = 0; i < matrix.Length; i++)
         matrix[i] = simplex[i].extend(1);
     int fact = 1;
     for (int i = 1; i < matrix.Length; i++) fact = fact*i;
     return determinant(matrix) / fact;
 }
Example #47
0
    /**
     * Place a new site into the DT.
     * Nothing happens if the site matches an existing DT vertex.
     * @param site the new Pnt
     * @throws ArgumentException if site does not lie in any triangle
     */
    public void delaunayPlace(Pnt site)
    {
        // Uses straightforward scheme rather than best asymptotic time

        // Locate containing triangle
        Triangle triangle = locate(site);
        // Give up if no containing triangle or if site is already in DT
        if (triangle == null)
            throw new ArgumentException("No containing triangle");
        if (triangle.Contains(site)) return;

        // Determine the cavity and update the triangulation
        List<Triangle> cavity = getCavity(site, triangle);
        mostRecent = update(site, cavity);
    }
Example #48
0
 /**
  * Compute the determinant of a submatrix specified by starting row
  * and by "active" columns.
  * @param matrix the matrix as an array of Pnts
  * @param row the starting row
  * @param columns a bool array indicating the "active" columns
  * @return the determinant of the specified submatrix
  * @throws IndexOutOfRangeException if dimensions are wrong
  */
 private static double determinant(Pnt[] matrix, int row, bool[] columns)
 {
     if (row == matrix.Length) return 1;
     double sum = 0;
     int sign = 1;
     for (int col = 0; col < columns.Length; col++) {
         if (!columns[col]) continue;
         columns[col] = false;
         sum += sign * matrix[row].coordinates[col] *
                determinant(matrix, row+1, columns);
         columns[col] = true;
         sign = -sign;
     }
     return sum;
 }
Example #49
0
    /**
     * Locate the triangle with point inside it or on its boundary.
     * @param point the point to locate
     * @return the triangle that holds point; null if no such triangle
     */
    public Triangle locate(Pnt point)
    {
        Triangle triangle = mostRecent;
        if (!this.Contains(triangle)) triangle = null;

        // Try a directed walk (this works fine in 2D, but can fail in 3D)
        List<Triangle> visited = new List<Triangle>();
        while (triangle != null) {
            if (visited.Contains(triangle)) { // This should never happen
                //System.out.println("Warning: Caught in a locate loop");
                break;
            }
            visited.AddIfNotContains(triangle);
            // Corner opposite point
            Pnt corner = point.isOutside(triangle.ToArray());
            if (corner == null) return triangle;
            triangle = this.neighborOpposite(corner, triangle);
        }
        // No luck; try brute force
        //System.out.println("Warning: Checking all triangles for " + point);
        foreach (var tri in Triangles) {
            if (point.isOutside(tri.ToArray()) == null) return tri;
        }
        // No such triangle
        //System.out.println("Warning: No triangle holds " + point);
        return null;
    }
Example #50
0
 /**
  * Dot product.
  * @param p the other Pnt
  * @return dot product of this Pnt and p
  */
 public double dot(Pnt p)
 {
     int len = DimCheck(p);
     double sum = 0;
     for (int i = 0; i < len; i++)
         sum += this.coordinates[i] * p.coordinates[i];
     return sum;
 }
Example #51
0
 /**
  * Circumcenter of a simplex.
  * @param simplex the simplex (as an array of Pnts)
  * @return the circumcenter (a Pnt) of simplex
  */
 public static Pnt circumcenter(Pnt[] simplex)
 {
     int dim = simplex[0].Dimension;
     if (simplex.Length - 1 != dim)
         throw new ArgumentException("Dimension mismatch");
     Pnt[] matrix = new Pnt[dim];
     for (int i = 0; i < dim; i++)
         matrix[i] = simplex[i].bisector(simplex[i+1]);
     Pnt hCenter = cross(matrix);      // Center in homogeneous coordinates
     double last = hCenter.coordinates[dim];
     double[] result = new double[dim];
     for (int i = 0; i < dim; i++) result[i] = hCenter.coordinates[i] / last;
     return new Pnt(result);
 }
Example #52
0
 /**
  * Check that dimensions match.
  * @param p the Pnt to check (against this Pnt)
  * @return the dimension of the Pnts
  * @throws ArgumentException if dimension fail to match
  */
 public int DimCheck(Pnt p)
 {
     int len = this.coordinates.Length;
     if (len != p.coordinates.Length)
         throw new ArgumentException("Dimension mismatch");
     return len;
 }
Example #53
0
 /**
  * Test relation between this Pnt and circumcircle of a simplex.
  * @param simplex the simplex (as an array of Pnts)
  * @return -1, 0, or +1 for inside, on, or outside of circumcircle
  */
 public int vsCircumcircle(Pnt[] simplex)
 {
     Pnt[] matrix = new Pnt[simplex.Length + 1];
     for (int i = 0; i < simplex.Length; i++)
         matrix[i] = simplex[i].extend(1, simplex[i].dot(simplex[i]));
     matrix[simplex.Length] = this.extend(1, this.dot(this));
     double d = determinant(matrix);
     int result = (d < 0)? -1 : ((d > 0)? +1 : 0);
     if (content(simplex) < 0) result = - result;
     return result;
 }
Example #54
0
 /**
  * Determine the cavity caused by site.
  * @param site the site causing the cavity
  * @param triangle the triangle containing site
  * @return set of all triangles that have site in their circumcircle
  */
 private List<Triangle> getCavity(Pnt site, Triangle triangle)
 {
     List<Triangle> encroached = new List<Triangle>();
     Queue<Triangle> toBeChecked = new Queue<Triangle>();
     List<Triangle> marked = new List<Triangle>();
     toBeChecked.Enqueue(triangle);
     marked.AddIfNotContains(triangle);
     while (toBeChecked.Count != 0) {
         triangle = toBeChecked.Dequeue();
         if (site.vsCircumcircle(triangle.ToArray()) == 1)
             continue; // Site outside triangle => triangle not in cavity
         encroached.AddIfNotContains(triangle);
         // Check the neighbors
         foreach (var neighbor in triGraph.neighbors(triangle)){
             if (marked.Contains(neighbor)) continue;
             marked.AddIfNotContains(neighbor);
             toBeChecked.Enqueue(neighbor);
         }
     }
     return encroached;
 }
        /// <summary>
        /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels.
        /// </summary>
        /// <param name="pTlc">Point to start the reading from in the Raster</param>
        /// <param name="pRaster">Reference Raster for the PixelBlock</param>
        /// <param name="pPixelBlock">PixelBlock to be filled in</param>
        public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock)
        {
            try
            {
                // Create a new pixel block to read the input data into.
                // This is done because the pPixelBlock represents the output
                // pixel block which is different from the input. 
                int pBHeight = pPixelBlock.Height;
                int pBWidth = pPixelBlock.Width;
                IPnt pBlockSize = new Pnt();
                pBlockSize.X = pBWidth;
                pBlockSize.Y = pBHeight;
                IPixelBlock inputPixelBlock = new PixelBlock();
                ((IPixelBlock4)inputPixelBlock).Create(myInpNumBands, pBWidth, pBHeight, myInpPixeltype);

                // Call Read method of the Raster Function Helper object to read the input pixels into
                // the inputPixelBlock.
                myFunctionHelper.Read(pTlc, null, pRaster, inputPixelBlock);

                System.Array inpPixelValues1;
                System.Array inpPixelValues2;
                System.Array outPixelValues;
                int index1 = Convert.ToInt16(myBandIndices[0]) - 1; ; // Get NIR band index specified by user.
                int index2 = Convert.ToInt16(myBandIndices[1]) - 1; ; // Get Red Band index specified by user.

                // Get the correct bands from the input.
                IPixelBlock3 ipPixelBlock = (IPixelBlock3)inputPixelBlock;
                inpPixelValues1 = (System.Array)(ipPixelBlock.get_PixelData(index1));
                inpPixelValues2 = (System.Array)(ipPixelBlock.get_PixelData(index2));
                outPixelValues = (System.Array)(((IPixelBlock3)pPixelBlock).get_PixelData(0));
                int i = 0;
                int k = 0;
                double pixelValue = 0.0;
                double nirValue = 0.0;
                double irValue = 0.0;
                // Perform the NDVI computation and store the result in the output pixel block.
                for (i = 0; i < pBHeight; i++)
                {
                    for (k = 0; k < pBWidth; k++)
                    {
                        nirValue = Convert.ToDouble(inpPixelValues1.GetValue(k, i));
                        irValue = Convert.ToDouble(inpPixelValues2.GetValue(k, i));
                        // Check if input is not NoData.
                        if ((Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index1, k, i)) == 1) &&
                            Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index2, k, i)) == 1)
                        {
                            // NDVI[k] = (NIR[k]-Red[k])/(NIR[k]+Red[k]);
                            if ((nirValue + irValue) != 0) // Check for division by 0.
                            {
                                pixelValue = (nirValue - irValue) / (nirValue + irValue);
                                if (pixelValue < -1.0 || pixelValue > 1.0)
                                    pixelValue = 0.0;
                            }
                            else
                                pixelValue = 0.0;
                        }
                        outPixelValues.SetValue((float)(pixelValue), k, i);
                    }
                }
                // Set the output pixel values on the output pixel block.
                ((IPixelBlock3)pPixelBlock).set_PixelData(0, outPixelValues);
                // Copy over the NoData mask from the input and set it on the output.
                ((IPixelBlock3)pPixelBlock).set_NoDataMask(0, ((IPixelBlock3)inputPixelBlock).get_NoDataMask(0));
            }
            catch (Exception exc)
            {
                System.Exception myExc = new System.Exception(
                    "Exception caught in Read method: " + exc.Message, exc);
                throw myExc;
            }
        }
Example #56
0
    /**
     * Update the triangulation by removing the cavity triangles and then
     * filling the cavity with new triangles.
     * @param site the site that created the cavity
     * @param cavity the triangles with site in their circumcircle
     * @return one of the new triangles
     */
    private Triangle update(Pnt site, List<Triangle> cavity)
    {
        List<List<Pnt>> boundary = new List<List<Pnt>>();
        List<Triangle> theTriangles = new List<Triangle>();

        // Find boundary facets and adjacent triangles
        foreach (var triangle in cavity) {
            var neighborTriangles = neighbors(triangle);
            theTriangles.AddUniques(neighborTriangles);
            foreach (var vertex in triangle) {
                List<Pnt> facet = triangle.facetOpposite(vertex);

                int removeIndex = -1;
                for (int i = 0; i < boundary.Count; i++)
                {
                    if (boundary[i].ListsEqual(facet)) removeIndex = i;
                }

                if (removeIndex != -1) boundary.RemoveAt(removeIndex);
                else boundary.Add(facet);
            }
        }
        theTriangles.RemoveAll(cavity);        // Adj triangles only

        // Remove the cavity triangles from the triangulation
        foreach (var triangle in cavity) triGraph.remove(triangle);

        // Build each new triangle and add it to the triangulation
        List<Triangle> newTriangles = new List<Triangle>();
        foreach (var vertices in boundary) {
            vertices.AddIfNotContains(site);
            Triangle tri = new Triangle(vertices);
            triGraph.add(tri);
            newTriangles.AddIfNotContains(tri);
        }

        // Update the graph links for each new triangle
        theTriangles.AddAll(newTriangles);    // Adj triangle + new triangles
        foreach (var triangle in newTriangles)
            foreach (var other in theTriangles)
                if (triangle.isNeighbor(other))
                    triGraph.add(triangle, other);

        // Return one of the new triangles
        var enumerator = newTriangles.GetEnumerator();
        enumerator.MoveNext();
        return enumerator.Current;
    }
        private byte[] QueryRasterHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;
            int layerID = Convert.ToInt32(boundVariables["layersID"]);
            double? min = null;
            double? max = null;
            operationInput.TryGetAsDouble("min", out min);
            operationInput.TryGetAsDouble("max", out max);
            if ((!min.HasValue) && (!max.HasValue)) {
                throw new ArgumentException(Name + ": must specify at least one of {min,max}");
            }
            ISpatialReference outSR = GetSpatialReferenceParam(operationInput, "outSR");

            IRaster raster = m_layers[layerID].Raster;
            IRasterBand band = (raster as IRasterBandCollection).Item(0);
            IRawPixels pixels = band as IRawPixels;
            IRasterProps properties = band as IRasterProps;
            int width = properties.Width;
            int height = properties.Height;
            double noData = Convert.ToDouble(properties.NoDataValue);

            IPnt flowDirBlockSize = new Pnt();
            flowDirBlockSize.SetCoords(width, height);
            IPixelBlock pixelBlock = raster.CreatePixelBlock(flowDirBlockSize);
            IPnt pixelOrigin = new Pnt();
            pixelOrigin.SetCoords(0, 0);
            pixels.Read(pixelOrigin, pixelBlock);
            System.Array data = (System.Array)(pixelBlock as IPixelBlock3).get_PixelDataByRef(0);

            bool[,] outData = new bool[width, height];
            for (int x = 0; x < width; x += 1) {
                for (int y = 0; y < height; y += 1) {
                    object value = data.GetValue(x, y);
                    bool cellValue = false;
                    if (value != null) {
                        double numericValue = Convert.ToDouble(value);
                        if ((numericValue != noData) &&
                            ((!min.HasValue) || (numericValue > min.Value)) &&
                            ((!max.HasValue) || (numericValue < max.Value))) {
                            cellValue = true;
                        }
                    }
                    outData.SetValue(cellValue, x, y);
                }
            }

            BoundingCurve bc = new BoundingCurve(outData);
            IPolygon resultGeom = bc.GetBoundaryAsPolygon(properties);
            resultGeom.SpatialReference = properties.SpatialReference;

            if ((outSR != null) && (outSR.FactoryCode != resultGeom.SpatialReference.FactoryCode)) {
                resultGeom.Project(outSR);
            }

            Feature resultFeature = new Feature();
            resultFeature.Geometry = resultGeom;
            resultFeature.Attributes.Add("Shape_Length", resultGeom.Length);
            resultFeature.Attributes.Add("Shape_Area", (resultGeom as IArea).Area);
            resultFeature.Attributes.Add("Shape_Units", DescribeUnits(resultGeom.SpatialReference));
            FeatureSet result = new FeatureSet();
            result.GeometryType = esriGeometryType.esriGeometryPolygon;
            result.Features.Add(resultFeature);

            return Encoding.UTF8.GetBytes(result.ToJsonObject().ToJson());
        }