Example #1
0
        public override Bitmap render(BBox bbox, int width, int height, int elevation)
        {
            Bitmap mapImg = new Bitmap(width, height);
            Graphics gfx = Graphics.FromImage(mapImg);

            gfx.Clear(Color.FromArgb(0, 0, 0, 0));

            Pen pen = new Pen(Color.Red);
            Brush brush = Brushes.Red;

            // draw agent position on the map
            try
            {
                m_scene.ForEachScenePresence(delegate(ScenePresence agent)
                {
                    if (!agent.IsChildAgent)
                    {
                        PointF agentPos = new PointF(agent.OffsetPosition.X, agent.OffsetPosition.Y);
                        PointF agentImgPos = Conversion.Projection(ref agentPos, ref bbox, width, height);
                        RectangleF rect = new RectangleF(agentImgPos.X, agentImgPos.Y, 20, 20); //point width and height hard coded as 20, should be changed
                        gfx.FillEllipse(brush, rect);
                    }
                }
                );
            }
            catch (Exception)
            {
                throw new Exception("agent layer rendering failed");
            }
            gfx.Dispose();
            pen.Dispose();
            return mapImg;
        }
Example #2
0
        /// <summary>
        /// Gets the axis aligned bounding box of the orientated shape.
        /// </summary>
        /// <param name="orientation">The orientation of the shape.</param>
        /// <param name="box">The axis aligned bounding box of the shape.</param>
        public override void GetBoundingBox(ref Matrix3x3 orientation, out BBox box)
        {
            Mathf.Abs(ref orientation, out Matrix3x3 abs);

            Vector3.Transform(ref halfSize, ref abs, out Vector3 temp);

            box.Max = temp;
            Vector3.Negate(ref temp, out box.Min);
        }
Example #3
0
        /// <summary>Adjust the X/Y axis of the chart to cover the given area</summary>
        public void PositionChart(BBox area)
        {
            // Ensure the selection area is >= 1 pixel for width/height
            var sz = ClientToChart(new Size(1, 1));

            XAxis.Set(area.MinX, Math.Max(area.MaxX, area.MinX + sz.Width));
            YAxis.Set(area.MinY, Math.Max(area.MaxY, area.MinY + sz.Height));
            SetCameraFromRange();
        }
Example #4
0
 public override object HitTest(PointT point, Coord radius, out PointT projected)
 {
     projected = point;
     if (!BBox.Inflated(radius, radius).Contains(point))
     {
         return(null);
     }
     return(HitTestPolyline(point, radius, Points, Divisions, out projected));
 }
Example #5
0
        /// <summary>
        /// Checks the AABB of the two rigid bodies.
        /// </summary>
        /// <param name="entity1">The first body.</param>
        /// <param name="entity2">The second body.</param>
        /// <returns>Returns true if an intersection occours.</returns>
        public bool CheckBoundingBoxes(IBroadphaseEntity entity1, IBroadphaseEntity entity2)
        {
            BBox box1 = entity1.BoundingBox;
            BBox box2 = entity2.BoundingBox;

            return((((box1.Max.z >= box2.Min.z) && (box1.Min.z <= box2.Max.z)) &&
                    ((box1.Max.y >= box2.Min.y) && (box1.Min.y <= box2.Max.y))) &&
                   ((box1.Max.x >= box2.Min.x) && (box1.Min.x <= box2.Max.x)));
        }
 /// <summary>
 /// Calculates the bounding box of the sphere.
 /// </summary>
 /// <param name="orientation">The orientation of the shape.</param>
 /// <param name="box">The resulting axis aligned bounding box.</param>
 public override void GetBoundingBox(ref Matrix3x3 orientation, out BBox box)
 {
     box.Min.x = -radius;
     box.Min.y = -radius;
     box.Min.z = -radius;
     box.Max.x = radius;
     box.Max.y = radius;
     box.Max.z = radius;
 }
Example #7
0
        public override void UpdateBounds()
        {
            var boxSize   = new Vector3(Tolerence) * (Vector3.One - Axis);
            var boxLength = Axis * (GizmoSize * (1f + ArrowSize));

            boxSize += boxLength;

            BoundingBox = BBox.FromCenterSize(boxLength / 2f, boxSize);
        }
Example #8
0
        public void BuildBBox()
        {
            var origin      = EnvCell.Position.Origin;
            var orientation = EnvCell.Position.Orientation;
            var translate   = Matrix4x4.CreateTranslation(new Vector3(origin.X, origin.Y, origin.Z));
            var rotate      = Matrix4x4.CreateFromQuaternion(new Quaternion(orientation.X, orientation.Y, orientation.Z, orientation.W));

            BBox = new BBox(Polygons, rotate * translate);
        }
Example #9
0
        public void assertBBox(Geofence Geofence, BBox expected, GeoCoord inside, GeoCoord outside)
        {
            BBox result = new BBox();

            Polygon.bboxFromGeofence(ref Geofence, ref result);
            Assert.True(BBox.bboxEquals(result, expected));
            Assert.True(BBox.bboxContains(result, inside));
            Assert.False(BBox.bboxContains(result, outside));
        }
Example #10
0
        public virtual void Update(float timestep)
        {
            active = false;

            foreach (MassPoint point in points)
            {
                if (point.isActive && !point.isStatic)
                {
                    active = true; break;
                }
            }

            if (!active)
            {
                return;
            }

            box    = BBox.SmallBox;
            volume = 0.0f;
            mass   = 0.0f;

            foreach (MassPoint point in points)
            {
                mass += point.Mass;
                box.AddPoint(point.position);
            }

            box.Min -= new Vector3(TriangleExpansion);
            box.Max += new Vector3(TriangleExpansion);

            foreach (Triangle t in triangles)
            {
                // Update bounding box and move proxy in dynamic tree.
                Vector3 prevCenter = t.boundingBox.Center;
                t.UpdateBoundingBox();

                Vector3 linVel = t.VertexBody1.linearVelocity +
                                 t.VertexBody2.linearVelocity +
                                 t.VertexBody3.linearVelocity;

                linVel *= 1.0f / 3.0f;

                dynamicTree.MoveProxy(t.dynamicTreeID, ref t.boundingBox, linVel * timestep);

                Vector3 v1 = points[t.indices.I0].position;
                Vector3 v2 = points[t.indices.I1].position;
                Vector3 v3 = points[t.indices.I2].position;

                volume -= ((v2.y - v1.y) * (v3.z - v1.z) -
                           (v2.z - v1.z) * (v3.y - v1.y)) * (v1.x + v2.x + v3.x);
            }

            volume /= 6.0f;

            AddPressureForces(timestep);
        }
Example #11
0
        private void GetMap_Click(object sender, EventArgs e)
        {
            var selectedText = cbMapType.SelectedValue.ToString();

            var selectedMap = (GeneralLayers)Enum.Parse(typeof(GeneralLayers), selectedText);

            var left   = Parse(tbLeft.Text);
            var right  = Parse(tbRight.Text);
            var top    = Parse(tbTop.Text);
            var bottom = Parse(tbBottom.Text);

            ActiveBBox = new BBox(left, bottom, right, top);

            int imageY;

            if (ActiveBBox.Ratio > 1)
            {
                var d = 800 / ActiveBBox.Ratio;
                imageY = (int)d;
            }
            else
            {
                imageY = 800;
            }
            int imageX;

            if (ActiveBBox.Ratio > 1)
            {
                imageX = 800;
            }
            else
            {
                var d = 800 * ActiveBBox.Ratio;
                imageX = (int)d;
            }


            var tmr = new GeneralMapRequest
            {
                Layers = selectedMap,
                BBOX   = ActiveBBox,
                WIDTH  = imageX,
                HEIGHT = imageY
            };


            try
            {
                var image = ImageLoader.GetImage(tmr, 1);
                pbMap.Image = image;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Example #12
0
        public override Util.WinForms.HitTestResult HitTest(PointT pos, VectorT hitTestRadius, SelType sel)
        {
            if (!BBox.Inflated(hitTestRadius.X, hitTestRadius.Y).Contains(pos))
            {
                return(null);
            }

            if (sel == SelType.Partial)
            {
                if (PointsAreNear(pos, Points[0], hitTestRadius))
                {
                    return(new HitTestResult(this, Cursors.SizeAll, 0));
                }
                if (PointsAreNear(pos, Points[Points.Count - 1], hitTestRadius))
                {
                    return(new HitTestResult(this, Cursors.SizeAll, Points.Count - 1));
                }
            }
            else if (sel == SelType.Yes)
            {
                for (int i = 0; i < Points.Count; i++)
                {
                    if (PointsAreNear(pos, Points[i], hitTestRadius))
                    {
                        return(new HitTestResult(this, Cursors.SizeAll, i));
                    }
                }
            }

            PointT projected;

            float?where = LLShape.HitTestPolyline(pos, hitTestRadius.X, Points, EmptyList <int> .Value, out projected);
            if (where != null)
            {
                if (sel == SelType.Yes)
                {
                    int seg   = (int)where.Value;
                    var angle = AngleMod8(Points[seg + 1].Sub(Points[seg]));
                    switch (angle & 3)
                    {
                    case 0: return(new HitTestResult(this, Cursors.SizeNS, seg));

                    case 1: return(new HitTestResult(this, Cursors.SizeNESW, seg));

                    case 2: return(new HitTestResult(this, Cursors.SizeWE, seg));

                    case 3: return(new HitTestResult(this, Cursors.SizeNWSE, seg));
                    }
                }
                else
                {
                    return(new HitTestResult(this, Cursors.Arrow, -1));
                }
            }
            return(null);
        }
Example #13
0
        public void BboxIsTransmeridian()
        {
            var bboxNormal = new BBox(1.0m, 0.8m, 1.0m, 0.8m);

            Assert.IsFalse(bboxNormal.IsTransmeridian);

            var bboxTransmeridian = new BBox(1.0m, 0.8m, -Constants.H3.M_PI + 0.3m, Constants.H3.M_PI - 0.1m);

            Assert.IsTrue(bboxTransmeridian.IsTransmeridian);
        }
Example #14
0
        /// <summary>
        /// Creates a new box containing the two given ones.
        /// </summary>
        /// <param name="original">First box.</param>
        /// <param name="additional">Second box.</param>
        /// <param name="result">A JBBox containing the two given boxes.</param>
        public static void CreateMerged(ref BBox original, ref BBox additional, out BBox result)
        {
            Vector3 vector;
            Vector3 vector2;

            Vector3.Min(ref original.Min, ref additional.Min, out vector2);
            Vector3.Max(ref original.Max, ref additional.Max, out vector);
            result.Min = vector2;
            result.Max = vector;
        }
Example #15
0
        public void BboxFromGeofenceNoVertices()
        {
            var geofence = new GeoFence();

            var expected = new BBox(0.0m, 0.0m, 0.0m, 0.0m);

            var result = geofence.ToBBox();

            Assert.AreEqual(result, expected);
        }
Example #16
0
            public void UpdateBoundingBox()
            {
                boundingBox = BBox.SmallBox;
                boundingBox.AddPoint(ref owner.points[indices.I0].position);
                boundingBox.AddPoint(ref owner.points[indices.I1].position);
                boundingBox.AddPoint(ref owner.points[indices.I2].position);

                boundingBox.Min -= new Vector3(owner.triangleExpansion);
                boundingBox.Max += new Vector3(owner.triangleExpansion);
            }
    private string BuildOsmFileRequest(Tile tile)
    {
        BBox bBox = GeoPositioningHelper.GetBBoxFromTile(tile);

        return(string.Format(StringConstants.OSMTileRequestPattern,
                             Convert.ToString(bBox.MinLongitude, CultureInfoHelper.EnUSInfo),
                             Convert.ToString(bBox.MinLatitude, CultureInfoHelper.EnUSInfo),
                             Convert.ToString(bBox.MaxLongitude, CultureInfoHelper.EnUSInfo),
                             Convert.ToString(bBox.MaxLatitude, CultureInfoHelper.EnUSInfo)));
    }
Example #18
0
 /// <summary>
 /// Whether the bounding box contains a given point
 /// </summary>
 /// <param name="box">Bounding box</param>
 /// <param name="point">Point to test</param>
 /// <returns>Whether the point is contained</returns>
 /// <!--
 /// bbox.c
 /// ool bboxContains
 /// -->
 public static bool Contains(this BBox box, GeoCoord point)
 {
     return(point.Latitude >= box.South &&
            point.Latitude <= box.North &&
            box.IsTransmeridian
            // transmeridian case
                ? point.Longitude >= box.West || point.Longitude <= box.East
            // standard case
                : point.Longitude >= box.West && point.Longitude <= box.East);
 }
Example #19
0
        public static LocationRect getLocationRectFromBBox(BBox bbox)
        {
            LocationRect locationRect = new LocationRect(new Location(90, -180), new Location(-90, 180));

            if (bbox != null)
            {
                locationRect = new LocationRect(new Location(bbox.BBox_Upper_Lat, bbox.BBox_Lower_Lon), new Location(bbox.BBox_Lower_Lat, bbox.BBox_Upper_Lon));
            }
            return(locationRect);
        }
Example #20
0
        private void UpdateBBox(ID3D11Device InDevice, ID3D11DeviceContext InDContext)
        {
            // Update vertex buffer
            VertexLayouts.BasicLayout.Vertex[] BBoxVertices = new VertexLayouts.BasicLayout.Vertex[Objects.Count * 8];

            int CurrentBBoxIndex = 0;

            foreach (RenderBoundingBox BBox in Objects.Values)
            {
                VertexLayouts.BasicLayout.Vertex[] Cached = BBox.GetTransformVertices();
                System.Array.Copy(Cached, 0, BBoxVertices, CurrentBBoxIndex * Cached.Length, Cached.Length);
                CurrentBBoxIndex++;
            }

            // Update index buffer
            uint[] BBoxIndices = new uint[Objects.Count * 24];

            CurrentBBoxIndex = 0;
            foreach (RenderBoundingBox BBox in Objects.Values)
            {
                uint[] CopiedIndices = new uint[BBox.Indices.Length];
                for (int i = 0; i < CopiedIndices.Length; i++)
                {
                    int BBoxOffset = (CurrentBBoxIndex * 8);
                    CopiedIndices[i] = (ushort)(BBox.Indices[i] + BBoxOffset);
                }

                System.Array.Copy(CopiedIndices, 0, BBoxIndices, CurrentBBoxIndex * BBox.Indices.Length, BBox.Indices.Length);
                CurrentBBoxIndex++;
            }

            SizeToRender = Objects.Count * 24;
            if (VertexBuffer == null && IndexBuffer == null)
            {
                VertexBuffer = InDevice.CreateBuffer(BindFlags.VertexBuffer, BBoxVertices, 0, ResourceUsage.Dynamic, CpuAccessFlags.Write);
                IndexBuffer  = InDevice.CreateBuffer(BindFlags.IndexBuffer, BBoxIndices, 0, ResourceUsage.Dynamic, CpuAccessFlags.Write);
            }
            else
            {
                // TODO: Templatize this
                MappedSubresource mappedResource = InDContext.Map(VertexBuffer, MapMode.WriteDiscard, MapFlags.None);
                unsafe
                {
                    UnsafeUtilities.Write(mappedResource.DataPointer, BBoxVertices);
                }
                InDContext.Unmap(VertexBuffer);

                mappedResource = InDContext.Map(IndexBuffer, MapMode.WriteDiscard, MapFlags.None);
                unsafe
                {
                    UnsafeUtilities.Write(mappedResource.DataPointer, BBoxIndices);
                }
                InDContext.Unmap(IndexBuffer);
            }
        }
Example #21
0
        public static BBox ComputeBoundingBox(Point3D[] points)
        {
            BBox result = new BBox();

            for (int i = 0; i < points.Length; i++)
            {
                result.Extend(points[i]);
            }

            return(result);
        }
Example #22
0
        /// <summary>
        /// Passes a axis aligned bounding box to the shape where collision
        /// could occour.
        /// </summary>
        /// <param name="box">The bounding box where collision could occur.</param>
        /// <returns>The upper index with which <see cref="SetCurrentShape"/> can be
        /// called.</returns>
        public override int Prepare(ref BBox box)
        {
            // simple idea: the terrain is a grid. x and z is the position in the grid.
            // y the height. we know compute the min and max grid-points. All quads
            // between these points have to be checked.

            // including overflow exception prevention

            if (box.Min.x < boundings.Min.x)
            {
                minX = 0;
            }
            else
            {
                minX = (int)Math.Floor((float)((box.Min.x - sphericalExpansion) / scaleX));
                minX = Math.Max(minX, 0);
            }

            if (box.Max.x > boundings.Max.x)
            {
                maxX = heightsLength0 - 1;
            }
            else
            {
                maxX = (int)Math.Ceiling((float)((box.Max.x + sphericalExpansion) / scaleX));
                maxX = Math.Min(maxX, heightsLength0 - 1);
            }

            if (box.Min.z < boundings.Min.z)
            {
                minZ = 0;
            }
            else
            {
                minZ = (int)Math.Floor((float)((box.Min.z - sphericalExpansion) / scaleZ));
                minZ = Math.Max(minZ, 0);
            }

            if (box.Max.z > boundings.Max.z)
            {
                maxZ = heightsLength1 - 1;
            }
            else
            {
                maxZ = (int)Math.Ceiling((float)((box.Max.z + sphericalExpansion) / scaleZ));
                maxZ = Math.Min(maxZ, heightsLength1 - 1);
            }

            numX = maxX - minX;
            numZ = maxZ - minZ;

            // since every quad contains two triangles we multiply by 2.
            return(numX * numZ * 2);
        }
Example #23
0
        /// <summary>
        /// Gets the center of a bounding box
        /// </summary>
        /// <param name="box">input bounding box</param>
        /// <returns>output center coordinate</returns>
        /// <!--
        /// bbox.c
        /// void bboxCenter
        /// -->
        public static GeoCoord Center(this BBox box)
        {
            decimal latitude = (box.North + box.South) / 2.0m;
            // If the bbox crosses the antimeridian, shift east 360 degrees
            decimal east = box.IsTransmeridian
                               ? box.East + Constants.H3.M_2PI
                               : box.East;
            decimal longitude = ((east + box.West) / 2.0m).ConstrainLongitude();

            return(new GeoCoord(latitude, longitude));
        }
Example #24
0
    public QuadTree(QuadTree parent, BBox bbox, int level)
    {
        this.parent = parent;
        this.bbox   = bbox;
        this.level  = level;
        width       = bbox.xmax - bbox.xmin;
        height      = bbox.ymax - bbox.ymin;
        position    = new Vector3(bbox.xmin + width * 0.5f, bbox.ymin + height * 0.5f, 0.0f);

        objectList = new List <PPObject>();
    }
Example #25
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            String bboxString = "";

            if (value is BBox)
            {
                BBox bbox = value as BBox;
                bboxString = "(" + bbox.BBox_Lower_Lon + ", " + bbox.BBox_Lower_Lat + ", " + bbox.BBox_Upper_Lon + ", " + bbox.BBox_Upper_Lat + ")";
            }
            return(bboxString);
        }
Example #26
0
 public Annulus(Vector3 cen, Vector3 norm, float i, float w, string name)
     : base(name)
 {
     center         = cen;
     normal         = norm;
     inner_radius   = i;
     wall_thickness = w;
     bbox           = new BBox(center.X - i - w, center.X + i + w, center.Y - MathUtil.Epsilon, center.Y + MathUtil.Epsilon, center.Z - i - w, center.Z + i + w);
     i_squared      = i * i;
     w_squared      = (i + w) * (i + w);
 }
Example #27
0
        /// <summary>
        /// Checks whether another bounding box is inside, outside or intersecting
        /// this box.
        /// </summary>
        /// <param name="box">The other bounding box to check.</param>
        /// <returns>The ContainmentType of the box.</returns>
        public ContainmentType Contains(ref BBox box)
        {
            ContainmentType result = ContainmentType.Disjoint;

            if ((((this.Max.x >= box.Min.x) && (this.Min.x <= box.Max.x)) && ((this.Max.y >= box.Min.y) && (this.Min.y <= box.Max.y))) && ((this.Max.z >= box.Min.z) && (this.Min.z <= box.Max.z)))
            {
                result = ((((this.Min.x <= box.Min.x) && (box.Max.x <= this.Max.x)) && ((this.Min.y <= box.Min.y) && (box.Max.y <= this.Max.y))) && ((this.Min.z <= box.Min.z) && (box.Max.z <= this.Max.z))) ? ContainmentType.Contains : ContainmentType.Intersects;
            }

            return(result);
        }
Example #28
0
        public void BboxFromLinkedGeoLoopNoVertices()
        {
            var loop     = new LinkedGeoLoop();
            var expected = new BBox(0.0m, 0.0m, 0.0m, 0.0m);

            var result = loop.ToBBox();

            Assert.AreEqual(result, expected);

            loop.Clear();
        }
Example #29
0
        // Constructor
        public BoardController(int size)
        {
            mOpenExitStack = new OpenExitStack(size);

            mSize = size;

            // setup bounds
            mBBox = new BBox(mSize);

            // for tracking occupied spaces
            InitializeGameGrid();
        }
Example #30
0
        /*
         * def getMap (self, param):
         * bbox  = map(float, param["bbox"].split(","))
         * layer = self.getLayer(param["layers"])
         * tile  = layer.getTile(bbox)
         * if not tile:
         * raise Exception(
         * "couldn't calculate tile index for layer %s from (%s)"
         * % (layer.name, bbox))
         * return tile
         */
        #endregion
        ITile GetMap(NameValueCollection param)
        {
            var bbox  = new BBox(param["bbox"]);
            var layer = GetLayer(param["layers"]);
            var tile  = layer.GetTile(bbox);

            if (tile == null)
            {
                throw new Exception(string.Format("couldn't calculate tile index for layer {0} from ({1})", layer.Name, bbox));
            }
            return(tile);
        }
        protected void UpdateInternalBoundingBox()
        {
            mInternalBBox.Min = new Vector3(float.MaxValue);
            mInternalBBox.Max = new Vector3(float.MinValue);

            for (int i = 0; i < shapes.Length; i++)
            {
                shapes[i].UpdateBoundingBox();

                BBox.CreateMerged(ref mInternalBBox, ref shapes[i].boundingBox, out mInternalBBox);
            }
        }
Example #32
0
        public override Bitmap render(BBox bbox, int width, int height, int elevation)
        {
            Bitmap gradientmapLd = new Bitmap("defaultstripe.png");
            int pallete = gradientmapLd.Height;
            ITerrainChannel heightMap = m_scene.Heightmap;
            Bitmap WholeRegionbmp = new Bitmap((int)bbox.Width, (int)bbox.Height);
            Color[] colours = new Color[pallete];
            for (int i = 0; i < pallete; i++)
            {
                colours[i] = gradientmapLd.GetPixel(0, i);
            }

            for (int y = 0; y < (int)bbox.Height; y++)
            {
                for (int x = 0; x < (int)bbox.Width; x++)
                {
                    // 512 is the largest possible height before colours clamp
                    int colorindex;
                    if (elevation >= heightMap[x, y])
                    {
                        colorindex = (int)(Math.Max(Math.Min(1.0, heightMap[x, y] / 512.0), 0.0) * (pallete - 1));
                    }
                    else
                        colorindex = (int)(Math.Max(Math.Min(1.0, elevation / 512.0), 0.0) * (pallete - 1));

                    // Handle error conditions
                    if (colorindex > pallete - 1 || colorindex < 0)
                        WholeRegionbmp.SetPixel(x, (int)bbox.Height - y - 1, Color.Red);
                    else
                        WholeRegionbmp.SetPixel(x, (int)bbox.Height - y - 1, colours[colorindex]);
                }
            }

            Bitmap RegionBBoxBmp = null;
            try
            {
                RegionBBoxBmp = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage(RegionBBoxBmp))
                {
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(WholeRegionbmp, new Rectangle(0, 0, width, height));
                }
            }
            catch
            {
                if (RegionBBoxBmp != null) RegionBBoxBmp.Dispose();
                throw;
            }
            return RegionBBoxBmp;
        }
Example #33
0
        public KDTree(List<Sphere> spheres, int maxPrimsPerNode)
        {
            // Store reference
            _primitives = spheres;
            _nodes = new KdTreeNode[0];

            _maxPrims = maxPrimsPerNode;

            // Guess a usefull bound on the maximum tree depth
            _maxDepth = 8 + (int)(1.3*Math.Log(spheres.Count, 2));

            // calculate primitive bounds, plus overall scene bounds
            BBox[] allPrimBounds = new BBox[_primitives.Count];
            for (int i=0; i<_primitives.Count; i++)
            {
                allPrimBounds[i] = _primitives[i].getBounds();
                _bounds.union( allPrimBounds[i] );
            }

            // Allocate temporary working space
            BoundEdge[][] edges = new BoundEdge[3][];
            for (int i = 0; i < 3; i++) { edges[i] = new BoundEdge[2 * _primitives.Count]; }

            // Allocate array to store overlaping primitive indices
            int[] primNums = new int[_primitives.Count];
            int primNumsBase = 0;
            for(int i=0; i<_primitives.Count; i++) { primNums[i]=i; }

            // Arries to hold subarries of primitive indices
            int[] prims0 = new int[_primitives.Count];
            int prims1Base = 0;
            int[] prims1 = new int[ (_maxDepth+1) * _primitives.Count];

            Console.WriteLine("Building Tree with " + _primitives.Count + " primitives...\n");

            // Start recursive construction tree
            buildTree(0, _bounds, allPrimBounds, primNums, primNumsBase, _primitives.Count, _maxDepth, edges, prims0, prims1, prims1Base, 0);

            Console.WriteLine("Finished building tree with " + nextFreeNode + " nodes");
        }
Example #34
0
            public static bool IntersectBox(BBox box, RayInfo ray)
            {
                float t0 = ray.Min;
                float t1 = ray.Max;

                var rayInvDir = 1f / ray.Dir;
                //1f /ray.Dir;

                float invDirX = rayInvDir.x;
                if (!process_box_coord(ref t0, ref t1, box.Min.x - ray.Org.x, box.Max.x - ray.Org.x, invDirX))
                    return false;

                float invDirY = rayInvDir.y;
                if (!process_box_coord(ref t0, ref t1, box.Min.y - ray.Org.y, box.Max.y - ray.Org.y, invDirY))
                    return false;

                float invDirZ = rayInvDir.z;
                if (!process_box_coord(ref t0, ref t1, box.Min.z - ray.Org.z, box.Max.z - ray.Org.z, invDirZ))
                    return false;
                return true;
            }
Example #35
0
        private void buildTree(	int nodeNum, BBox nodeBounds, BBox[] allPrimBounds, 
								int[] primNums, int primNumsBase, 
								int nPrimitives, int depth, BoundEdge[][] edges,
								int[] prims0, 
								int[] prims1, int prims1base, 
								int badRefines)
        {
            string indent = "".PadLeft(_maxDepth - depth);

            if (nextFreeNode == nAllocedNodes)
            {
                int nAlloc = Math.Max(2*nAllocedNodes, 512);
                KdTreeNode[] n = new KdTreeNode[nAlloc];
                if (nAllocedNodes > 0)
                    Array.Copy(_nodes, n, nAllocedNodes);
                _nodes = n;
                nAllocedNodes = nAlloc;
            }
            ++nextFreeNode;

            // *** Termination: Stop recursion if we have few enough nodes or the max depth has been reached ***
            if (nPrimitives <= _maxPrims || depth == 0)
            {
                _nodes[nodeNum] = KdTreeNode.makeLeaf(primNums, primNumsBase, nPrimitives);
                #if DEBUG
                Console.WriteLine(indent + _nodes[nodeNum]);
                #endif
                return;
            }

            // *** Not reached termination, so pick split plane and continue recursion ***
            Axis bestAxis = Axis.none;
            int bestOffset = -1;
            float bestCost = float.PositiveInfinity;
            float oldCost = iCost * (float)nPrimitives;
            float totalSA = nodeBounds.surfaceArea();
            float invTotalSA = 1.0f/totalSA;
            Vector3 d = nodeBounds.pMax - nodeBounds.pMin;
            Axis axis = nodeBounds.longestAxis();	// Start by checking the longest axis
            int retries = 0;
            retrySplit:

            // Fill edge lists
            for (int i=0; i<nPrimitives; i++)
            {
                int primIndex = primNums[primNumsBase + i];
                BBox bbox = allPrimBounds[primIndex];
                edges[(int)axis][2*i] = new BoundEdge( getAxisVal(bbox.pMin, axis), primIndex, true);
                edges[(int)axis][2*i+1] = new BoundEdge(getAxisVal(bbox.pMax, axis), primIndex, false);
            }
            Array.Sort(edges[(int)axis], 0, 2*nPrimitives);	// sort the edges of the first n primitives (2*n edges)

            // Find the best split by checking cost of every possible split plane
            int nBelow = 0, nAbove = nPrimitives;
            for (int i=0; i<2*nPrimitives; i++)
            {
                if( edges[(int)axis][i].type == BoundType.End) --nAbove;
                float edgeT = edges[(int)axis][i].t;
                if (edgeT > getAxisVal(nodeBounds.pMin, axis) &&
                    edgeT < getAxisVal(nodeBounds.pMax, axis) )
                {
                    // Compute split cost for the ith edge
                    Axis otherAxis0 = (Axis) (	((int)axis+1)	% 3);
                    Axis otherAxis1 = (Axis) (	((int)axis+2)	% 3);
                    float belowSA = 2* (getAxisVal(d, otherAxis0) * getAxisVal(d, otherAxis1) +
                                        (edgeT - getAxisVal(nodeBounds.pMin, axis)) *
                                        (getAxisVal(d, otherAxis0) + getAxisVal(d, otherAxis1)));
                    float aboveSA = 2*(getAxisVal(d, otherAxis0) * getAxisVal(d, otherAxis1) +
                                        (getAxisVal(nodeBounds.pMax, axis) - edgeT) *
                                        (getAxisVal(d, otherAxis0) + getAxisVal(d, otherAxis1)));
                    float pBelow = belowSA * invTotalSA;
                    float pAbove = aboveSA * invTotalSA;
                    float eb = (nAbove == 0 || nBelow == 0) ? emptyBonus : 0;
                    float cost = tCost + iCost * (1-eb) * (pBelow * nBelow + pAbove * nAbove);

                    // Save this split if it is better the previous split position
                    if(cost < bestCost)
                    {
                        bestCost = cost;
                        bestAxis = axis;
                        bestOffset = i;
                    }

                }
                if (edges[(int)axis][i].type == BoundType.Start) ++nBelow;
            }

            // Create a leaf node if no good split was found
            if(bestAxis == Axis.none && retries < 2)
            {
                ++retries;
                axis = (Axis) ( ((int)axis+1) % 3);
                goto retrySplit;
            }
            if (bestCost > oldCost) ++badRefines;
            if (( bestCost > 4.0f * oldCost && nPrimitives < 16) || bestAxis == Axis.none || badRefines == 3)
            {
                _nodes[nodeNum] = KdTreeNode.makeLeaf(primNums, primNumsBase, nPrimitives);
                #if DEBUG
                Console.WriteLine(indent + _nodes[nodeNum] + " (split failure)");
                #endif
                return;
            }

            // Classifiy primitives with respect to split
            int n0=0, n1=0;
            for (int i=0; i<bestOffset; i++)
            {
                if(edges[(int)bestAxis][i].type == BoundType.Start)
                    prims0[n0++] = edges[(int)bestAxis][i].primNum;
            }
            for (int i=bestOffset+1; i<2*nPrimitives; i++)
            {
                if(edges[(int)bestAxis][i].type == BoundType.End)
                    prims1[prims1base + n1++] = edges[(int)bestAxis][i].primNum;
            }

            // Ititalize child nodes
            float tsplit = edges[(int)bestAxis][bestOffset].t;
            BBox bounds0 = nodeBounds, bounds1 = nodeBounds;
            setAxisVal(ref bounds0.pMax, bestAxis, tsplit);
            setAxisVal(ref bounds1.pMin, bestAxis, tsplit);

            #if DEBUG
            KdTreeNode testNode = KdTreeNode.makeInternal(bestAxis, nextFreeNode, tsplit);
            int[] aboveIndices = new int[n1];
            int[] belowIndices = new int[n0];
            Array.Copy(prims0, belowIndices, n0);
            Array.Copy(prims1, prims1base, aboveIndices, 0, n1);

            Console.WriteLine(indent + testNode);
            Console.WriteLine(indent + " Above: { " + String.Join(",", aboveIndices) + " }");
            Console.WriteLine(indent + " Below: { " + String.Join(",", belowIndices) + " }");
            #endif

            buildTree(nodeNum+1, bounds0, allPrimBounds, prims0, 0, n0,
                        depth-1, edges, prims0, prims1, prims1base+nPrimitives-1, badRefines);

            int aboveChild = nextFreeNode;
            _nodes[nodeNum] = KdTreeNode.makeInternal(bestAxis, aboveChild, tsplit);

            buildTree(aboveChild, bounds1, allPrimBounds, prims1, prims1base, n1,
                        depth-1, edges, prims0, prims1, prims1base+nPrimitives-1, badRefines);
        }
Example #36
0
 public void AddBox(int x, int y, int width, int height, BBox type)
 {
     switch (type)
     {
         case BBox.Paragraph:
             _paragraphs.Add(FixRect(x, y, width, height));
             break;
         case BBox.Column:
             _columns.Add(FixRect(x, y, width, height));
             break;
         case BBox.Line:
             _lines.Add(FixRect(x, y, width, height));
             break;
         case BBox.Character:
             _characters.Add(FixRect(x, y, width, height));
             break;
     }
 }
Example #37
0
        public override Bitmap render(BBox bbox, int width, int height, int elevation)
        {
            LLVector3CL[] pos = new LLVector3CL[m_volumeCount];
            LLVector3CL[] sca = new LLVector3CL[m_volumeCount];
            LLQuaternionCL[] rot = new LLQuaternionCL[m_volumeCount];
            LLVolumeParamsCL[] vop = new LLVolumeParamsCL[m_volumeCount];
            TextureEntryListCL[] tel = new TextureEntryListCL[m_volumeCount];
            for (int i = 0; i < m_volumeCount; i++)
            {
                pos[i] = m_positions[i];
                sca[i] = m_scales[i];
                rot[i] = m_rotations[i];
                vop[i] = m_volumeParams[i];
                tel[i] = m_textureEntryLists[i];
            }
            MapRenderCL mr = new MapRenderCL();
            string regionID = m_scene.RegionInfo.RegionID.ToString();

            mr.mapRender(
                regionID,
                bbox.MinX, bbox.MinY, 0, bbox.MaxX, bbox.MaxY, (float)elevation,
                vop,
                m_volumeCount,
                pos,
                rot,
                sca,
                tel,
                width,
                height,
                "e:\\\\MonoImage\\\\",
                "e:\\\\regionMap\\\\");
            Bitmap bmp = new Bitmap("e:\\\\regionMap\\\\" + regionID + ".bmp");
            bmp.MakeTransparent(Color.FromArgb(0, 0, 0, 0));
            return bmp;
        }
Example #38
0
 /// <summary>
 /// generate the projection Bitmap of a layer
 /// </summary>
 /// <param name="bbox">the boundary of the layer to be drawn</param>
 /// <param name="height">height of the output bitmap</param>
 /// <param name="weight">weight of the output bitmap</param>
 public abstract Bitmap render(BBox bbox, int height, int weight, int elevation);
Example #39
0
 public BBox(BBox b)
 {
     this.Max = b.Max;
     this.Min = b.Min;
 }
Example #40
0
        public override Bitmap render(BBox bbox, int width, int height, int elevation)
        {
            MapRenderCL mr = new MapRenderCL();
            string regionID = m_scene.RegionInfo.RegionID.ToString();
            try
            {
                bool result = mr.mapRender(regionID,
                    bbox.MinX, bbox.MinY, 0, bbox.MaxX, bbox.MaxY, (float)elevation,
                    m_primitiveList.ToArray(), m_primitiveList.Count,
                    width, height,
                    MapPath);

                if (result)
                {
                    Bitmap bmp = new Bitmap(MapPath + regionID + ".bmp");
                    bmp.MakeTransparent(Color.FromArgb(0, 0, 0, 0));
                    return bmp;
                }
                else
                {
                    Bitmap bmp = new Bitmap(width, height);
                    return bmp;
                }
            }
            catch (Exception e)
            {
                m_log.Error(e.Message + e.StackTrace);
                Bitmap bmp = new Bitmap(width, height);
                return bmp;
            }
        }