Пример #1
0
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin();

            _spriteBatch.DrawPolygon(_polygonExtent, Color.Black);
            _spriteBatch.DrawPolygonExtent(_polygonExtent, RenderParams.Debug);

            for (int i = 0; i < _polygonExtent.NumSides; i++)
            {
                int     nextIndex    = (i + 1) % _polygonExtent.NumSides;
                Vector2?intersection = ShapeUtility.FindYIntersectionPoint(_polygonExtent.Vertices[i], _polygonExtent.Vertices[nextIndex], _yValue);
                if (intersection != null)
                {
                    _markerIntersect_Blue.RenderingExtent.Anchor = intersection.Value;
                    _spriteBatch.DrawSprite(_markerIntersect_Blue);
                }
            }

            _spriteBatch.DrawSprite(_markerPoint_Red);

            if (_polygonExtent.ContainsPoint(new Vector2(_xValue, _yValue)))
            {
                _spriteBatch.DrawString(_insidePolygon);
            }

            _spriteBatch.End();

            base.Draw(gameTime);
        }
        internal static CSGBrush CreateBrush(UnityEngine.Transform parent, string brushName, ControlMesh controlMesh, Shape shape)
        {
            var gameObject = OperationsUtility.CreateGameObject(parent, brushName, false);

            if (!gameObject)
            {
                return(null);
            }
            var brush = gameObject.AddComponent <CSGBrush>();

            if (!brush)
            {
                return(null);
            }
            brush.ControlMesh = controlMesh;
            brush.Shape       = shape;
            if (brush.ControlMesh != null)
            {
                brush.ControlMesh.SetDirty();
            }
            if (brush.Shape != null)
            {
                ShapeUtility.EnsureInitialized(brush.Shape);
            }
            return(brush);
        }
        public static bool SetBrushFromPlanes(CSGBrush brush, UnityEngine.Plane[] planes, UnityEngine.Vector3[] tangents = null, UnityEngine.Vector3[] binormals = null, UnityEngine.Material[] materials = null, UnityEngine.Matrix4x4[] textureMatrices = null, TextureMatrixSpace textureMatrixSpace = TextureMatrixSpace.WorldSpace)
        {
            if (!brush)
            {
                return(false);
            }

            ControlMesh controlMesh;
            Shape       shape;

            if (!CreateControlMeshFromPlanes(out controlMesh, out shape, planes, tangents, binormals, materials, textureMatrices, textureMatrixSpace))
            {
                return(false);
            }

            brush.ControlMesh = controlMesh;
            brush.Shape       = shape;
            if (brush.ControlMesh != null)
            {
                brush.ControlMesh.SetDirty();
            }
            if (brush.Shape != null)
            {
                ShapeUtility.EnsureInitialized(brush.Shape);
            }
            return(true);
        }
Пример #4
0
        public static void StoreSelfExplanationTextToSlide(List <ExplanationItem> selfExplanationClickItems,
                                                           PowerPointSlide slide)
        {
            string shapeName = ELearningLabText.ELearningLabTextStorageShapeName;

            slide.DeleteShapeWithName(shapeName);
            List <Dictionary <string, string> > selfExplanationText =
                ConvertListToDictionary(selfExplanationClickItems);
            XElement textInxml = new XElement(ELearningLabText.SelfExplanationTextIdentifier,
                                              selfExplanationText.Select(kv =>
                                                                         new XElement(ELearningLabText.SelfExplanationItemIdentifier,
                                                                                      from text in kv select new XElement(text.Key, text.Value))));
            Shape shape = ShapeUtility.InsertSelfExplanationTextBoxToSlide(slide, shapeName, textInxml.ToString());
        }
Пример #5
0
        /// <summary>
        /// 导出所有图幅号到shape文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonTFHExportShp_Click(object sender, EventArgs e)
        {
            MapScaleObject scaleObj   = this.comboBoxLTRBMapScale.SelectedItem as MapScaleObject;
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter           = "Shape文件(*.shp)|*.*|所有文件(*.*)|*.*";
            saveDialog.FilterIndex      = 1;
            saveDialog.RestoreDirectory = true;
            saveDialog.FileName         = "LB-" + scaleObj.Scale.ToString();
            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string        fileName = saveDialog.FileName;
                List <string> xyList   = new List <string>();
                foreach (TFHObject obj in this.checkedListBoxLTRBTFHs.Items)
                {
                    string   xy  = string.Empty;
                    string[] xys = obj.Extent.Split(',');
                    if (xys.Length == 4)
                    {
                        double ltl = double.Parse(xys[0]);
                        double ltb = double.Parse(xys[1]);
                        double rbl = double.Parse(xys[2]);
                        double rbb = double.Parse(xys[3]);

                        xy += string.Format("{0},", obj.TFH);
                        xy += string.Format("{0} {1},", ltl, rbb);
                        xy += string.Format("{0} {1},", ltl, ltb);
                        xy += string.Format("{0} {1},", rbl, ltb);
                        xy += string.Format("{0} {1},", rbl, rbb);
                        xy += string.Format("{0} {1}", ltl, rbb);
                        xyList.Add(xy);
                    }
                }

                try
                {
                    ShapeUtility.ExportShapeFile(fileName, xyList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Пример #6
0
        private static Shape InsertCalloutShapeToSlide(PowerPointSlide slide, string calloutText, int tagNo)
        {
            string shapeName = string.Format(ELearningLabText.CalloutShapeNameFormat, tagNo);

            if (slide.ContainShapeWithExactName(shapeName))
            {
                Shape shape = ShapeUtility.ReplaceTextForShape(slide.GetShapeWithName(shapeName)[0], calloutText);
                templatedShape = shape;
                return(shape);
            }
            try
            {
                return(ShapeUtility.InsertTemplatedShapeToSlide(slide, templatedShape, shapeName, calloutText));
            }
            catch
            {
                return(ShapeUtility.InsertDefaultCalloutBoxToSlide(slide, shapeName, calloutText));
            }
        }
        internal static CSGBrush CreateBrushComponent(UnityEngine.GameObject gameObject, ControlMesh controlMesh, Shape shape)
        {
            var brush = gameObject.AddComponent <CSGBrush>();

            if (!brush)
            {
                return(null);
            }
            brush.ControlMesh = controlMesh;
            brush.Shape       = shape;
            if (brush.ControlMesh != null)
            {
                brush.ControlMesh.SetDirty();
            }
            if (brush.Shape != null)
            {
                ShapeUtility.EnsureInitialized(brush.Shape);
            }
            return(brush);
        }
Пример #8
0
        public AreaStatistics(IShapeCollection shapes)
        {
            this.Areas = new List <double>();

            this.NumberOfPoints = 0;

            Threshold = 0;

            foreach (ISimplePoints item in shapes)
            {
                this.NumberOfPoints += item.Points.Length;

                var areas = ShapeUtility.GetAreas(item.Points);

                if (areas != null && areas.Length > 0)
                {
                    this.Areas.AddRange(areas);
                }
            }
        }
Пример #9
0
        private static Shape InsertCaptionShapeToSlide(PowerPointSlide slide, string captionText, int tagNo)
        {
            string shapeName   = string.Format(ELearningLabText.CaptionShapeNameFormat, tagNo);
            float  slideHeight = PowerPointPresentation.Current.SlideHeight;

            if (slide.ContainShapeWithExactName(shapeName))
            {
                Shape shape = ShapeUtility.ReplaceTextForShape(slide.GetShapeWithName(shapeName)[0], captionText);
                shape.Visible  = Microsoft.Office.Core.MsoTriState.msoTrue;
                templatedShape = shape;
                shape.Top      = slideHeight - shape.Height;
                return(shape);
            }
            try
            {
                return(ShapeUtility.InsertTemplatedShapeToSlide(slide, templatedShape, shapeName, captionText));
            }
            catch
            {
                return(ShapeUtility.InsertDefaultCaptionBoxToSlide(slide, shapeName, captionText));
            }
        }
Пример #10
0
        public AngleStatistics(IShapeCollection shapes)
        {
            this.Angles = new List <double>();

            this.NumberOfPoints = 0;

            Threshold = 0;

            foreach (ISimplePoints item in shapes)
            {
                this.NumberOfPoints += item.Points.Length;

                var areas = ShapeUtility.GetCosineOfAngles(item.Points);

                if (areas != null && areas.Length > 0)
                {
                    this.Angles.AddRange(areas);
                }
            }

            RaisePropertyChanged("Average");
            RaisePropertyChanged("StandardDeviation");
            RaisePropertyChanged("Description");
        }
        public static bool SetBrushCubeMesh(CSGBrush brush, UnityEngine.Vector3 size)
        {
            if (!brush)
            {
                return(false);
            }

            ControlMesh controlMesh;
            Shape       shape;

            BrushFactory.CreateCubeControlMesh(out controlMesh, out shape, size);

            brush.ControlMesh = controlMesh;
            brush.Shape       = shape;
            if (brush.ControlMesh != null)
            {
                brush.ControlMesh.SetDirty();
            }
            if (brush.Shape != null)
            {
                ShapeUtility.EnsureInitialized(brush.Shape);
            }
            return(true);
        }
Пример #12
0
        private void buttonExportXYTFHShape_Click(object sender, EventArgs e)
        {
            if (this.m_AllTFHS.Count > 0)
            {
                this.m_CurrentSpheroid = (Spheroid)int.Parse(this.comboBoxCoordinateSystem.SelectedValue.ToString());
                this.m_CoordHelper     = CoordinateFactory.CreateCoordinate(this.m_CurrentSpheroid);
                MapScaleObject scaleObj = this.comboBoxLTRBMapScale.SelectedItem as MapScaleObject;

                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter           = "Shape文件(*.shp)|*.*|所有文件(*.*)|*.*";
                saveDialog.FilterIndex      = 1;
                saveDialog.RestoreDirectory = true;
                saveDialog.FileName         = "XY-" + scaleObj.Scale.ToString();
                if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string        fileName = saveDialog.FileName;
                    List <string> xyList   = new List <string>();
                    //获取第一个和最后一格
                    TFHObject firstTFHObj = null;
                    TFHObject endTFHObj   = null;
                    int       tmpHs       = 0;
                    int       tmpLs       = 0;
                    firstTFHObj = this.m_AllTFHS[0];
                    endTFHObj   = this.m_AllTFHS[this.m_AllTFHS.Count - 1];
                    for (int i = 0; i < this.m_AllTFHS.Count; i++)
                    {
                        if (this.m_AllTFHS[i].H1 == firstTFHObj.H1)
                        {
                            tmpLs++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    tmpHs = this.m_AllTFHS.Count / tmpLs;

                    double   ltYe, ltXn, rbYe, rbXn;
                    LonWide  lw         = (LonWide)int.Parse(this.comboBoxLonWide.SelectedValue.ToString());
                    int      delno      = int.Parse(this.textBoxDELNO.Text.Trim());
                    string[] firstTLXYs = firstTFHObj.Extent.Split(',');
                    string[] endRBXYs   = endTFHObj.Extent.Split(',');
                    double   ltl        = double.Parse(firstTLXYs[0]);
                    double   ltb        = double.Parse(firstTLXYs[1]);
                    double   rbl        = double.Parse(endRBXYs[2]);
                    double   rbb        = double.Parse(endRBXYs[3]);
                    this.m_CoordHelper.GaussPrjCalculate(ltl, ltb, lw, delno, out ltYe, out ltXn);
                    this.m_CoordHelper.GaussPrjCalculate(rbl, rbb, lw, delno, out rbYe, out rbXn);
                    double rXn = 0, rYe = 0;
                    rXn = Math.Abs((ltXn - rbXn) / tmpHs);
                    rYe = Math.Abs((rbYe - ltYe) / tmpLs);

                    for (int i = 0; i < this.m_AllTFHS.Count; i++)
                    {
                        double tmpLTYe = 0, tmpLTXn = 0, tmpRBYe = 0, tmpRBXn = 0;
                        int    tmpH = (int)(Math.Floor((double)(i / tmpLs)));
                        int    tmpL = (int)(i % tmpLs);
                        string xy   = string.Empty;

                        tmpLTYe = ltYe + rYe * tmpL;
                        tmpLTXn = ltXn - rXn * tmpH;
                        tmpRBYe = ltYe + rYe * (tmpL + 1);
                        tmpRBXn = ltXn - rXn * (tmpH + 1);

                        xy += string.Format("{0},", this.m_AllTFHS[i].TFH);
                        xy += string.Format("{0} {1},", tmpLTYe, tmpRBXn);
                        xy += string.Format("{0} {1},", tmpLTYe, tmpLTXn);
                        xy += string.Format("{0} {1},", tmpRBYe, tmpLTXn);
                        xy += string.Format("{0} {1},", tmpRBYe, tmpRBXn);
                        xy += string.Format("{0} {1}", tmpLTYe, tmpRBXn);
                        xyList.Add(xy);
                    }
                    try
                    {
                        ShapeUtility.ExportShapeFile(fileName, xyList);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
        internal static bool CreateCubeControlMesh(out ControlMesh controlMesh, out Shape shape, UnityEngine.Vector3 min, UnityEngine.Vector3 max, UnityEngine.Material material = null)
        {
            if (min.x > max.x)
            {
                float x = min.x; min.x = max.x; max.x = x;
            }
            if (min.y > max.y)
            {
                float y = min.y; min.y = max.y; max.y = y;
            }
            if (min.z > max.z)
            {
                float z = min.z; min.z = max.z; max.z = z;
            }

            if (min.x == max.x || min.y == max.y || min.z == max.z)
            {
                shape       = null;
                controlMesh = null;
                return(false);
            }

            controlMesh          = new ControlMesh();
            controlMesh.Vertices = new []
            {
                new Vector3(min.x, min.y, min.z),       // 0
                new Vector3(min.x, max.y, min.z),       // 1
                new Vector3(max.x, max.y, min.z),       // 2
                new Vector3(max.x, min.y, min.z),       // 3

                new Vector3(min.x, min.y, max.z),       // 4
                new Vector3(max.x, min.y, max.z),       // 5
                new Vector3(max.x, max.y, max.z),       // 6
                new Vector3(min.x, max.y, max.z)        // 7
            };

            controlMesh.Edges = new []
            {
                new HalfEdge {
                    PolygonIndex = 0, TwinIndex = 21, VertexIndex = 0
                },                                                                      //  0
                new HalfEdge {
                    PolygonIndex = 0, TwinIndex = 8, VertexIndex = 1
                },                                                                      //  1
                new HalfEdge {
                    PolygonIndex = 0, TwinIndex = 12, VertexIndex = 2
                },                                                                      //  2
                new HalfEdge {
                    PolygonIndex = 0, TwinIndex = 17, VertexIndex = 3
                },                                                                      //  3

                new HalfEdge {
                    PolygonIndex = 1, TwinIndex = 10, VertexIndex = 4
                },                                                                      //  4
                new HalfEdge {
                    PolygonIndex = 1, TwinIndex = 23, VertexIndex = 5
                },                                                                      //  5
                new HalfEdge {
                    PolygonIndex = 1, TwinIndex = 19, VertexIndex = 6
                },                                                                      //  6
                new HalfEdge {
                    PolygonIndex = 1, TwinIndex = 14, VertexIndex = 7
                },                                                                      //  7

                new HalfEdge {
                    PolygonIndex = 2, TwinIndex = 1, VertexIndex = 0
                },                                                                      //  8
                new HalfEdge {
                    PolygonIndex = 2, TwinIndex = 20, VertexIndex = 4
                },                                                                      //  9
                new HalfEdge {
                    PolygonIndex = 2, TwinIndex = 4, VertexIndex = 7
                },                                                                      // 10
                new HalfEdge {
                    PolygonIndex = 2, TwinIndex = 13, VertexIndex = 1
                },                                                                      // 11

                new HalfEdge {
                    PolygonIndex = 3, TwinIndex = 2, VertexIndex = 1
                },                                                                      // 12
                new HalfEdge {
                    PolygonIndex = 3, TwinIndex = 11, VertexIndex = 7
                },                                                                      // 13
                new HalfEdge {
                    PolygonIndex = 3, TwinIndex = 7, VertexIndex = 6
                },                                                                      // 14
                new HalfEdge {
                    PolygonIndex = 3, TwinIndex = 18, VertexIndex = 2
                },                                                                      // 15

                new HalfEdge {
                    PolygonIndex = 4, TwinIndex = 22, VertexIndex = 3
                },                                                                      // 16
                new HalfEdge {
                    PolygonIndex = 4, TwinIndex = 3, VertexIndex = 2
                },                                                                      // 17
                new HalfEdge {
                    PolygonIndex = 4, TwinIndex = 15, VertexIndex = 6
                },                                                                      // 18
                new HalfEdge {
                    PolygonIndex = 4, TwinIndex = 6, VertexIndex = 5
                },                                                                      // 19

                new HalfEdge {
                    PolygonIndex = 5, TwinIndex = 9, VertexIndex = 0
                },                                                                      // 20
                new HalfEdge {
                    PolygonIndex = 5, TwinIndex = 0, VertexIndex = 3
                },                                                                      // 21
                new HalfEdge {
                    PolygonIndex = 5, TwinIndex = 16, VertexIndex = 5
                },                                                                      // 22
                new HalfEdge {
                    PolygonIndex = 5, TwinIndex = 5, VertexIndex = 4
                }                                                                       // 23
            };

            controlMesh.Polygons = new []
            {
                // left/right
                new Polygon(new int[] { 0, 1, 2, 3 }, 0),       // 0
                new Polygon(new int[] { 4, 5, 6, 7 }, 1),       // 1

                // front/back
                new Polygon(new int[] { 8, 9, 10, 11 }, 2),     // 2
                new Polygon(new int[] { 12, 13, 14, 15 }, 3),   // 3

                // top/down
                new Polygon(new int[] { 16, 17, 18, 19 }, 4),   // 4
                new Polygon(new int[] { 20, 21, 22, 23 }, 5)    // 5
            };

            shape = new Shape();

            shape.Surfaces = new Surface[6];
            shape.Surfaces[0].TexGenIndex = 0;
            shape.Surfaces[1].TexGenIndex = 1;
            shape.Surfaces[2].TexGenIndex = 2;
            shape.Surfaces[3].TexGenIndex = 3;
            shape.Surfaces[4].TexGenIndex = 4;
            shape.Surfaces[5].TexGenIndex = 5;

            shape.Surfaces[0].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 0);
            shape.Surfaces[1].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 1);
            shape.Surfaces[2].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 2);
            shape.Surfaces[3].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 3);
            shape.Surfaces[4].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 4);
            shape.Surfaces[5].Plane = GeometryUtility.CalcPolygonPlane(controlMesh, 5);

            GeometryUtility.CalculateTangents(shape.Surfaces[0].Plane.normal, out shape.Surfaces[0].Tangent, out shape.Surfaces[0].BiNormal);
            GeometryUtility.CalculateTangents(shape.Surfaces[1].Plane.normal, out shape.Surfaces[1].Tangent, out shape.Surfaces[1].BiNormal);
            GeometryUtility.CalculateTangents(shape.Surfaces[2].Plane.normal, out shape.Surfaces[2].Tangent, out shape.Surfaces[2].BiNormal);
            GeometryUtility.CalculateTangents(shape.Surfaces[3].Plane.normal, out shape.Surfaces[3].Tangent, out shape.Surfaces[3].BiNormal);
            GeometryUtility.CalculateTangents(shape.Surfaces[4].Plane.normal, out shape.Surfaces[4].Tangent, out shape.Surfaces[4].BiNormal);
            GeometryUtility.CalculateTangents(shape.Surfaces[5].Plane.normal, out shape.Surfaces[5].Tangent, out shape.Surfaces[5].BiNormal);

            if (material == null)
            {
                material = CSGSettings.DefaultMaterial;
            }

            shape.TexGens = new TexGen[6];

            shape.TexGens[0].RenderMaterial = material;
            shape.TexGens[1].RenderMaterial = material;
            shape.TexGens[2].RenderMaterial = material;
            shape.TexGens[3].RenderMaterial = material;
            shape.TexGens[4].RenderMaterial = material;
            shape.TexGens[5].RenderMaterial = material;

            shape.TexGens[0].Scale = MathConstants.oneVector3;
            shape.TexGens[1].Scale = MathConstants.oneVector3;
            shape.TexGens[2].Scale = MathConstants.oneVector3;
            shape.TexGens[3].Scale = MathConstants.oneVector3;
            shape.TexGens[4].Scale = MathConstants.oneVector3;
            shape.TexGens[5].Scale = MathConstants.oneVector3;


            //			shape.TexGens[0].Color = Color.white;
            //			shape.TexGens[1].Color = Color.white;
            //			shape.TexGens[2].Color = Color.white;
            //			shape.TexGens[3].Color = Color.white;
            //			shape.TexGens[4].Color = Color.white;
            //			shape.TexGens[5].Color = Color.white;

            shape.TexGenFlags = new []
            {
                RealtimeCSG.CSGSettings.DefaultTexGenFlags,
                RealtimeCSG.CSGSettings.DefaultTexGenFlags,
                RealtimeCSG.CSGSettings.DefaultTexGenFlags,
                RealtimeCSG.CSGSettings.DefaultTexGenFlags,
                RealtimeCSG.CSGSettings.DefaultTexGenFlags,
                RealtimeCSG.CSGSettings.DefaultTexGenFlags
            };

            //controlMesh.Validate();
            ShapeUtility.EnsureInitialized(shape);
            controlMesh.Valid = ControlMeshUtility.Validate(controlMesh, shape);

            return(controlMesh.Valid);
        }
Пример #14
0
        /// <summary>
        /// Scrapes data from the NUFORC web portal, deserializes it into Report objects
        /// Multithreaded, takes a lot of CPU and memory to run, and is more or less a DDOS if done wrong
        /// Ensure parameters are properly set before starting
        /// </summary>
        /// <returns></returns>
        public IEnumerable <Report> GetReports(ISet <int> currentIds)
        {
            IsRunning = true;
            Halt      = false;
            var newReports = new HashSet <Report>();

            var web     = new HtmlWeb();
            var homeDoc = web.Load(BaseUrl + "webreports.html");

            // from front page, go to "by state"
            var stateIndexLink = BaseUrl + homeDoc.QuerySelector(Selectors.indexSelector).Attributes["href"].Value;
            var stateIndexDoc  = web.Load(stateIndexLink);

            // number of pending requests to the NUFORC site, decrements once the web page is received
            int requestsInFlight = 0;

            // get list of links to state pages
            var stateLinkNodes = stateIndexDoc.QuerySelectorAll(Selectors.tableLinkSelector);


            // Main loop, forks threads to independently open and close pages as they load
            do
            {
                foreach (var s in stateLinkNodes)
                {
                    web = new HtmlWeb();

                    var stateLink = BaseUrl + "webreports/" + s.Attributes["href"].Value;

                    // throttle requests when too many are in flight
                    while (requestsInFlight > MaxInFlight)
                    {
                        Thread.Sleep(ThrottleTimeout);
                    }
                    requestsInFlight++;

                    // spin off threads for each state
                    web.LoadFromWebAsync(stateLink).ContinueWith((state_task) =>
                    {
                        try { state_task.Wait(); }
                        catch { return; }

                        requestsInFlight--;

                        if (!state_task.IsCompletedSuccessfully)
                        {
                            return;
                        }

                        var stateDoc = state_task.Result;

                        // get list of links to individual reports (same selector)
                        var reportLinkNodes = stateDoc.QuerySelectorAll(Selectors.tableLinkSelector);

                        foreach (var r in reportLinkNodes)
                        {
                            // add another short lived web client!
                            var webTemp    = new HtmlWeb();
                            var reportLink = BaseUrl + "webreports/" + r.Attributes["href"].Value;

                            // extract ID from url, use that as the ID
                            bool parseResult = int.TryParse(reportLink.Substring(reportLink.LastIndexOf('/') + 2).Replace(".html", ""), out int reportId);

                            // check against duplicates and failed lookups
                            if (!parseResult || currentIds.Contains(reportId))
                            {
                                continue;
                            }

                            // throttle requests when to many are in flight
                            while (requestsInFlight >= MaxInFlight)
                            {
                                Thread.Sleep(ThrottleTimeout);
                            }
                            requestsInFlight++;

                            // spin off *another* thread to load the report pages
                            webTemp.LoadFromWebAsync(reportLink).ContinueWith((report_task) =>
                            {
                                try
                                { report_task.Wait(); }
                                catch { return; }
                                finally { requestsInFlight--; }

                                // bail out if the request failed
                                if (!report_task.IsCompletedSuccessfully)
                                {
                                    return;
                                }

                                var reportDoc = report_task.Result;

                                // get the details and description of the report
                                var reportTable = reportDoc.QuerySelectorAll("tr td");

                                // report wasn't found, got a different page
                                if (reportTable.Count < 2)
                                {
                                    return;
                                }

                                var details     = reportTable[0].InnerHtml;
                                var description = reportTable[1];

                                // bail out if we've hit the max batch in any thread
                                if (Halt.Equals(true) || (BatchSize != -1 && newReports.Count > BatchSize))
                                {
                                    Halt = true;
                                    return;
                                }

                                // for this row: the left most portion is the date, the rightmost is the time, the middle is usually useless
                                var reportDateTimes = Regex.Match(details, RegularExpressions.dateReported).Value.Split(' ');

                                // there is
                                newReports.Add(new Report()
                                {
                                    ReportId      = reportId,
                                    DateOccurred  = DateTime.Parse(Regex.Match(details, RegularExpressions.dateOccured).Value),
                                    DateSubmitted = DateTime.Parse(reportDateTimes[0] + reportDateTimes[reportDateTimes.Length - 1]),
                                    DatePosted    = DateTime.Parse(Regex.Match(details, RegularExpressions.datePosted).Value),
                                    Location      = Regex.Match(details, RegularExpressions.location).Value,
                                    Shape         = ShapeUtility.ShapeAliases(Regex.Match(details, RegularExpressions.shape).Value),
                                    Duration      = Regex.Match(details, RegularExpressions.duration).Value,
                                    Description   = description.InnerText
                                });

                                Console.WriteLine(newReports.Count);
                            });

                            if (Halt.Equals(true))
                            {
                                break;
                            }
                        }
                    });
                    if (Halt.Equals(true))
                    {
                        break;
                    }
                }
            } while (requestsInFlight > 0 || Halt.Equals(false));

            // reset initial conditions
            Halt      = false;
            IsRunning = false;

            return(newReports);
        }
Пример #15
0
        /// <summary>
        /// Scrapes data from the NUFORC web portal, serializes it into
        /// Multithreaded, takes a lot of CPU and memory to run, ensure parameters are properly set before starting
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <Report> GetReports()
        {
            var newReports = new HashSet <Report>();

            var web     = new HtmlWeb();
            var homeDoc = web.Load(baseUrl + "webreports.html");

            // from front page, go to "by state"
            var stateIndexLink = baseUrl + homeDoc.QuerySelector(Selectors.indexSelector).Attributes["href"].Value;
            var stateIndexDoc  = web.Load(stateIndexLink);

            // number of pending requests to the NUFORC site, decrements once the web page is received
            int requestsInFlight = 0;

            object stopRequests = false;

            // get list of links to state pages
            var stateLinkNodes = stateIndexDoc.QuerySelectorAll(Selectors.tableLinkSelector);

            do
            {
                foreach (var s in stateLinkNodes)
                {
                    web = new HtmlWeb();

                    var stateLink = baseUrl + "webreports/" + s.Attributes["href"].Value;

                    // throttle requests when too many are in flight
                    while (requestsInFlight > maxInFlight)
                    {
                        Thread.Sleep(throttleTimeout);
                    }
                    requestsInFlight++;

                    // spin off threads for each state
                    web.LoadFromWebAsync(stateLink).ContinueWith((state_task) =>
                    {
                        try { state_task.Wait(); }
                        catch { return; }

                        requestsInFlight--;

                        if (!state_task.IsCompletedSuccessfully)
                        {
                            return;
                        }

                        var stateDoc = state_task.Result;

                        // get list of links to individual reports (same selector)
                        var reportLinkNodes = stateDoc.QuerySelectorAll(Selectors.tableLinkSelector);

                        foreach (var r in reportLinkNodes)
                        {
                            var webTemp    = new HtmlWeb();
                            var reportLink = baseUrl + "webreports/" + r.Attributes["href"].Value;

                            // extract ID from url, use that as the ID
                            var reportId = int.Parse(reportLink.Substring(reportLink.LastIndexOf('/') + 2).Replace(".html", ""));

                            // throttle requests when to many are in flight
                            while (requestsInFlight >= maxInFlight)
                            {
                                Thread.Sleep(throttleTimeout);
                            }
                            requestsInFlight++;

                            // spin off *another* thread to load the report pages
                            webTemp.LoadFromWebAsync(reportLink).ContinueWith((report_task) =>
                            {
                                try
                                { report_task.Wait(); }
                                catch { return; }
                                finally { requestsInFlight--; }

                                // bail out if the request failed
                                if (!report_task.IsCompletedSuccessfully)
                                {
                                    return;
                                }

                                var reportDoc = report_task.Result;

                                // TODO: get hashset of all IDs from DB into memory before running this method, check for duplicates here


                                // get the details and description of the report
                                var reportTable = reportDoc.QuerySelectorAll("tr td");

                                // report wasn't found, got a different page
                                if (reportTable.Count < 2)
                                {
                                    return;
                                }

                                var details     = reportTable[0].InnerHtml;
                                var description = reportTable[1];

                                // bail out if we've hit the max batch in any thread
                                if (stopRequests.Equals(true) || (maxReportBatch != -1 && newReports.Count >= maxReportBatch))
                                {
                                    stopRequests = true;
                                    return;
                                }

                                Console.WriteLine(newReports.Count);


                                // for this row: the left most portion is the date, the rightmost is the time, the middle is usually useless
                                var reportDateTimes = Regex.Match(details, RegularExpressions.dateReported).Value.Split(' ');

                                newReports.Add(new Report()
                                {
                                    ReportId      = reportId,
                                    DateOccurred  = DateTime.Parse(Regex.Match(details, RegularExpressions.dateOccured).Value),
                                    DateSubmitted = DateTime.Parse(reportDateTimes[0] + reportDateTimes[reportDateTimes.Length - 1]),
                                    DatePosted    = DateTime.Parse(Regex.Match(details, RegularExpressions.datePosted).Value),
                                    Location      = Regex.Match(details, RegularExpressions.location).Value,
                                    Shape         = ShapeUtility.ShapeAliases(Regex.Match(details, RegularExpressions.shape).Value),
                                    Duration      = Regex.Match(details, RegularExpressions.duration).Value,
                                    Description   = description.InnerText
                                });
                            });

                            if (stopRequests.Equals(true))
                            {
                                break;
                            }
                        }
                    });
                    if (stopRequests.Equals(true))
                    {
                        break;
                    }
                }
            } while (requestsInFlight > 0 && stopRequests.Equals(false));

            return(newReports);
        }
Пример #16
0
        public static void Flip(CSGBrush[] brushes, Matrix4x4 flipMatrix, string undoDescription = "Flip brushes")
        {
            var fail = false;

            Undo.IncrementCurrentGroup();
            Undo.RegisterCompleteObjectUndo(brushes.ToArray <UnityEngine.Object>(), undoDescription);

            var isGlobal = Tools.pivotRotation == PivotRotation.Global;

            var centerAll = BoundsUtilities.GetCenter(brushes);

            for (var t = 0; t < brushes.Length; t++)
            {
                var brush    = brushes[t];
                var shape    = brush.Shape;
                var position = brush.transform.position;

                Matrix4x4 brushFlip;
                Vector3   brushCenter;
                if (isGlobal)
                {
                    brushFlip = brush.transform.localToWorldMatrix *
                                flipMatrix *
                                brush.transform.worldToLocalMatrix;
                    brushCenter = brush.transform.InverseTransformPoint(centerAll) - position;
                }
                else
                {
                    brushFlip   = flipMatrix;
                    brushCenter = brush.transform.InverseTransformPoint(centerAll);
                }

                for (var s = 0; s < shape.Surfaces.Length; s++)
                {
                    var plane = shape.Surfaces[s].Plane;

                    var normal   = brushFlip.MultiplyVector(plane.normal);
                    var biNormal = brushFlip.MultiplyVector(shape.Surfaces[s].BiNormal);
                    var tangent  = brushFlip.MultiplyVector(shape.Surfaces[s].Tangent);

                    var pointOnPlane = plane.pointOnPlane;
                    pointOnPlane -= brushCenter;
                    pointOnPlane  = brushFlip.MultiplyPoint(pointOnPlane);
                    pointOnPlane += brushCenter;

                    shape.Surfaces[s].Plane    = new CSGPlane(normal, pointOnPlane);
                    shape.Surfaces[s].BiNormal = biNormal;
                    shape.Surfaces[s].Tangent  = tangent;
                }

                var controlMesh = brush.ControlMesh;
                brush.Shape = shape;

                brush.ControlMesh = ControlMeshUtility.CreateFromShape(shape);
                if (brush.ControlMesh == null)
                {
                    brush.ControlMesh = controlMesh;
                    fail = true;
                    break;
                }

                ShapeUtility.CreateCutter(shape, brush.ControlMesh);
                brush.EnsureInitialized();

                brush.ControlMesh.SetDirty();
                EditorUtility.SetDirty(brush);

                InternalCSGModelManager.CheckSurfaceModifications(brush, true);

                ControlMeshUtility.RebuildShape(brush);
            }
            if (fail)
            {
                Debug.Log("Failed to perform operation");
                Undo.RevertAllInCurrentGroup();
            }
            InternalCSGModelManager.Refresh();
        }