protected void BuildTriangleList() { if (_TriangleList != null) return; _TriangleList = new List<MappingGridTriangle>[this._mapPoints.Length]; for (int i = 0; i < _TriangleIndiciesCache.Length; i += 3) { int iOne = _TriangleIndiciesCache[i]; int iTwo = _TriangleIndiciesCache[i + 1]; int iThree = _TriangleIndiciesCache[i + 2]; //Safe to go straight into the cache since we looked at TriangleIndicies to initialize list MappingGridTriangle newTri = new MappingGridTriangle(mapPoints, _TriangleIndiciesCache[i], _TriangleIndiciesCache[i + 1], _TriangleIndiciesCache[i + 2]); //Get the list for each point and add a reference to the triangle if (_TriangleList[iOne] == null) { _TriangleList[iOne] = new List<MappingGridTriangle>(6); } _TriangleList[iOne].Add(newTri); if (_TriangleList[iTwo] == null) { _TriangleList[iTwo] = new List<MappingGridTriangle>(6); } _TriangleList[iTwo].Add(newTri); if (_TriangleList[iThree] == null) { _TriangleList[iThree] = new List<MappingGridTriangle>(6); } _TriangleList[iThree].Add(newTri); } }
public static MappingGridTriangle TriangleForPoint(int GridSizeX, int GridSizeY, GridRectangle Bounds, MappingGridVector2[] points, int[] TriIndicies, GridVector2 Point) { //Having a smaller epsilon caused false positives. //We just want to know if we are close enough to check with the more time consuming math double epsilon = 5; if (Point.X < Bounds.Left - epsilon) return null; if (Point.X > Bounds.Right + epsilon) return null; if (Point.Y > Bounds.Top + epsilon) return null; if (Point.Y < Bounds.Bottom - epsilon) return null; double OffsetX = Point.X - Bounds.Left; double OffsetY = Point.Y - Bounds.Bottom; double X = (OffsetX / Bounds.Width) * (GridSizeX-1); double Y = (OffsetY / Bounds.Height) * (GridSizeY-1); int iX = (int)X; int iY = (int)Y; //This gives us the grid coordinates which contains two triangles, however there are two triangles. If the fractional parts add up to a number greater than one it is the upper triangle. bool IsUpper = (X - iX) + (Y - iY) > 1; //Check edge case where point is exactly on the right edge of the boundary if (OffsetX + double.Epsilon >= Bounds.Width ) { IsUpper = true; iX--; } else if (OffsetY + double.Epsilon >= Bounds.Height) { IsUpper = true; iY--; } else { IsUpper = (X - iX) + (Y - iY) > 1; } int iTri = (iY * 2) + ((GridSizeY-1) * 2 * iX); //int iTri = (iX * 2) + ((GridSizeX-1) * 2 * iY); iTri += IsUpper ? 1:0; iTri *= 3;//Multiply by three to get the triangle offset MappingGridTriangle mapTri = new MappingGridTriangle(points, TriIndicies[iTri], TriIndicies[iTri + 1], TriIndicies[iTri + 2]); Debug.Assert(mapTri.IntersectsMapped(Point), "Calculated GridTransform does not intersect requested point"); return mapTri; }