Beispiel #1
0
        protected override void OnMouseMove(object sender, MouseEventArgs e)
        {
            base.OnMouseMove(sender, e);
            GridVector2 WorldPosition = Parent.ScreenToWorld(e.X, e.Y);

            //Check if we should start a rectangle
            if (e.Button == MouseButtons.Left && oldMouse.Button != MouseButtons.Left)
            {
                this.rectangle = new GridRectangle(WorldPosition, 0, 0);
            }
            else if (e.Button == MouseButtons.Left)
            {
                if (WorldPosition.Y < this.rectangle.Bottom)
                    this.rectangle.Bottom = WorldPosition.Y;
                else
                    this.rectangle.Top = WorldPosition.Y;

                if (WorldPosition.X < this.rectangle.Left)
                    this.rectangle.Left = WorldPosition.X;
                else
                    this.rectangle.Right = WorldPosition.X;
            }
            //If the mouse was released we stop drawing rectangle
            else if (e.Button != MouseButtons.Left && oldMouse.Button == MouseButtons.Left)
            {
                this.CommandActive = false;
            }
        }
Beispiel #2
0
 public GridTransform(SerializationInfo info, StreamingContext context)
 {
     _mapPoints = info.GetValue("_mapPoints", typeof(MappingGridVector2[])) as MappingGridVector2[];
     _TriangleIndiciesCache = info.GetValue("_TriangleIndiciesCache", typeof(int[])) as int[];
     _CachedMappedBounds = (GridRectangle)info.GetValue("_CachedMappedBounds", typeof(GridRectangle));
     _CachedControlBounds = (GridRectangle)info.GetValue("_CachedControlBounds", typeof(GridRectangle));
     LastModified = info.GetDateTime("LastModified");
 }
        public override TilePyramid VisibleTiles(GridRectangle VisibleBounds, double DownSample)
        {
            int roundedDownsample = NearestAvailableLevel(DownSample);

            GridQuad VisibleQuad = null;

            //Add any corners of the VisibleBounds that we can transform to the list of points
            List<MappingGridVector2> VisiblePoints = VisibleBoundsCorners(VolumeTransform, VisibleBounds);
            if (VisiblePoints.Count != 4)
            {
                //If we can't map all four corners then add all the points from the transform falling inside the visible rectangle or
                //connected to those points by an edge
                List<MappingGridVector2> listTransformPoints = this.VolumeTransform.IntersectingControlRectangle(VisibleBounds, true);
                VisiblePoints.AddRange(listTransformPoints);
            }
            else
            {
                VisiblePoints.Sort(new MappingGridVector2SortByMapPoints());
                VisibleQuad = new GridQuad(VisiblePoints[0].MappedPoint,
                                           VisiblePoints[1].MappedPoint,
                                           VisiblePoints[2].MappedPoint,
                                           VisiblePoints[3].MappedPoint);
            }

            //OK, transform all points falling inside the section border
            //Starting with low-res tiles, add tiles to the list until we reach desired resolution
            //List<Tile> TilesToDraw = new List<Tile>();
            TilePyramid TilesToDraw = new TilePyramid(VisibleBounds);

            if (VisiblePoints.Count < 3)
                return TilesToDraw;

            GridRectangle SectionBorder = MappingGridVector2.CalculateMappedBounds(VisiblePoints.ToArray());

            int iLevel = AvailableLevels.Length - 1;
            int level = AvailableLevels[iLevel];
            do
            {
                List<Tile> newTiles = RecursiveVisibleTiles(VisibleBounds,
                                                            SectionBorder,
                                                            VisibleQuad,
                                                            level
                                                            //PORT: AsynchTextureLoad
                                                            );

                //Insert at the beginning so we overwrite earlier tiles with poorer resolution
                TilesToDraw.AddTiles(level, newTiles.ToArray());

                iLevel--;
                if (iLevel >= 0)
                    level = AvailableLevels[iLevel];
            }
            while (level >= roundedDownsample && iLevel >= 0);

            //  Trace.WriteLine("Drawing " + TilesToDraw.Count.ToString() + " Tiles", "VolumeModel");

            return TilesToDraw;
        }
Beispiel #4
0
 public static int[] Triangulate(GridVector2[] points, GridRectangle bounds)
 {
     double WidthMargin = bounds.Width;
     double HeightMargin = bounds.Height;
     GridVector2[] BoundingPoints = new GridVector2[] { new GridVector2(bounds.Left - WidthMargin, bounds.Bottom - HeightMargin),
                                                        new GridVector2(bounds.Right + WidthMargin, bounds.Bottom - HeightMargin),
                                                        new GridVector2(bounds.Left - WidthMargin, bounds.Top +  HeightMargin),
                                                        new GridVector2(bounds.Right + WidthMargin, bounds.Top + HeightMargin)};
     return Delaunay.Triangulate(points, BoundingPoints);
 }
Beispiel #5
0
        public ScreenshotForm(GridRectangle myRect, double Downsample, int Z)
        {
            this._Z = Z;
            this.Rect = myRect;

            ViewerDownsample = Downsample;

            if (ScreenshotForm.UseViewerDownsampleChecked)
                this.Downsample = Downsample;
            else
                this.Downsample = ScreenshotForm.LastDownsampleValue;

            InitializeComponent();
        }
Beispiel #6
0
        public void TestGridRectangle()
        {
            GridRectangle rectA = new GridRectangle(10, 50, 20, 40);

            bool success = rectA.Contains(new GridVector2(10, 20));
            Debug.Assert(success);

            success = rectA.Contains(new GridVector2(50, 40));
            Debug.Assert(success);

            success = rectA.Contains(rectA.Center);
            Debug.Assert(success);

            GridRectangle rectBOverlaps = new GridRectangle(5, 15, 10, 21);
            success = rectA.Intersects(rectBOverlaps);
            Debug.Assert(success);

            success = rectA.Contains(rectBOverlaps);
            Debug.Assert(false == success);

            GridRectangle rectCNoOverlap = new GridRectangle(5, 15, 10, 19);
            success = rectA.Intersects(rectCNoOverlap);
            Debug.Assert(false == success);

            success = rectA.Contains(rectBOverlaps);
            Debug.Assert(false == success);

            GridRectangle rectDContained = new GridRectangle(15, 45, 25, 35);
            success = rectA.Intersects(rectDContained);
            Debug.Assert(success);

            success = rectA.Contains(rectDContained);
            Debug.Assert(success);

            /*Scale the rectangle and test again*/
            rectA.Scale(2);

            Debug.Assert(-10.0 == rectA.Left &&
                         70 == rectA.Right &&
                         10 == rectA.Bottom &&
                         50 == rectA.Top);

            /*Scale the rectangle and test again*/
            rectA.Scale(0.5);

            Debug.Assert(10.0 == rectA.Left &&
                         50 == rectA.Right &&
                         20 == rectA.Bottom &&
                         40 == rectA.Top);
        }
        public ICollection<Location_CanvasViewModel> GetLocations(GridRectangle bounds)
        {
            List<GridVector2> foundPoints; 
            List<Location_CanvasViewModel> foundLocations;
            Locations.Intersect(bounds, out foundPoints, out foundLocations);

            return foundLocations; 
        }
Beispiel #8
0
 public bool Union(GridRectangle rect)
 {
     return this.Union(rect.LowerLeft) || this.Union(rect.UpperRight);
 }
Beispiel #9
0
        public static List<MappingGridVector2> ParseRotateTranslateAffineTransform(string[] parts,
            float pixelSpacing,
            int iFixedParameters,
            int iVariableParameters,
            GridRectangle MappedBounds, 
            GridRectangle ControlBounds)
        {
            //Find the dimensions of the grid
            List<MappingGridVector2> mappings = new List<MappingGridVector2>();
            /*
            GridVector2[] Points = new GridVector2[4];
            GridVector2[] mappedPoints = new GridVector2[4];
            GridVector2[] ctrlPoints = new GridVector2[4];

            Points[0] = new GridVector2(0, 0);
            Points[1] = new GridVector2(MappedBounds.Width, 0);
            Points[2] = new GridVector2(0, MappedBounds.Height);
            Points[3] = new GridVector2(MappedBounds.Width, MappedBounds.Height);

            ctrlPoints[0] = new GridVector2(0, 0);
            ctrlPoints[1] = new GridVector2(ControlBounds.Width, 0);
            ctrlPoints[2] = new GridVector2(0, ControlBounds.Height);
            ctrlPoints[3] = new GridVector2(ControlBounds.Width, ControlBounds.Height);

            Matrix mat = Matrix.Identity;
            mat.M11 = System.Convert.ToSingle(parts[iVariableParameters + 2]);
            mat.M12 = System.Convert.ToSingle(parts[iVariableParameters + 3]);
            mat.M21 = System.Convert.ToSingle(parts[iVariableParameters + 4]);
            mat.M22 = System.Convert.ToSingle(parts[iVariableParameters + 5]);

            //Cheating: since the rotation matrix is
            //[cos(t) -sin(t)]
            //[sin(t)  cos(t)]
            //we just take the asin of the parameter to find the rotation value

            //            double theta = Math.Acos(System.Convert.ToSingle(parts[iVariableParameters + 2]));

            //Matrix mat = Matrix.CreateRotationZ((float)theta);

            mappedPoints[0] = Vector2.Transform(Points[0], mat);
            mappedPoints[1] = Vector2.Transform(Points[1], mat);
            mappedPoints[2] = Vector2.Transform(Points[2], mat);
            mappedPoints[3] = Vector2.Transform(Points[3], mat);

            Triangle controlOne = new Triangle(ctrlPoints[0], ctrlPoints[1], ctrlPoints[2]);
            Triangle controlTwo = new Triangle(ctrlPoints[2], ctrlPoints[1], ctrlPoints[3]);
            Triangle mappedOne = new Triangle(mappedPoints[0], mappedPoints[1], mappedPoints[2]);
            Triangle mappedTwo = new Triangle(mappedPoints[2], mappedPoints[1], mappedPoints[3]);

            mappings.Add(new MappingTriangle(controlOne, mappedOne));
            mappings.Add(new MappingTriangle(controlTwo, mappedTwo));
            */
            return mappings;
        }
Beispiel #10
0
        /// <summary>
        /// Returns true if the passed rectangle is entirely inside this rectangle
        /// </summary>
        /// <param name="rect"></param>
        /// <returns></returns>
        public bool Contains(GridRectangle rect)
        {
            //Find out if rect is inside this rectangle
            if (rect.Right <= this.Right &&
               rect.Top <= this.Top &&
               rect.Left >= this.Left &&
               rect.Bottom >= this.Bottom)
                return true;

            return false;
        }
Beispiel #11
0
        /// <summary>
        /// Returns true if the passed rectangle in inside or overlaps this rectangle
        /// </summary>
        /// <param name="rect"></param>
        /// <returns></returns>
        public bool Intersects(GridRectangle rect)
        {
            //Find out if the rectangles can't possibly intersect
            if(rect.Right < this.Left ||
               rect.Top < this.Bottom ||
               rect.Left > this.Right ||
               rect.Bottom > this.Top)
                return false;

            return true;
        }
Beispiel #12
0
        /// <summary>
        /// Takes a capture and sends it to the clipboard
        /// </summary>
        protected Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[] CaptureArea(GridRectangle Rect, float Downsample)
        {
            Debug.Assert((Rect.Width / Downsample) < 4096 && (Rect.Height / Downsample) < 4096);
            Debug.Assert(this.PaintCallRefCount == 0);

            //            Vector3 OriginalCameraLookAt = this.Camera.LookAt;
            //float OriginalCameraDistance = this.CameraDistance;
             //           Rectangle OriginalVisibleRect = this.VisibleScreenRect;

            int Width = (int)Math.Round(Rect.Width / Downsample);
            int Height = (int)Math.Round(Rect.Height / Downsample);

            Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[] data = new Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[Width * Height];

            try
            {
                // Initialize our RenderTarget
                ScreenshotRenderTarget = new RenderTarget2D(Device,
                    Width,
                    Height,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.Depth24Stencil8);

                Device.SetRenderTarget(ScreenshotRenderTarget);

                bool OldAsynchTextureLoad = AsynchTextureLoad;
                AsynchTextureLoad = false;
               //     Draw(Downsample);
                AsynchTextureLoad = OldAsynchTextureLoad;

                Device.SetRenderTarget(null);

                data = new Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[ScreenshotRenderTarget.Width * ScreenshotRenderTarget.Height];
                ScreenshotRenderTarget.GetData<Microsoft.Xna.Framework.Graphics.PackedVector.Byte4>(data);

               //         Draw();
            }
            finally
            {
                Device.SetRenderTarget(null);

                if (ScreenshotRenderTarget != null)
                {
                    ScreenshotRenderTarget.Dispose();
                    ScreenshotRenderTarget = null;
                }

            //                this.CameraLookAt = OriginalCameraLookAt;
               // this.CameraDistance = OriginalCameraDistance;
            }

            return data;
        }
Beispiel #13
0
        protected override void OnMouseMove(object sender, MouseEventArgs e)
        {
            //Figure out if we are starting a rectangle
            if (e.Button == MouseButtons.Left && this.CommandActive)
            {
                GridVector2 NewPosition = Parent.ScreenToWorld(e.X, e.Y);

                double Width = NewPosition.X - Origin.X;
                double Height = NewPosition.Y - Origin.Y;
                if (Width != 0 && Height != 0)
                {
                    MyRect = new GridRectangle(Origin, Width, Height);
                    this.Color = Color.Red;

                    this.Parent.Refresh();
                }
            }

            base.OnMouseMove(sender, e);
        }
Beispiel #14
0
        /// <summary>
        /// Allocates a new quad tree based on the current section parameters
        /// </summary>
        public static GridRectangle SectionBounds(Viking.UI.Controls.SectionViewerControl Parent, int SectionNumber)
        {
            GridRectangle bounds = new GridRectangle();

            //Figure out the new boundaries for our quad-tree
            if(!Parent.Section.VolumeViewModel.SectionViewModels.ContainsKey(SectionNumber))
                return new GridRectangle();

            SectionViewModel SectionView = Parent.Section.VolumeViewModel.SectionViewModels[SectionNumber];
            bounds = Parent.SectionBounds(SectionView.section);
            if (SectionView.ReferenceSectionAbove != null)
            {
                bounds = GridRectangle.Union(bounds, Parent.SectionBounds(SectionView.ReferenceSectionAbove));
            }
            if (SectionView.ReferenceSectionBelow != null)
            {
                bounds = GridRectangle.Union(bounds, Parent.SectionBounds(SectionView.ReferenceSectionBelow));
            }

            return bounds;
        }
Beispiel #15
0
        /// <summary>
        /// Maps the provided visible bounds in volume space back to section space with the provided transform.
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="VisibleBounds"></param>
        /// <returns></returns>
        protected List<MappingGridVector2> VisibleBoundsCorners(Geometry.Transforms.TransformBase transform, GridRectangle VisibleBounds)
        {
            List<MappingGridVector2> listBoundCorners = new List<MappingGridVector2>(4);
            //Add any corners of the VisibleBounds that we can transform to the list of points
            bool transformSuccess = false;
            GridVector2 TLowerLeft;
            GridVector2 TLowerRight;
            GridVector2 TUpperLeft;
            GridVector2 TUpperRight;

            transformSuccess = transform.TryInverseTransform(VisibleBounds.LowerLeft, out TLowerLeft);
            if(transformSuccess)
                listBoundCorners.Add(new MappingGridVector2(VisibleBounds.LowerLeft, TLowerLeft));

            //Add any corners of the VisibleBounds that we can transform to the list of points
            transformSuccess = transform.TryInverseTransform(VisibleBounds.LowerRight, out TLowerRight);
            if(transformSuccess)
                listBoundCorners.Add(new MappingGridVector2(VisibleBounds.LowerRight, TLowerRight));

            transformSuccess = transform.TryInverseTransform(VisibleBounds.UpperLeft, out TUpperLeft);
            if(transformSuccess)
                listBoundCorners.Add(new MappingGridVector2(VisibleBounds.UpperLeft, TUpperLeft));

            transformSuccess = transform.TryInverseTransform(VisibleBounds.UpperRight, out TUpperRight);
            if(transformSuccess)
                listBoundCorners.Add(new MappingGridVector2(VisibleBounds.UpperRight, TUpperRight));

            return listBoundCorners;
        }
Beispiel #16
0
        /// <summary>
        /// Returns all points inside the requested region.  
        /// If include adjacent is set to true we include points with an edge that crosses the border of the requested rectangle
        /// </summary>
        /// <param name="gridRect"></param>
        /// <returns></returns>
        private List<MappingGridVector2> IntersectingRectangle(GridRectangle gridRect,
                                                               QuadTree<List<MappingGridTriangle>> PointTree)
        {
            List<GridVector2> Points;
            List<List<MappingGridTriangle>> ListofListTriangles;

            List<MappingGridVector2> MappingPointList= null;

            if (gridRect.Contains(PointTree.Border))
            {
                MappingPointList = new List<MappingGridVector2>(_mapPoints);
                return MappingPointList;
            }

            PointTree.Intersect(gridRect, out Points, out ListofListTriangles);

            bool[] Added = new bool[_mapPoints.Length];
            MappingPointList = new List<MappingGridVector2>(Points.Count * 2);
            List<List<MappingGridTriangle>> MappingTriangleList = new List<List<MappingGridTriangle>>(Points.Count * 2);

            //Add all the unique points bordering the requested rectangle
            for (int iPoint = 0; iPoint < Points.Count; iPoint++)
            {
                List<MappingGridTriangle> FoundTriangleList = ListofListTriangles[iPoint];
                for (int iTri = 0; iTri < FoundTriangleList.Count; iTri++)
                {
                    MappingGridTriangle Triangle = FoundTriangleList[iTri];
                    if (!Added[Triangle.N1])
                    {
                        Added[Triangle.N1] = true;
                        MappingPointList.Add(this._mapPoints[Triangle.N1]);
                        MappingTriangleList.Add(this._TriangleList[Triangle.N1]);
                    }
                    if (!Added[Triangle.N2])
                    {
                        Added[Triangle.N2] = true;
                        MappingPointList.Add(this._mapPoints[Triangle.N2]);
                        MappingTriangleList.Add(this._TriangleList[Triangle.N1]);
                    }
                    if (!Added[Triangle.N3])
                    {
                        Added[Triangle.N3] = true;
                        MappingPointList.Add(this._mapPoints[Triangle.N3]);
                        MappingTriangleList.Add(this._TriangleList[Triangle.N1]);
                    }
                }
            }

            return MappingPointList;
        }
Beispiel #17
0
        /// <summary>
        /// Takes two transforms and transforms the control grid of this section into the control grid space of the passed transfrom. Requires control section
        /// of this transform to match mapped section of adding transform
        /// </summary>
        public void Add(GridTransform transform)
        {
            //We can't map if we don't have a triangle
            if (transform.mapPoints.Length < 3)
                return;

            //Temp: Ensure we know the edges
            this.CalculateEdges();
            transform.BuildDataStructures();

            //Reset boundaries since they will be changed
            _CachedControlBounds = new GridRectangle(double.MinValue, double.MinValue, 0, 0);
            _CachedMappedBounds = new GridRectangle(double.MinValue, double.MinValue, 0, 0);

            List<AddTransformThreadObj> threadObjList = new List<AddTransformThreadObj>();
            List<ManualResetEvent> doneEvents = new List<ManualResetEvent>();

            List<MappingGridVector2> newPoints = new List<MappingGridVector2>(mapPoints.Length);

            #if DEBUG
            List<GridVector2> mapPointList = new List<GridVector2>(newPoints.Count);
            #endif

            //            Trace.WriteLine("Starting with " + mapPoints.Length + " points", "Geometry");

            //    List<MappingGridVector2> newPoints = new List<MappingGridVector2>();

            //           Trace.WriteLine("Started GridTransform.Add with " + mapPoints.Length.ToString() + " points", "Geometry");

            //Search all mapping triangles and update control points, if they fall outside the grid then discard the triangle
            const int PointsPerThread = 4;
            for (int iPoint = 0; iPoint < this.mapPoints.Length; iPoint += PointsPerThread )
            {
                //Create a series of points for the thread to process so they aren't constantly hitting the queue lock looking for new work.
                List<int> listPoints = new List<int>(PointsPerThread);
                for (int iAddPoint = iPoint; iAddPoint < iPoint + PointsPerThread; iAddPoint++)
                {
                    //Don't add if the point is out of range
                    if (iAddPoint >= this.mapPoints.Length)
                        break;

                    listPoints.Add(iAddPoint);
                }

                //MappingGridVector2 mapPoint = mapPoints[iPoint];
                AddTransformThreadObj AddThreadObj = new AddTransformThreadObj(listPoints.ToArray(), this, transform);
                doneEvents.Add(AddThreadObj.DoneEvent);
                threadObjList.Add(AddThreadObj);

                /*
                MappingGridVector2 UnmappedPoint = mapPoints[iPoint];
                MappingGridTriangle mapTri = transform.GetTransform(mapPoints[iPoint].ControlPoint);

                if (mapTri != null)
                {
                    GridVector2 newControl = mapTri.Transform(UnmappedPoint.ControlPoint);
                    newPoints.AddRange(new MappingGridVector2[] { new MappingGridVector2(newControl, UnmappedPoint.MappedPoint) });

                    List<MappingGridVector2> sortPoints = new List<MappingGridVector2>(newPoints);
                    sortPoints.Sort();
                    for (int i = 1; i < sortPoints.Count; i++)
                    {
                        Debug.Assert(sortPoints[i - 1].ControlPoint != sortPoints[i].ControlPoint);
                    }
                }
                else
                {
                    //In this case we need to test each edge connecting this point to other points.
                    //newPoints = new MappingGridVector2[0];
                    for(int i = 0; i < TriangleIndicies.Length; i += 3)
                    {
                        if(TriangleIndicies[i] == iPoint)
                        {

                    int[] EdgesIndicies = Array.Find<int>(this.TriangleIndicies, iPoint);
                }
                */

                //For single threaded debug, comment out threadpool and uncomment AddThreadObj.ThreadPoolCallback line
                ThreadPool.QueueUserWorkItem(AddThreadObj.ThreadPoolCallback);
            //                AddThreadObj.ThreadPoolCallback(null);

                //newPoints.AddRange(AddThreadObj.newPoints);

                //newPoints.Sort();

            #if false
                for (int iTest = 1; iTest < newPoints.Count; iTest++)
                {
                    Debug.Assert(newPoints[iTest - 1].ControlPoint != newPoints[iTest].ControlPoint);
                }

                for (int iMap = 0; iMap < AddThreadObj.newPoints.Length; iMap++)
                {
                    mapPointList.Add(AddThreadObj.newPoints[iMap].MappedPoint);
                }

                mapPointList.Sort();

                for (int iMap = 1; iMap < mapPointList.Count; iMap++)
                {
                    Debug.Assert(GridVector2.Distance(mapPointList[iMap], mapPointList[iMap - 1]) > Global.epsilon);
                }
            #endif
            }

            //Wait for the threads to finish processing.  There is a 64 handle limit for WaitAll so we wait on one at a time
            foreach (ManualResetEvent doneEvent in doneEvents)
                doneEvent.WaitOne();

            newPoints.Clear();

            foreach(AddTransformThreadObj obj in threadObjList)
            {
                if(obj.newPoints != null)
                    newPoints.AddRange(obj.newPoints);
            }

            //            Trace.WriteLine("Mapped " + newPoints.Count + " points", "Geometry");

            #if false

            mapPointList.Clear();
            for (int iMap = 0; iMap < newPoints.Count; iMap++)
            {
                mapPointList.Add(newPoints[iMap].MappedPoint);
            }

            mapPointList.Sort();

            for (int iMap = 1; iMap < mapPointList.Count; iMap++)
            {
                Debug.Assert(GridVector2.Distance(mapPointList[iMap], mapPointList[iMap - 1]) > Global.epsilon);
            }
            #endif

            //Remove duplicates: In the case that a line on the warpingGrid passes through a point on the fixedGrid then both ends of the line will map the point and we will get a duplicate
            newPoints.Sort();
            int iCompareStart = 0;
            for (int iTest = 1; iTest < newPoints.Count; iTest++)
            {
            //   Debug.Assert(newPoints[iTest - 1].ControlPoint != newPoints[iTest].ControlPoint);
                //This is slow, but even though we sort on the X axis it doesn't mean a point that is not adjacent to the point on the list isn't too close
                for (int jTest = iCompareStart; jTest < iTest; jTest++)
                {
                    if (GridVector2.Distance(newPoints[jTest].ControlPoint, newPoints[iTest].ControlPoint) <= Global.Epsilon)
                    {
                        newPoints.RemoveAt(iTest);
                        iTest--;
                        break;
                    }

                    //Optimization, since the array is sorted we don't need to compare points once a point is distant enough
                    if (newPoints[iTest].ControlPoint.X - newPoints[jTest].ControlPoint.X > Global.Epsilon)
                    {
                        iCompareStart = jTest;
                    }
                }
            }

            //            Trace.WriteLine("Ended with " + newPoints.Count + " points", "Geometry");
            this.mapPoints = newPoints.ToArray();

            //Edges are build on mapPoints, so we need to remove them so they'll be recalculates
            _edges = null;
            //Other datastructures are dependent on edges, so minimize memory will delete them
            MinimizeMemory();

            //            Trace.WriteLine("Finished GridTransform.Add with " + newPoints.Count.ToString() + " points", "Geometry");

            //Check whether these have been set yet or if I don't need to clear them again
            this.ControlSection = transform.ControlSection;
        }
Beispiel #18
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            double ROIWidth = (double)this.numWidth.Value * this.Downsample;
            double ROIHeight = (double)this.numHeight.Value * this.Downsample;

            this.Rect = new GridRectangle(new GridVector2((double)this.numX.Value - ROIWidth / 2,
                                                          (double)this.numY.Value - ROIHeight / 2),
                                                          ROIWidth,
                                                          ROIHeight);

            ScreenshotForm.LastDownsampleValue = this.Downsample;
            this.IncludeOverlays = this.checkOverlays.Checked;

            //Write down the filename and remove the automatically appended number if needed
            ScreenshotForm.LastFileNamePrefix = System.IO.Path.GetFileNameWithoutExtension(textFilename.Text);
            string CaptureNumberString = "_" + ScreenshotForm.NextCaptureNumber.ToString("d03");
            if (ScreenshotForm.LastFileNamePrefix.EndsWith(CaptureNumberString))
            {
                int i = ScreenshotForm.LastFileNamePrefix.LastIndexOf(CaptureNumberString);
                ScreenshotForm.LastFileNamePrefix = ScreenshotForm.LastFileNamePrefix.Remove(i);
            }

            ScreenshotForm.LastFileNamePrefix = System.IO.Path.GetDirectoryName(textFilename.Text) +
                                                System.IO.Path.DirectorySeparatorChar +
                                                ScreenshotForm.LastFileNamePrefix;

            ScreenshotForm.NextCaptureNumber++;

            this.DialogResult = DialogResult.OK;
            this.Close();

            //Try to create a descriptive text file matching the image name
            try
            {
                string dirname = System.IO.Path.GetDirectoryName(this.Filename);
                string basename = System.IO.Path.GetFileNameWithoutExtension(this.Filename);
                string MetaFilename = System.IO.Path.Combine(dirname, basename + ".txt");
                using (System.IO.StreamWriter textFile = System.IO.File.CreateText(MetaFilename))
                {
                    double X = this.Rect.Left;
                    double Y = this.Rect.Bottom;
                    textFile.WriteLine("Filename:\t" + Filename);
                    textFile.WriteLine("X: " + X.ToString() + "\tY: " + Y.ToString() + "\tZ: " + this._Z.ToString());
                    textFile.WriteLine("Width: " + Rect.Width.ToString() + "\tHeight: " + Rect.Height.ToString());
                    textFile.WriteLine("Downsample: " + Downsample.ToString());
                }
            }
            catch (Exception except)
            {
                MessageBox.Show("Error creating meta-data file for screen capture:\n" + except.Message, "Error");
            }
        }
        /// <summary>
        /// Returns true if the specified tile is visible
        /// </summary>
        /// <param name="iX"></param>
        /// <param name="iY"></param>
        /// <returns></returns>
        private GridRectangle TileBorder(int iX, int iY, int Downsample)
        {
            GridRectangle TileBorder;
            double Width = this.TileSizeX * Downsample;
            double Height = this.TileSizeY * Downsample;
            double X = iX * Width;
            double Y = iY * Height;

            TileBorder = new GridRectangle(X, X+Width, Y, Y+Height);

            return TileBorder;
        }
        private List<Tile> RecursiveVisibleTiles(
                                                 GridRectangle VolumeVisibleBounds,
                                                 GridRectangle SectionVisibleBounds,
                                                 GridQuad VisibleQuad, 
                                                 int roundedDownsample)
        {
            GridInfo gridInfo = LevelToGridInfo[roundedDownsample];

            int ScaledTileSizeX = this.TileSizeX * roundedDownsample;
            int ScaledTileSizeY = this.TileSizeX * roundedDownsample;

            //Figure out which grid locations are visible
            int iMinX = (int)Math.Floor(SectionVisibleBounds.Left / ScaledTileSizeX);
            int iMinY = (int)Math.Floor(SectionVisibleBounds.Bottom / ScaledTileSizeY);
            int iMaxX = (int)Math.Ceiling(SectionVisibleBounds.Right / ScaledTileSizeX);
            int iMaxY = (int)Math.Ceiling(SectionVisibleBounds.Top / ScaledTileSizeY);

            iMinX = iMinX < 0 ? 0 : iMinX;
            iMinY = iMinY < 0 ? 0 : iMinY;
            iMaxX = iMaxX > gridInfo.GridXDim ? gridInfo.GridXDim : iMaxX;
            iMaxY = iMaxY > gridInfo.GridYDim ? gridInfo.GridYDim : iMaxY;

            int ExpectedTileCount = (iMaxX - iMinX) * (iMaxY - iMinY);
            List<Tile> TilesToDraw = new List<Tile>(ExpectedTileCount);

            for (int iX = iMinX; iX < iMaxX; iX++)
            {
                for (int iY = iMinY; iY < iMaxY; iY++)
                {
                    //Figure out if the tile would be visible
                    GridRectangle tileBorder = TileBorder(iX, iY, roundedDownsample);
                    if (tileBorder.Intersects(SectionVisibleBounds) == false)
                        continue;

                    //If we have a visble quad see if the tile intersects that too
                    if (VisibleQuad != null)
                    {
                        if (VisibleQuad.Contains(tileBorder) == false)
                            continue;
                    }
                    string UniqueID = Tile.CreateUniqueKey(Section.Number, "Grid to Volume", Name, roundedDownsample, this.TileTextureFileName(iX, iY));

                    //                   Trace.WriteLine(TextureFileName, "VolumeModel");
                    Tile tile = Global.TileCache.Fetch(UniqueID);
                    if (tile == null)
                    {
                        //First create a new tile
                        int MipMapLevels = 1; //No mip maps
                        if (roundedDownsample == this.AvailableLevels[AvailableLevels.Length - 1])
                            MipMapLevels = 0; //Generate mipmaps for lowest res texture

                        //PORT: string TextureCacheFileName = TileCacheName(iX, iY, roundedDownsample);
                        int[] edges;
            //                        Trace.WriteLine(TextureFileName, "VolumeModel");
                        PositionNormalTextureVertex[] verticies = CalculateVerticies(iX,
                                                                                     iY,
                                                                                     roundedDownsample,
                                                                                     out edges);

                        string TextureFileName = TileFullPath(iX, iY, roundedDownsample);

                        tile = Global.TileCache.ConstructTile(UniqueID,
                                                            verticies,
                                                            edges,
                                                            TextureFileName,
                                                            this.TileTextureCacheFileName(roundedDownsample, iX, iY),
                                                            //PORT: TextureCacheFileName,
                                                            this.Name,
                                                            roundedDownsample,
                                                            MipMapLevels);
                    }

                    TilesToDraw.Add(tile);
                }
            }

            return TilesToDraw;
        }
 /// <summary>
 /// Return all the line segments visible in the passed bounds
 /// </summary>
 /// <param name="bounds"></param>
 /// <returns></returns>
 public StructureLink[] VisibleStructureLinks(GridRectangle bounds)
 {
     StructureLink[] LinkList = StructureLinksSearch.GetValues(bounds);
     return LinkList;
 }
Beispiel #22
0
        /// <summary>
        /// This code was reverse engineered from original stos polynomial transform source
        /// </summary>
        /// <param name="parts"></param>
        /// <param name="pixelSpacing"></param>
        /// <param name="iFixedParameters"></param>
        /// <param name="iVariableParameters"></param>
        /// <param name="MappedBounds"></param>
        /// <returns></returns>
        public static List<MappingGridVector2> ParsePolyTransform(string[] parts, float pixelSpacing, int iFixedParameters, int iVariableParameters, GridRectangle MappedBounds)
        {
            List<MappingGridVector2> mappings = new List<MappingGridVector2>();

            float MappedWidth = (float)MappedBounds.Width;
            float MappedHeight = (float)MappedBounds.Height;

            int numParams = System.Convert.ToInt32(parts[iVariableParameters +1]);

            //Skip two so we skip the "vp 5" part of the file and our indicies line up with Paul's code
            iFixedParameters += 2;
            iVariableParameters += 2;

            double uc = System.Convert.ToDouble(parts[iFixedParameters]);
            double vc = System.Convert.ToDouble(parts[iFixedParameters + 1]);
            double xmax = System.Convert.ToDouble(parts[iFixedParameters + 2]);
            double ymax = System.Convert.ToDouble(parts[iFixedParameters + 3]);

            uc = xmax / 2;
            vc = ymax / 2;

            double[] parameters = new double[numParams];
            for(int iVP = 0; iVP < numParams; iVP++)
            {
                parameters[iVP] = System.Convert.ToDouble(parts[iVariableParameters + iVP]);
            }

            int gridHeight = 5;
            int gridWidth = 5;

            int NumPts = (int)(gridHeight * gridWidth);

            GridVector2[] Points = new GridVector2[NumPts];

            for (int iY = 0; iY < gridHeight; iY++)
            {
                for (int iX = 0; iX < gridWidth; iX++)
                {
                    double u = (xmax / (double)(gridWidth-1)) * (double)iX;
                    double v = (ymax / (double)(gridHeight-1)) * (double)iY;

                    double A = (u - uc) / xmax;
                    double B = (v - vc) / ymax;

                    //For some reason I am off by a factor of two:
                    A *= 2;
                    B *= 2;

                    double[] P = new double[Dimensions + 1];
                    double[] Q = new double[Dimensions + 1];

                    for (int i = 0; i <= Dimensions; i++)
                    {
                        P[i] = Legendre.P[i](A);
                        Q[i] = Legendre.P[i](B);
                    }

                    double Sa = 0.0;
                    double Sb = 0.0;

                    for (int i = 0; i <= Dimensions; i++)
                    {
                        for (int j = 0; j <= i; j++)
                        {
                            int k = i - j;
                            double PjQk = P[j] * Q[k];
                            Sa += parameters[index_a(j, k)] * PjQk;
                            Sb += parameters[index_b(j, k)] * PjQk;
                        }
                    }

                    Points[(iY * gridWidth) + iX] = new GridVector2((xmax * Sa * pixelSpacing), (ymax * Sb * pixelSpacing));
                }
            }

            for (int y = 0; y < gridHeight; y++)
            {
                for (int x = 0; x < gridWidth; x++)
                {
                    int i = x + (y * gridWidth);
                    GridVector2 controlPoint = Points[i];
                    GridVector2 mappedPoint = CoordinateFromGridPos(x, y, gridWidth, gridHeight, MappedWidth, MappedHeight);

                    mappings.Add(new MappingGridVector2(controlPoint, mappedPoint));
                }
            }

            return mappings;
        }
Beispiel #23
0
        public GridRectangle RenderTargetBounds()
        {
            if (Device == null)
                return new GridRectangle(0, 0, 10, 10);

            //For debugging
            const int offset = 0;

            //GridVector2 TopLeft = ScreenToWorld(offset, offset);
            //GridVector2 BottomLeft = ScreenToWorld(offset, GraphicsDevice.Viewport.Height - offset);
            //GridVector2 TopRight = ScreenToWorld(GraphicsDevice.Viewport.Width - offset, offset);

            GridVector2 BottomLeft = Scene.ScreenToWorld(offset, Device.Viewport.Height - offset);
            GridVector2 TopRight = Scene.ScreenToWorld(Device.Viewport.Width - offset, offset);
            GridRectangle rect = new GridRectangle(BottomLeft, TopRight.X - BottomLeft.X, TopRight.Y - BottomLeft.Y);
            return rect;
        }
Beispiel #24
0
        /// <summary>
        /// Returns a rectangle bounding the passed rectangles
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <returns></returns>
        public static GridRectangle Union(GridRectangle A, GridRectangle B)
        {
            double left = A.Left < B.Left ? A.Left : B.Left;
            double right = A.Right > B.Right ? A.Right : B.Right;
            double top = A.Top > B.Top ? A.Top : B.Top;
            double bottom = A.Bottom < B.Bottom ? A.Bottom : B.Bottom;

            return new GridRectangle(left, right, bottom, top);
        }
Beispiel #25
0
        private static List<Location_CanvasViewModel> FindVisibleLocations(ICollection<Location_CanvasViewModel> locations,  GridRectangle VisibleBounds)
        {
            GridCircle VisibleCircle = new GridCircle(VisibleBounds.Center, GridVector2.Distance(VisibleBounds.Center, new GridVector2(VisibleBounds.Left, VisibleBounds.Top)));
            List<Location_CanvasViewModel> listLocationsToDraw = new List<Location_CanvasViewModel>(locations.Count);

            foreach (Location_CanvasViewModel loc in locations)
            {
                if (loc == null)
                    continue;

                if (!loc.VolumePositionHasBeenCalculated)
                    continue;

                //Find out if we should draw the location
                if (loc.TypeCode == LocationType.CIRCLE)
                {
                    if (VisibleCircle.Intersects(loc.VolumePosition, loc.Radius) == false)
                        continue;
                }
                else if (loc.TypeCode == LocationType.POINT)
                {
                    if (VisibleBounds.Contains(loc.VolumePosition) == false)
                        continue;
                }
                else
                {
                    Debug.Fail("Unknown location type");
                }

                Structure ParentStructure = loc.Parent;
                if (ParentStructure == null)
                    continue;

                if (ParentStructure.Type == null)
                    continue;

                listLocationsToDraw.Add(loc);
            }

            return listLocationsToDraw;
        }
Beispiel #26
0
        protected override void OnMouseUp(object sender, MouseEventArgs e)
        {
            if (oldMouse != null)
            {
                if (oldMouse.Button == MouseButtons.Left && this.CommandActive)
                {
                    GridVector2 NewPosition = Parent.ScreenToWorld(e.X, e.Y);

                    double Width = Math.Abs(NewPosition.X - Origin.X);
                    double Height = Math.Abs(NewPosition.Y - Origin.Y);
                    double X = Math.Min(Origin.X, NewPosition.X);
                    double Y = Math.Min(Origin.Y, NewPosition.Y);
                    MyRect = new GridRectangle(new GridVector2(X, Y), Width, Height);

                    Execute();

                    this.Parent.Refresh();
                }
            }
            base.OnMouseUp(sender, e);
        }
Beispiel #27
0
 /// <summary>
 /// Returns a set of tiles which should be rendered in the order returned
 /// </summary>
 /// <param name="VisibleBounds">Visible region of the section</param>
 /// <returns></returns>
 public abstract TilePyramid VisibleTiles(GridRectangle VisibleBounds,
                                          double DownSample
                                          //PORT: bool AsynchTextureLoad
                                          );
Beispiel #28
0
        public List<MappingGridVector2> IntersectingMappedRectangle(GridRectangle gridRect, bool IncludeAdjacent)
        {
            List<MappingGridVector2> foundPoints = IntersectingRectangle(gridRect, this.mapTriangles);
            if (!IncludeAdjacent)
            {
                for (int i = 0; i < foundPoints.Count; i++)
                {
                    if (!gridRect.Contains(foundPoints[i].MappedPoint))
                    {
                        foundPoints.RemoveAt(i);
                        i--;
                    }
                }
            }

            return foundPoints;
        }
Beispiel #29
0
        public override TilePyramid VisibleTiles(GridRectangle VisibleBounds, double DownSample)
        {
            if (VolumeTransform != null)
            {
                GridQuad VisibleQuad = null;
                //Add any corners of the VisibleBounds that we can transform to the list of points
                List<MappingGridVector2> VisiblePoints = VisibleBoundsCorners(VolumeTransform, VisibleBounds);
                if (VisiblePoints.Count == 4)
                {
                    VisiblePoints.Sort(new MappingGridVector2SortByMapPoints());
                    VisibleQuad = new GridQuad(VisiblePoints[0].MappedPoint,
                                               VisiblePoints[1].MappedPoint,
                                               VisiblePoints[2].MappedPoint,
                                               VisiblePoints[3].MappedPoint);
                }

                return VisibleTiles(VisibleBounds, VisibleQuad, DownSample);
            }
            else
            {
                return new TilePyramid(VisibleBounds);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Use this to set points and triangles so we don't have to run the delaunay algorithm.
        /// </summary>
        /// <param name="points"></param>
        /// <param name="triangleIndicies"></param>
        public void SetPointsAndTriangles(MappingGridVector2[] points, int[] triangleIndicies)
        {
            #if DEBUG
            //Check for duplicate points
            for (int i = 1; i < points.Length; i++)
            {
                Debug.Assert(points[i - 1].ControlPoint != points[i].ControlPoint, "Duplicate Points found in transform.  This breaks Delaunay.");
            }
            #endif
            _mapPoints = points;
            _TriangleIndiciesCache = triangleIndicies;

            this._CachedMappedBounds = MappingGridVector2.CalculateMappedBounds(this.mapPoints);
            this._CachedControlBounds = MappingGridVector2.CalculateControlBounds(this.mapPoints);
        }