Exemplo n.º 1
0
    // Use this for initialization
    void Start()
    {
        VD    = GetComponent <VertexDriver>();
        Inter = Intersector.Instance;

        // create target
        TargetI = (float)(TargetDistance * Math.Tan(DegToRad(VD.TargetFOV.x / 2.0)));
        TargetJ = (float)(TargetDistance * Math.Tan(DegToRad(VD.TargetFOV.y / 2.0)));
        Vector3 TargetBotLeft  = new Vector3(-TargetI, -TargetJ, TargetDistance);
        Vector3 TargetBotRight = new Vector3(TargetI, -TargetJ, TargetDistance);
        Vector3 TargetTopLeft  = new Vector3(-TargetI, TargetJ, TargetDistance);
        Vector3 TargetTopRight = new Vector3(TargetI, TargetJ, TargetDistance);

        TargetLines = new List <Vector3[]>();
        TargetLines.Add(new Vector3[] { TargetBotLeft, TargetBotRight });  // bottom
        TargetLines.Add(new Vector3[] { TargetBotRight, TargetTopRight }); // right
        TargetLines.Add(new Vector3[] { TargetTopRight, TargetTopLeft });  // top
        TargetLines.Add(new Vector3[] { TargetTopLeft, TargetBotLeft });   // left

        OcLines = new List <Vector3[]>();
        for (int i = 1; i < Inter.OccGridSize.x; i++)
        {
            float   offset = i * (2f * Math.Abs(TargetI)) / Inter.OccGridSize.x;
            Vector3 bot    = new Vector3(TargetBotLeft.x + offset, TargetBotLeft.y, TargetBotLeft.z);
            Vector3 top    = new Vector3(TargetTopLeft.x + offset, TargetTopLeft.y, TargetTopLeft.z);
            OcLines.Add(new Vector3[] { bot, top });
        }
        for (int i = 1; i < Inter.OccGridSize.y; i++)
        {
            float   offset = i * (2f * Math.Abs(TargetJ)) / Inter.OccGridSize.y;
            Vector3 left   = new Vector3(TargetBotLeft.x, TargetBotLeft.y + offset, TargetBotLeft.z);
            Vector3 right  = new Vector3(TargetBotRight.x, TargetBotRight.y + offset, TargetBotRight.z);
            OcLines.Add(new Vector3[] { left, right });
        }

        TargetContainer      = new GameObject();
        TargetContainer.name = "TargetContainer";
        for (int i = 0; i < TargetLines.Count; i++)
        {
            Vector3[] line = TargetLines[i];
            VertexDriver.DrawLine(line[0], line[1], TargetContainer, TargetSize, TargetMaterial, i.ToString());
        }
        OcContainer      = new GameObject();
        OcContainer.name = "OcContainer";
        for (int i = 0; i < OcLines.Count; i++)
        {
            Vector3[] line = OcLines[i];
            VertexDriver.DrawLine(line[0], line[1], OcContainer, OcGridSize, TargetMaterial, i.ToString());
        }


        // create diagnostics panel
        Diagnostics = new GameObject();
        Diagnostics.transform.position           = DiagnosticsPosition;
        DiagnosticsText.transform.parent         = Diagnostics.transform;
        DiagnosticsText.transform.position       = Diagnostics.transform.TransformPoint(DiagnosticsText.transform.position);
        DiagnosticsBackground.transform.parent   = Diagnostics.transform;
        DiagnosticsBackground.transform.position = Diagnostics.transform.
                                                   TransformPoint(DiagnosticsBackground.transform.position);
    }
Exemplo n.º 2
0
        public void Test_Intersect_Between_Arrays_Comparison_Hash()
        {
            long averageMs    = 0;
            long averageTicks = 0;
            int  count        = 0;

            Console.WriteLine("Test_Intersect_Between_Arrays_Hash_Average");
            for (var i = 0; i < COMPARISON_LOOP; i++)
            {
                var stopWatch = new Stopwatch();

                stopWatch.Start();
                var intersection = Intersector.IntersectionWithHashSet(colorsArray, namesArray,
                                                                       comparer: new CustomComparer(),
                                                                       formatFunction: (i1, i2) => new string[] { i1[0], i1[1], i2[1] });
                stopWatch.Stop();

                Console.WriteLine($"Ran in {stopWatch.ElapsedTicks} ticks,{stopWatch.ElapsedMilliseconds}ms");
                if (i != 0)
                {
                    averageTicks += stopWatch.ElapsedTicks;
                    averageMs    += stopWatch.ElapsedMilliseconds;
                    count++;
                }
            }

            averageMs    = averageMs / count;
            averageTicks = averageTicks / count;

            Console.WriteLine($"Average in {averageTicks} ticks,{averageMs}ms");
        }
Exemplo n.º 3
0
    private List <TopologyIntersection> FindAllIntersections(Face2D target, List <ICuttableEdge> edges2cut)
    {
        Intersector intersector = new Intersector();

        List <TopologyIntersection> res_list = new List <TopologyIntersection>();

        for (int loop_idx = 0; loop_idx < target.Loops.Count; ++loop_idx)
        {
            var loop = target.Loops[loop_idx];
            for (int target_edge_idx = 0; target_edge_idx < loop.Count; ++target_edge_idx)
            {
                List <TopologyIntersection> sorted_is = new List <TopologyIntersection>();
                for (int tool_edge_idx = 0; tool_edge_idx < edges2cut.Count; ++tool_edge_idx)
                {
                    var intersections = intersector.Intersect(loop[target_edge_idx], edges2cut[tool_edge_idx]);
                    foreach (var intersection in intersections)
                    {
                        TopologyIntersection res = new TopologyIntersection(
                            loop_idx, target_edge_idx, tool_edge_idx, intersection);

                        sorted_is.Add(res);
                    }
                }

                sorted_is.Sort(new TopologyIntersectionCompare_ByTarget());
                res_list.AddRange(sorted_is);
            }
        }

        return(res_list);
    }
Exemplo n.º 4
0
        public ImageSensorData Measure()
        {
            var tmpLocation     = GetCameraLocation(_robot);
            var result          = new KinectData(_settings.VerticalResolution, _settings.HorisontalResolution);
            var horisontalAngle = -_settings.HorisontalViewAngle / 2.0;
            var verticalAngle   = -_settings.VerticalViewAngle / 2.0;

            for (int i = 0; i < _settings.VerticalResolution; i++)
            {
                Frame3D mediateDirection = SensorRotation.VerticalFrameRotation(tmpLocation, -verticalAngle);
                horisontalAngle = -_settings.HorisontalViewAngle / 2.0;
                for (int j = 0; j < _settings.HorisontalResolution; j++)
                {
                    Frame3D direction = SensorRotation.HorisontalFrameRotation(mediateDirection, horisontalAngle);
                    Ray     ray       = new Ray(tmpLocation.ToPoint3D(), SensorRotation.GetFrontDirection(direction));
                    var     dist      = double.PositiveInfinity;
                    foreach (var body in _worldRoot.GetSubtreeChildrenFirst())
                    {
                        if (_settings.Exclude.All(a => a != body))
                        {
                            var inter = Intersector.Intersect(body, ray);
                            dist = Math.Min(dist, inter);
                        }
                    }
                    result.Depth[i, j] = dist;

                    //verticalAngle += _settings.VStep;
                    horisontalAngle += _settings.HStep;
                }
                verticalAngle += _settings.VStep;
            }
            return(new ImageSensorData(result.GetBytes()));
        }
Exemplo n.º 5
0
    // Use this for initialization
    void Awake()
    {
        // gather dependencies
        MeshMan     = MeshManager.Instance;
        VoxGridMan  = new VoxelGridManager <byte>(myMinSize: DefaultVoxGridRes, myDefaultSize: DefaultVoxelSize);
        VertVis     = new Visualizer("VertexMarkers", "Marker", "Line", DefaultMaterial);
        VertexInter = new Intersector();
        Observer    = GetComponent <SpatialMappingObserver>();

        // finish setup
        SensorField.Transform = Camera.main.transform;
        SensorField.FOV       = new Intersector.ViewVector((int)SensorFOV.x, (int)SensorFOV.y);
        MeshDensity           = MeshMan.Density;
        SensorData            = new byte[(int)SensorPixelCount.x, (int)SensorPixelCount.y];
        for (int i = 0; i < SensorPixelCount.x; i++)
        {
            for (int j = 0; j < SensorPixelCount.y; j++)
            {
                SensorData[i, j] = (byte)(255f * (float)(i + j) / (SensorPixelCount.x + SensorPixelCount.y));
            }
        }

        // finish dependendencies setup: some variables must be created in Start()
        MeshMan.BoundsVis = new Visualizer("MeshBounds", "Marker", "Line", DefaultMaterial);
        VerticesRendered  = DefaultRenderVerts;
    }
Exemplo n.º 6
0
        private Dictionary <Edge, Operation> GenerateLoop(string input, string output, List <Edge> edges, Dictionary <Edge, Operation> mapping)
        {
            //foreach 0 <= k1, k2, k3 < Length(s)
            //  eSet1 = GenerateStr(sigma, s[k1 : k2]);
            //  eSet2 = GenerateStr(sigma, s[k2 : k3]);
            //  eSet = Unify(eSet1, eSet2);
            //  if ([[Loop(lambda W : eSet)]]sigma = {s[k1 : k3]})
            //      W(<k1, k3>) = W'(<k1, k3>) U {Loop(lambda W : eSet)};

            int len = output.Length;

            for (int i = 0; i < len; ++i)
            {
                for (int j = i; j < len; ++j)
                {
                    for (int k = j; k < len; ++k)
                    {
                        var traceSet1 = GenerateStr(input, output.Substring(i, j - i));
                        var traceSet2 = GenerateStr(input, output.Substring(j, k - j));
                        var traceSet  = new Intersector().Unify(traceSet1, traceSet2);

                        Loop loop = new Loop(traceSet);
                        if (loop.Apply(input).Equals(output.Substring(i, k - i)))
                        {
                            Edge targetEdge = new Edge(i, k);
                            //mapping[targetEdge] = mapping[targetEdge] U loop;
                        }
                    }
                }
            }

            return(mapping);
        }
Exemplo n.º 7
0
        public void IntersectConvexTest()
        {
            var intersect = Intersector.IntersectConvex(m_diamond, m_squarePoly);

            Assert.AreEqual(0.5f, intersect.Area);

            Assert.Throws <GeomException>(() => Intersector.IntersectConvex(m_diamond, m_arrow));
        }
Exemplo n.º 8
0
        public bool GetGroundPosition(Vec3D position, Vec3 direction, out MapPos result, ClampFlags flags = ClampFlags.DEFAULT)
        {
            result = new MapPos();

            // Coordinate is now in world Cartesian coordinates (Roi Position)

            Vec3D origo = new Vec3D(0, 0, 0);       // Set used origo

            Intersector isect = new Intersector();

            // Check camera frustrum -----------------------------------------------------------

            if (_camera != null && _camera.IsValid())
            {
                origo = _camera.Position;

                if ((flags & ClampFlags.FRUSTRUM_CULL) != 0)
                {
                    isect.SetCamera(_camera);
                }
            }

            // Adjust intersector to use origo as center
            position = position - origo;

            isect.SetStartPosition((Vec3)position);
            isect.SetDirection(direction);

            if (isect.Intersect(_currentMap, IntersectQuery.NEAREST_POINT | IntersectQuery.NORMAL | ((flags & ClampFlags.WAIT_FOR_DATA) != 0 ? IntersectQuery.WAIT_FOR_DYNAMIC_DATA : 0), 1, true, origo))
            {
                IntersectorResult res = isect.GetResult();

                IntersectorData data = res.GetData(0);

                result.position = data.position + origo;

                result.normal = data.normal;

                result.clamped = true;
            }

            isect.Dispose();   // Drop handle and ignore GC

            if (_topRoi != null)
            {
                RoiNode roi = _topRoi.GetClosestRoiNode(result.position);
                result.node = roi;

                // Remove roiNode position as offset - Go to local RoiNode based coordinate system

                if (roi != null && roi.IsValid())
                {
                    result.position -= roi.Position;
                }
            }

            return(true);
        }
Exemplo n.º 9
0
    // Use this for initialization
    void Start()
    {
        TextObj = TextContainer.GetComponent <TextMesh>();

        Driver         = EFPContainer.GetComponent <ExternalFeedDriver>();
        MeshManagerObj = EFPContainer.GetComponent <MeshManager>();
        GridManager    = EFPContainer.GetComponent <VoxelGridManager>();
        Intersect      = EFPContainer.GetComponent <Intersector>();
    }
Exemplo n.º 10
0
        public void Test_Intersect_Between_Arrays_Linear_Search()
        {
            var intersection = Intersector.IntersectionWithLinearSearch(colorsArray, namesArray,
                                                                        formatFunction: (i1, i2) => new string[] { i1[0], i1[1], i2[1] });

            var result = string.Join("\r\n", intersection.Select(x => $"{x[0]},{x[1]},{x[2]}"));

            Assert.AreEqual(expectedResult, result);
        }
Exemplo n.º 11
0
        public void Test_Intersect_Between_Arrays_Hash()
        {
            var intersection = Intersector.IntersectionWithHashSet(colorsArray, namesArray,
                                                                   comparer: new CustomComparer(),
                                                                   formatFunction: (i1, i2) => new string[] { i1[0], i1[1], i2[1] });

            var result = string.Join("\r\n", intersection.Select(x => $"{x[0]},{x[1]},{x[2]}"));

            //       Assert.AreEqual(expectedResult, result);
        }
Exemplo n.º 12
0
    void Start()
    {
        observer  = GetComponent <SpatialMappingObserver>();
        Density   = observer.Density;
        MeshInter = new Intersector();

        TotalMeshCount  = 0;
        MeshesInView    = 0;
        TrianglesInView = 0;
        VerticesInView  = 0;
    }
Exemplo n.º 13
0
    void Start()
    {
        observer         = GetComponent <SpatialMappingObserver>();
        Density          = observer.TrianglesPerCubicMeter;
        MeshInter        = new Intersector();
        BoundsVis        = new Visualizer("MeshBounds", "Marker", "Line", DefaultMaterial);
        BoundsVisualized = DefaultVisualizeBounds;

        TotalMeshCount  = 0;
        MeshesInView    = 0;
        TrianglesInView = 0;
        VerticesInView  = 0;
    }
Exemplo n.º 14
0
    // Use this for initialization
    void Start()
    {
        // finish setup
        FOV       = new ViewVector(TargetFOV.x, TargetFOV.y);
        ViewField = new Frustum(Camera.main.transform, FOV);
        CubeMin   = new Vector3(CubeCenter.x - CubeSize / 2f, CubeCenter.y - CubeSize / 2f,
                                CubeCenter.z - CubeSize / 2f);
        CubeMax = new Vector3(CubeCenter.x + CubeSize / 2f, CubeCenter.y + CubeSize / 2f,
                              CubeCenter.z + CubeSize / 2f);
        for (int i = 0; i < Vertices; i++)
        {
            Points.Add(RandomPoint(CubeMin, CubeMax, Rand));
        }
        Scale = new Vector3(VertexSize, VertexSize, VertexSize);
        Inter = Intersector.Instance;

        // create point markers
        Parent      = new GameObject();
        Parent.name = "VertexMarkers";
        for (int i = 0; i < Vertices; i++)
        {
            GameObject Child = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            Child.AddComponent <MeshFilter>();
            Child.AddComponent <MeshRenderer>();
            Child.AddComponent <SphereCollider>();
            Child.name                 = "Marker" + i.ToString();
            Child.transform.parent     = Parent.transform;
            Child.transform.position   = Points[i];
            Child.transform.localScale = Scale;
            Child.GetComponent <MeshRenderer>().material = OutViewMaterial;

            if (ViewVectorLabels)
            {
                GameObject VVLabelT = Instantiate(VVLabelText);
                VVLabelT.transform.parent   = Parent.transform;
                VVLabelT.name               = "Text" + i.ToString();
                VVLabelT.transform.position = Points[i] + VVLabelOffset;
                GameObject VVLabelB = Instantiate(VVLabelBackground);
                VVLabelB.transform.parent   = Parent.transform;
                VVLabelB.name               = "Background" + i.ToString();
                VVLabelB.transform.position = Points[i] + VVLabelOffset + new Vector3(0, 0, 0.01f);
            }
        }

        // draw bounds box
        GameObject BoxParent = new GameObject();

        BoxParent.name = "BoxParent";
        DrawBox(CubeMin, CubeMax, BoxParent, LineSize, LineMaterial);
    }
Exemplo n.º 15
0
    // Use this for initialization
    void Awake()
    {
        // gather dependencies
        MeshMan           = MeshManager.Instance;
        VoxGridMan        = new VoxelGridManager <byte>(myMinSize: DefaultVoxGridRes, myDefaultSize: DefaultVoxelSize);
        VertVis           = new Visualizer("VertexMarkers", "Marker", "Line", DefaultMaterial);
        VertexInter       = new Intersector();
        Observer          = GetComponent <SpatialMappingObserver>();
        SensorDataUpdater = DataUpdateContainer.GetComponent <Receiving.ImageReceiver>();

        // finish setup
        SensorField.Transform = Camera.main.transform;
        SensorField.FOV       = new Intersector.ViewVector((int)(SensorFOV.x * SensorFOVReduction.x),
                                                           (int)(SensorFOV.y * SensorFOVReduction.y));
        MeshDensity = MeshMan.Density;
        SensorData  = new byte[SensorDataHeight * SensorDataWidth];

        // sync state to default values
        VerticesRendered = DefaultRenderVerts;
        ProximityConfig  = DefaultToProximity;
    }
Exemplo n.º 16
0
        /// <summary>
        /// Calculates total area owned by each player separately.
        /// </summary>
        private void UpdatePlayerAreaOwned()
        {
            m_playerArea = new float[2] {
                0, 0
            };

            foreach (var inputNode in m_delaunay.Vertices)
            {
                // get dcel face containing input node
                var face = m_DCEL.GetContainingFace(inputNode);

                if (m_ownership[inputNode] != EOwnership.UNOWNED)
                {
                    // update player area with face that intersects with window
                    var playerIndex = m_ownership[inputNode] == EOwnership.PLAYER1 ? 0 : 1;
                    m_playerArea[playerIndex] += Intersector.IntersectConvex(m_meshRect, face.Polygon.Outside).Area;
                }
            }

            // update GUI to reflect new player area owned
            m_GUIManager.SetPlayerAreaOwned(m_playerArea[0], m_playerArea[1]);
        }
Exemplo n.º 17
0
 public EdgeVisitor(Intersector intersector)
 {
     m_intersector = intersector;
     m_e1c         = null;
     m_e1l         = null;
 }
Exemplo n.º 18
0
 /// <summary>
 /// Creates ViewVector from spatialVector.
 /// Note: spatialVector MUST originate from origin.
 /// </summary>
 public ViewVector(Vector3 spatialVector)
 {
     Theta = Intersector.RadToDeg(AdjAtanTheta(spatialVector.x, spatialVector.z));
     Phi   = Intersector.RadToDeg(AdjAtanPhi(spatialVector));
 }
Exemplo n.º 19
0
    // Tests Intersector class
    // Currently tests:
    // Vector (T1)
    // InverseTransformVector (T2 - not implemented)
    // ViewVector alt. constructor (T3)
    // Intersection (small scale) (T4 - not implemented)
    // Intersection (large scale) (T5 - not implemented)
    static string TestIntersector(Intersector IntersectorObj)
    {
        string output = "\n<size=144>Testing Intersector...</size>\n\n";

        // Test 1: Vector from two points
        output += "<b>Test 1</b>\n";
        Vector3 p1 = new Vector3(0, 0, 0);
        Vector3 p2 = new Vector3(2, 2, 2);

        output += String.Format("Vector from two points: {0} to {1}\n", pointToStr(p1), pointToStr(p2));
        Vector3 result = new Vector3();

        IntersectorObj.Vector(p1, p2, ref result);
        output += String.Format("Resultant vector: {0}\n\n", pointToStr(result));

        // Cannot test Unity Library outside of Unity...
        // Test 2: InverseTransformVector
        output += "<b>Test 2</b>\n";
        GameObject view2 = new GameObject();

        view2.name = "ViewFieldTest2";
        view2.transform.Rotate(new Vector3(90, 90, 0));
        output += String.Format("InverseTransformVector... view-field position: {0}, view-field euler angles: {1}\n",
                                pointToStr(view2.transform.position), pointToStr(view2.transform.eulerAngles));
        Vector3[] unitVectors = unitVectorsArray();
        for (int i = 0; i < 8; i++)
        {
            output += String.Format("Vector{0}: World Space: {1}, View-Field Local Space: {2}\n",
                                    i + 1, pointToStr(unitVectors[i]), pointToStr(view2.transform.InverseTransformVector(unitVectors[i])));
        }
        output += "\n";
        // */

        // Test 3: View Vector alt. constructor
        output += "<b>Test 3</b>\n";
        output += String.Format("ViewVector creation from position vector (in local space)... 2D cross-sectional plane is XY plane.\n");
        Vector3 forward = new Vector3(0, 0, 1);

        for (int i = 0; i < 8; i++)
        {
            output += String.Format("Vector{0} {1}: ViewVector{0} (deg): {2}\n",
                                    i + 1, pointToStr(unitVectors[i]), viewVectorToStr(new ViewVector(unitVectors[i])));
        }
        output += String.Format("Vector {0}: ViewVector (deg): {1}\n",
                                pointToStr(forward), viewVectorToStr(new ViewVector(forward)));
        output += "\n";

        // Cannot test Unity Library outside of Unity...
        // Test 4: Intersection (small scale)
        output += "<b>Test 4</b>\n";
        List <Vector3> unitVectorList = new List <Vector3>();

        for (int i = 0; i < 8; i++)
        {
            unitVectorList.Add(unitVectors[i]);
        }
        GameObject view4 = new GameObject();

        view4.name = "ViewFieldTest4";
        ViewVector FOV4        = new ViewVector(170, 170);
        Frustum    projection4 = new Frustum(view4.transform, FOV4);

        byte[,] raster4 = new byte[100, 100];
        output         += String.Format("Intersection... Raster: ({0}x{1}), Frustum FOV: ({2}x{3}), " +
                                        "Frustum Pos: {4}, Frustum EA's: {5}\n" +
                                        "Tested all 8 unit vectors, found intersection points...\n",
                                        raster4.GetLength(0), raster4.GetLength(1), FOV4.Theta, FOV4.Phi,
                                        pointToStr(projection4.Transform.position), pointToStr(projection4.Transform.eulerAngles));
        List <PointValue <byte> > intersect = Intersector.Instance.Intersection(projection4, raster4, unitVectorList);

        foreach (PointValue <byte> pv in intersect)
        {
            output += String.Format("Point: {0}, ViewVector: {1}\n",
                                    pointToStr(pv.Point), viewVectorToStr(new ViewVector(pv.Point)));
        }
        output += "\n";


        // Cannot test Unity Library outside of Unity...
        // Test 5: Intersection (large scale)
        output += "<b>Test 5</b>\n";
        System.Random rand  = new System.Random();
        GameObject    view5 = new GameObject();

        view5.name = "ViewFieldTest5";
        ViewVector FOV5        = new ViewVector(179, 179);
        Frustum    projection5 = new Frustum(view5.transform, FOV5);

        byte[,] raster5 = new byte[100, 100];
        int            iterations  = 100;
        Stopwatch      stopWatch   = new Stopwatch();
        Vector3        boundsMin   = new Vector3(-5, -5, -5);
        Vector3        boundsMax   = new Vector3(5, 5, 5);
        List <Vector3> randVectors = new List <Vector3>();

        for (int i = 0; i < iterations; i++)
        {
            randVectors.Add(randomPoint(boundsMin, boundsMax, rand));
        }
        output += String.Format("Intersection... Raster: ({0}x{1}), Frustum FOV: ({2}x{3}). {4} Iterations...\n",
                                raster5.GetLength(0), raster5.GetLength(1), FOV5.Theta, FOV5.Phi, randVectors.Count);
        Intersector tmp = Intersector.Instance;

        stopWatch.Reset();
        stopWatch.Start();
        List <PointValue <byte> > result5 = tmp.Intersection(projection5, raster5, randVectors);

        stopWatch.Stop();
        long ms = (long)1000 * stopWatch.ElapsedTicks / Stopwatch.Frequency;

        output += String.Format("Took {0} ms ({1} us / op)... {2} vectors in view\n", ms,
                                ms / (double)iterations * 1000.0, result5.Count);
        output += "\n";

        // Test 6: RequiredGrid
        output += "<b>Test 6</b>\n";
        ViewVector FOV6 = new ViewVector(60, 60);

        output += String.Format("Testing RequiredGrid... FOV: {0}\n", viewVectorToStr(FOV6));
        Dictionary <string, int> pixels = Intersector.Instance.RequiredGrid(FOV6);

        output += String.Format("i: {0}, j: {1}\n", pixels["i"], pixels["j"]);
        output += "\n";

        /// Test 7: Occlusion (basic)
        output += "<b>Test 7</b>\n";
        GameObject view7 = new GameObject();

        view7.name = "ViewFieldTest7";
        ViewVector FOV7        = new ViewVector(170, 170);
        Frustum    projection7 = new Frustum(view7.transform, FOV7);

        byte[,] raster7 = new byte[100, 100];
        for (int i = 0; i < raster7.GetLength(0); i++)
        {
            for (int j = 0; j < raster7.GetLength(1); j++)
            {
                raster7[i, j] = (byte)(i + j);
            }
        }
        output += String.Format("Created Frustum: pos: {0}, EA's {1}, FOV: {2}\n",
                                pointToStr(projection7.Transform.position), pointToStr(projection7.Transform.eulerAngles),
                                viewVectorToStr(projection7.FOV));
        output += String.Format("Created Raster: {0}x{1}\n", raster7.GetLength(0), raster7.GetLength(1));
        Vector3        v1        = new Vector3(1, 1, 1);
        Vector3        v2        = new Vector3(2, 2, 2);
        Vector3        v3        = new Vector3(0, 0, 1);
        List <Vector3> vertices7 = new List <Vector3>();

        vertices7.Add(v2);
        vertices7.Add(v1);
        vertices7.Add(v2);
        vertices7.Add(v3);
        output += String.Format("Trying vertices: v1: {0}, v2: {1}, v3: {2}. Intersection return...\n",
                                pointToStr(v1), pointToStr(v2), pointToStr(v3));
        List <PointValue <byte> > intersectRet = Intersector.Instance.Intersection(projection7, raster7, vertices7);

        for (int i = 0; i < intersectRet.Count; i++)
        {
            output += String.Format("Point: {0}, Value: {1}\n",
                                    pointToStr(intersectRet[i].Point), intersectRet[i].Value);
        }
        output += "\n";

        // Test 8: Occlusion (large scale)
        output += "<b>Test 8</b>\n";
        GameObject view8 = new GameObject();

        view8.name = "ViewFieldTest8";
        ViewVector FOV8        = new ViewVector(170, 170);
        Frustum    projection8 = new Frustum(view8.transform, FOV8);

        byte[,] raster8 = new byte[100, 100];
        output         += String.Format("Created Frustum: pos: {0}, EA's {1}, FOV: {2}\n",
                                        pointToStr(projection8.Transform.position), pointToStr(projection8.Transform.eulerAngles),
                                        viewVectorToStr(projection8.FOV));
        output += String.Format("Created Raster: {0}x{1}\n", raster8.GetLength(0), raster8.GetLength(1));
        // create 'wall' vertices
        double         wallSize     = 4.0;
        double         wallRes      = 0.05;
        double         wallDistance = 3.0;
        float          wallWiggle   = 0.001f;
        int            wallPixels   = (int)(wallSize / wallRes);
        double         wallBotLeft  = -(wallSize / 2.0);
        int            wallValue    = 0;
        int            wallCount    = (int)Math.Pow(wallPixels, 2);
        List <Vector3> vertices     = new List <Vector3>();

        for (int i = 0; i < wallPixels; i++)
        {
            for (int j = 0; j < wallPixels; j++)
            {
                float   vertX = (float)(i * wallRes + wallBotLeft);
                float   vertY = (float)(j * wallRes + wallBotLeft);
                float   vertZ = (float)wallDistance;
                Vector3 vert  = new Vector3(vertX, vertY, vertZ);
                vertices.Add(wiggleVert(vert, wallWiggle, rand));
            }
        }
        // create 'box' vertices
        float   boxSize  = 1f;
        Vector3 boxMin   = new Vector3(-boxSize / 2, -boxSize / 2, (float)(wallDistance + 1));
        Vector3 boxMax   = new Vector3(boxSize / 2, boxSize / 2, (float)(wallDistance + 1 + boxSize));
        int     boxCount = 10000;

        for (int i = 0; i < boxCount; i++)
        {
            vertices.Add(randomPoint(boxMin, boxMax, rand));
        }
        // report progress
        output += String.Format("Created wall... ({0},{0}) to ({1},{1}), z: {2}, wiggle: {3}, " +
                                "vertices: {4}, resolution (m): {5}\n",
                                wallBotLeft, wallBotLeft + wallSize, wallDistance, wallWiggle, wallCount, wallRes);
        output += String.Format("Created box: {0} to {1}, vertices: {2}\n",
                                pointToStr(boxMin), pointToStr(boxMax), boxCount);
        // run intersection
        List <PointValue <byte> > intersectRet8 = Intersector.Instance.Intersection(projection8, raster8, vertices);
        int wallCountRet = 0;
        int boxCountRet  = 0;

        for (int i = 0; i < intersectRet8.Count; i++)
        {
            Vector3 point = intersectRet8[i].Point;
            if (within(point, boxMin, boxMax))
            {
                boxCountRet++;
            }
            else
            {
                wallCountRet++;
            }
        }
        output += String.Format("Intersection Return... wall vertices: {0}/{1}, box vertices: {2}/{3}",
                                wallCountRet, wallCount, boxCountRet, boxCount);

        return(output);
    }
Exemplo n.º 20
0
 // Use this for initialization
 void Start()
 {
     TextObj        = TextContainer.GetComponent <TextMesh>();
     IntersectorObj = IntersectorContainer.GetComponent <Intersector>();
     TextObj.text   = TestIntersector(IntersectorObj);
 }
Exemplo n.º 21
0
        public bool UpdatePosition(ref MapPos result, GroundClampType groundClamp = GroundClampType.NONE, ClampFlags flags = ClampFlags.DEFAULT)
        {
            if (groundClamp != GroundClampType.NONE)
            {
                // Add ROINode position as offset   - Go to global 3D coordinate system as we need to clamp in global 3D

                if (result.roiNode != null && result.roiNode.IsValid())
                {
                    result.position += result.roiNode.Position;
                }

                Intersector isect = new Intersector();

                Vec3D eyePos = new Vec3D(0, 0, 0);

                if (_camera != null && _camera.IsValid())
                {
                    eyePos = _camera.Position;

                    if ((flags & ClampFlags.FRUSTRUM_CULL) != 0)
                    {
                        isect.SetCamera(_camera);
                    }
                }

                if ((flags & ClampFlags.ISECT_LOD_QUALITY) != 0)                // Lets stand in the ray to get highest quality
                {
                    eyePos = result.position;
                }

                Vec3 up = new Vec3(result.local_orientation.v13, result.local_orientation.v23, result.local_orientation.v33);

                // TODO: Fix this....
                if (up.x == 0 && up.y == 0 && up.z == 0)
                {
                    up.y = 1;
                }

                isect.SetStartPosition((Vec3)(result.position - eyePos) + 10000.0f * up);
                isect.SetDirection(-up);

                if (isect.Intersect(_currentMap, IntersectQuery.NEAREST_POINT | IntersectQuery.NORMAL | ((flags & ClampFlags.WAIT_FOR_DATA) != 0 ? IntersectQuery.WAIT_FOR_DYNAMIC_DATA : 0), 1, true, eyePos))
                {
                    IntersectorResult res = isect.GetResult();

                    IntersectorData data = res.GetData(0);

                    result.position.x = data.position.x + eyePos.x;
                    result.position.y = data.position.y + eyePos.y;
                    result.position.z = data.position.z + eyePos.z;


                    result.normal  = data.normal;
                    result.clamped = true;
                }
                else
                {
                    result.normal  = up;
                    result.clamped = false;
                }

                if (groundClamp == GroundClampType.GROUND)
                {
                    result.normal = result.local_orientation.GetCol(2);
                }


                isect.Dispose();    // Drop handle and ignore GC

                // Remove ROINode position as offset - Go to local coordinate system under ROI Node

                if (result.roiNode != null && result.roiNode.IsValid())
                {
                    result.position -= result.roiNode.Position;
                }
            }


            return(true);
        }
Exemplo n.º 22
0
        public bool GetScreenGroundPosition(int x, int y, uint size_x, uint size_y, out MapPos result, ClampFlags flags = ClampFlags.DEFAULT)
        {
            result = new MapPos();

            Vec3D position;
            Vec3  direction;

            if (!GetScreenVectors(x, y, size_x, size_y, out position, out direction))
            {
                return(false);
            }

            Intersector isect = new Intersector();

            if ((flags & ClampFlags.FRUSTRUM_CULL) != 0 && _camera != null && _camera.IsValid())
            {
                isect.SetCamera(_camera);

                if (_camera.RoiPosition)
                {
                    position = position - _camera.Position;
                }
            }

            isect.SetStartPosition((Vec3)(position));
            isect.SetDirection(direction);

            if (isect.Intersect(_currentMap, IntersectQuery.NEAREST_POINT | IntersectQuery.NORMAL | ((flags & ClampFlags.WAIT_FOR_DATA) != 0 ? IntersectQuery.WAIT_FOR_DYNAMIC_DATA : 0), 1, true, _camera.Position))
            {
                IntersectorResult res = isect.GetResult();

                IntersectorData data = res.GetData(0);

                result.position = data.position;

                if (_camera.RoiPosition)
                {
                    result.position = result.position + _camera.Position;
                }

                result.normal = data.normal;

                result.clamped = true;
            }

            isect.Dispose();   // Drop handle and ignore GC

            if (_topRoi != null)
            {
                result.roiNode = _topRoi.GetClosestRoiNode(result.position);

                // Remove roiNode position as offset - Go to local RoiNode based coordinate system

                if (result.roiNode != null && result.roiNode.IsValid())
                {
                    result.position -= result.roiNode.Position;
                }
            }

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Get a Local mappos in Global ray direction
        /// </summary>
        /// <param name="global_position"></param>
        /// <param name="direction"></param>
        /// <param name="result"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public bool GetGroundPosition(Vec3D global_position, Vec3 direction, out MapPos result, ClampFlags flags = ClampFlags.DEFAULT)
        {
            result = new MapPos();

            // Coordinate is now in world Cartesian coordinates (Roi Position)

            Vec3D origo = new Vec3D(0, 0, 0);       // Set used origo for clamp operation

            Intersector isect = new Intersector();

            // Check camera frustrum -----------------------------------------------------------

            if (_camera != null && _camera.IsValid())
            {
                origo = _camera.Position;

                if ((flags & ClampFlags.FRUSTRUM_CULL) != 0)
                {
                    isect.SetCamera(_camera);
                }
            }

            // Adjust intersector to use origo as center
            global_position = global_position - origo;

            isect.SetStartPosition((Vec3)global_position);
            isect.SetDirection(direction);

            if (isect.Intersect(_currentMap, IntersectQuery.ABC_TRI |
                                IntersectQuery.NEAREST_POINT |
                                (flags.HasFlag(ClampFlags.ALIGN_NORMAL_TO_SURFACE) ? IntersectQuery.NORMAL : 0) |                      //IntersectQuery.NORMAL |
                                (flags.HasFlag(ClampFlags.WAIT_FOR_DATA) ? IntersectQuery.WAIT_FOR_DYNAMIC_DATA : 0),
                                1, true, origo))
            {
                IntersectorResult res = isect.GetResult();

                IntersectorData data = res.GetData(0);

                result.position = data.coordinate + origo;

                if ((data.resultMask & IntersectQuery.NORMAL) != 0)
                {
                    result.normal = data.normal;
                }

                if (data.resultMask.HasFlag(IntersectQuery.ABC_TRI))
                {
                    result.a = data.a + origo;
                    result.b = data.b + origo;
                    result.c = data.c + origo;
                }

                result.clampResult = data.resultMask;
            }
            else
            {
                result.clampResult = IntersectQuery.NULL;
            }

            isect.Dispose();   // Drop handle and ignore GC

            result.local_orientation = GetLocalOrientation(result.position);

            if (result.clampResult == IntersectQuery.NULL)
            {
                result.normal = result.local_orientation.GetCol(2);
            }

            return(ToLocal(result));
        }
Exemplo n.º 24
0
        public bool UpdatePosition(MapPos result, GroundClampType groundClamp = GroundClampType.NONE, ClampFlags flags = ClampFlags.DEFAULT)
        {
            if (_currentMap == null)    // No map
            {
                return(false);
            }

            result.normal = result.local_orientation.GetCol(2);

            if (groundClamp != GroundClampType.NONE)
            {
                // Add ROINode position as offset   - Go to global 3D coordinate system as we need to clamp in global 3D

                RoiNode roi = result.node as RoiNode;

                if (roi != null && roi.IsValid())
                {
                    result.position += roi.Position;
                }

                // The defined down vector

                Vec3 down = new Vec3(-result.local_orientation.v13, -result.local_orientation.v23, -result.local_orientation.v33);


                // Check triangel ground

                if (result.clampResult.HasFlag(IntersectQuery.ABC_TRI))
                {
                    if (Intersect(result.position, down, result.a, result.b, result.c, out Vec3D p))
                    {
                        result.position = p;
                        ToLocal(result);

                        return(true);
                    }
                }

                // Check new intersector


                Intersector isect = new Intersector();

                Vec3D origo = new Vec3D(0, 0, 0);

                // Check camera frustrum -----------------------------------------------------------

                if (_camera != null && _camera.IsValid())
                {
                    origo = _camera.Position;

                    if ((flags & ClampFlags.FRUSTRUM_CULL) != 0)
                    {
                        isect.SetCamera(_camera);
                    }
                }

                if ((flags & ClampFlags.ISECT_LOD_QUALITY) != 0)                // Lets stand in the ray to get highest quality
                {
                    origo = result.position;
                }


                isect.SetStartPosition((Vec3)(result.position - origo) - 10000.0f * down);  // Move backwards
                isect.SetDirection(down);

                if (isect.Intersect(_currentMap, IntersectQuery.NEAREST_POINT | IntersectQuery.ABC_TRI |
                                    (flags.HasFlag(ClampFlags.ALIGN_NORMAL_TO_SURFACE) ? IntersectQuery.NORMAL : 0) |                 //IntersectQuery.NORMAL |
                                    (flags.HasFlag(ClampFlags.WAIT_FOR_DATA) ? IntersectQuery.WAIT_FOR_DYNAMIC_DATA : 0) |
                                    (flags.HasFlag(ClampFlags.UPDATE_DATA) ? IntersectQuery.UPDATE_DYNAMIC_DATA : 0)
                                    , 1, true, origo))
                {
                    IntersectorResult res = isect.GetResult();

                    IntersectorData data = res.GetData(0);

                    result.position = data.coordinate + origo;

                    if ((data.resultMask & IntersectQuery.NORMAL) != 0)
                    {
                        result.normal = data.normal;
                    }

                    if (data.resultMask.HasFlag(IntersectQuery.ABC_TRI))
                    {
                        result.a = data.a + origo;
                        result.b = data.b + origo;
                        result.c = data.c + origo;
                    }

                    result.clampResult = data.resultMask;
                }
                else
                {
                    result.clampResult = IntersectQuery.NULL;
                }

                //if (groundClamp == GroundClampType.GROUND)
                //{
                //    result.normal = result.local_orientation.GetCol(2);
                //}


                isect.Dispose();    // Drop handle and ignore GC

                // Remove ROINode position as offset - Go to local coordinate system under ROI Node

                ToLocal(result);
            }

            result.clampFlags = flags;
            result.clampType  = groundClamp;

            return(true);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Find cut line through the intersection of dcel faces.
        /// Each dcel face is bounded by lines in the dual plane, representing the points to separate equally.
        /// </summary>
        /// <param name="a_region1"></param>
        /// <param name="a_region2"></param>
        /// <param name="a_region3"></param>
        /// <returns></returns>
        public static List <Line> FindCutlinesInDual(List <Face> a_region1, List <Face> a_region2, List <Face> a_region3)
        {
            a_region1.Sort((f1, f2) => f1.BoundingBox().xMin.CompareTo(f2.BoundingBox().xMin));
            a_region2.Sort((f1, f2) => f1.BoundingBox().xMin.CompareTo(f2.BoundingBox().xMin));
            a_region3.Sort((f1, f2) => f1.BoundingBox().xMin.CompareTo(f2.BoundingBox().xMin));

            var region1 = a_region1.Select(x => x.Polygon.Outside).ToList();
            var region2 = a_region2.Select(x => x.Polygon.Outside).ToList();
            var region3 = a_region3.Select(x => x.Polygon.Outside).ToList();

            var intermediateList = new List <Polygon2D>();

            //Intersect first two lists
            var list1index = 0;
            var list2index = 0;

            while (list1index < region1.Count && list2index < region2.Count)
            {
                //progress trough y coordinates
                var intersection = Intersector.IntersectConvex(region1[list1index], region2[list2index]);
                if (intersection != null)
                {
                    intermediateList.Add(intersection);
                }

                if (region2[list2index].BoundingBox().xMax < region1[list1index].BoundingBox().xMax)
                {
                    list2index++;
                }
                else
                {
                    list1index++;
                }
            }

            var result = new List <Polygon2D>();
            //Intersect intermediate list and last list
            var intermediateIndex = 0;
            var list3index        = 0;

            while (intermediateIndex < intermediateList.Count && list3index < region3.Count)
            {
                //progress trough y coordinates
                var intersection = Intersector.IntersectConvex(intermediateList[intermediateIndex], region3[list3index]);
                if (intersection != null)
                {
                    result.Add(intersection);
                }

                if (region3[list3index].BoundingBox().xMax < intermediateList[intermediateIndex].BoundingBox().xMax)
                {
                    list3index++;
                }
                else
                {
                    intermediateIndex++;
                }
            }

            //Convert polygons to lines
            return(FindCutLinesInDual(result));
        }
Exemplo n.º 26
0
        public void Connect()
        {
            // check validness (1) 2pts, (2) line segment not exist; (3) not crossed with existing segments (5) not intersecting existing polygon

            if (m_selected_points.Count < 2)
            {
                return;
            }
            var seg   = new P2Segment(m_selected_points[0].Pos, m_selected_points[1].Pos, player1Turn);
            var segLS = new LineSegment(m_selected_points[0].Pos, m_selected_points[1].Pos);


            //Debug.Log(seg.Segment.Point1 + "," + seg.Segment.Point2);


            if (m_segments.Contains(segLS))
            {
                return;
            }



            foreach (P2Segment s in PlayerSegments[playerIndex])
            {
                if (LineSegment.IntersectProper(s.Segment, seg.Segment) != null)
                {
                    return;
                }
            }

            if (SegIntersectPolygon(seg, playerIndex))
            {
                return;
            }

            //points on existing polygon cannot be selected.
            //Some explanations: If we can select points on existing polygon, we need to deal with the case: one line segement connecting two polygon
            //If we want to find a largest circle, this is NP-hard problem(Hamilton Cycle)



            operated = true;

            //add both vertices and segment to current player
            PlayerPoints[playerIndex].Add(seg.Segment.Point1);
            PlayerPoints[playerIndex].Add(seg.Segment.Point2);
            PlayerPoints[playerIndex] = PlayerPoints[playerIndex].Distinct().ToList();

            PlayerSegments[playerIndex].Add(seg);
            m_segments.Add(segLS);

            //draw line segment,
            var mesh = Instantiate(PlayerLineMeshesPrefab[playerIndex], Vector3.forward, Quaternion.identity) as GameObject;

            mesh.transform.parent = LineMeshCollection[playerIndex].transform;
            mesh.GetComponent <P2Segment>().CopySegment(seg);

            instantObjects.Add(mesh);
            PlayerLineMeshes[playerIndex].Add(mesh);

            var meshScript = mesh.GetComponent <ReshapingMesh>();

            meshScript.CreateNewMesh(seg.Segment.Point1, seg.Segment.Point2);



            // add new convex hull (if exist) to current player, draw convex hull, update score

            Polygon2D newpolygon = FindPolygon(playerIndex, seg.Segment.Point1);



            if (newpolygon != null)
            {
                Debug.Log("new polygon v cnt: " + newpolygon.VertexCount.ToString());


                PlayerPolygons[playerIndex].Add(newpolygon);
                CanvasPlayerPolygons[playerIndex].Add(PolygonOnCanvas(newpolygon));


                string printtext = "";
                foreach (var v in newpolygon.Vertices)
                {
                    printtext += "(" + v.x + "," + v.y + ")  ";
                }

                Debug.Log(printtext);

                UpdateMesh(newpolygon, playerIndex, true);

                if (newpolygon.VertexCount > 0)
                {
                    PlayerScore[playerIndex] += newpolygon.Area;
                }

                //For the other player, disable the merging for polygon with intersection

                foreach (Polygon2D polygon in PlayerPolygons[1 - playerIndex])
                {
                    int i = PlayerPolygons[1 - playerIndex].IndexOf(polygon);

                    Debug.Log("Polygon in oppo1: " + PolygonOnCanvas(polygon).VertexCount);
                    Debug.Log("Polygon in oppo2: " + PolygonOnCanvas(newpolygon).VertexCount);

                    if (Intersector.ifIntersect(PolygonOnCanvas(polygon), PolygonOnCanvas(newpolygon)))
                    {
                        PlayerPolygonObjects[1 - playerIndex][i].GetComponent <P2Hull>().mergeChance = false;
                    }
                }

                UpdateScore();
            }
            UpdateTrapezoidalDecomposition();
        }
Exemplo n.º 27
0
        public void Merge()
        {
            //check validness (1) 2 polygon, (2) mergechance > 1;
            if (m_selected_convexhulls.Count < 2)
            {
                return;
            }
            foreach (GameObject hullObject in m_selected_convexhulls)
            {
                if (!hullObject.GetComponent <P2Hull>().mergeChance)
                {
                    return;
                }
            }

            //Compute new convex hull,  add new convex hull to current player, update score

            operated = true;

            Polygon2D newhull = ConvexHull.ComputeConvexHull(m_selected_convexhulls[0].GetComponent <P2Hull>().hull, m_selected_convexhulls[1].GetComponent <P2Hull>().hull);

            Debug.Log(m_selected_convexhulls[0].GetComponent <P2Hull>().hull.Area + ", " + m_selected_convexhulls[1].GetComponent <P2Hull>().hull.Area + "=" + newhull.Area);

            PlayerPolygons[playerIndex].Add(newhull);
            foreach (var v in newhull.Vertices)
            {
                PlayerPointsOnPolygons[playerIndex].Add(v);
            }

            CanvasPlayerPolygons[playerIndex].Add(PolygonOnCanvas(newhull));

            foreach (var v in newhull.Vertices)
            {
                PlayerPoints[playerIndex].Add(v);
            }
            foreach (var seg in newhull.Segments)
            {
                PlayerSegments[playerIndex].Add(new P2Segment(seg.Point1, seg.Point2, player1Turn));
            }


            //disable merges
            m_selected_convexhulls[0].GetComponent <P2Hull>().mergeChance = false;
            m_selected_convexhulls[1].GetComponent <P2Hull>().mergeChance = false;

            foreach (Polygon2D polygon in PlayerPolygons[1 - playerIndex])
            {
                int i = PlayerPolygons[1 - playerIndex].IndexOf(polygon);

                if (Intersector.ifIntersect(PolygonOnCanvas(polygon), PolygonOnCanvas(newhull)))
                {
                    PlayerPolygonObjects[1 - playerIndex][i].GetComponent <P2Hull>().mergeChance = false;
                }
            }

            UpdateMesh(newhull, playerIndex, false);


            if (newhull.VertexCount > 0)
            {
                PlayerScore[playerIndex] += newhull.Area;
            }
            UpdateScore();

            UpdateTrapezoidalDecomposition();
        }