示例#1
0
    // Retrace portals between corners and register if type of polygon changes
    public static int RetracePortals(NavMeshQuery query, int startIndex, int endIndex, NativeSlice <PolygonId> path, int n, Vector3 termPos, ref NativeList <NavMeshLocation> straightPath, int maxStraightPath)
    {
#if DEBUG_CROWDSYSTEM_ASSERTS
        Assert.IsTrue(n < maxStraightPath);
        Assert.IsTrue(startIndex <= endIndex);
#endif

        for (var k = startIndex; k < endIndex - 1; ++k)
        {
            var type1 = query.GetPolygonType(path[k]);
            var type2 = query.GetPolygonType(path[k + 1]);
            if (type1 != type2)
            {
                Vector3 l, r;
                var     status = query.GetPortalPoints(path[k], path[k + 1], out l, out r);

#if DEBUG_CROWDSYSTEM_ASSERTS
                Assert.IsTrue(status); // Expect path elements k, k+1 to be verified
#endif

                float3 cpa1, cpa2;
                GeometryUtils.SegmentSegmentCPA(out cpa1, out cpa2, l, r, straightPath[n - 1].position, termPos);
                straightPath.Add(query.CreateLocation(cpa1, path[k + 1]));

                // straightPathFlags[n] = (type2 == NavMeshPolyTypes.OffMeshConnection) ? StraightPathFlags.OffMeshConnection : 0;
                if (++n == maxStraightPath)
                {
                    // Debug.Log($"1: {n} {maxStraightPath} {startIndex} {endIndex} {straightPath.Length}");

                    return(maxStraightPath);
                }
            }
        }
        // Debug.Log($"2:{n} {maxStraightPath} {startIndex} {endIndex} {straightPath.Length}");

        // if (n < straightPath.Length)
        // {
        straightPath.Add(query.CreateLocation(termPos, path[endIndex]));
        // straightPathFlags[n] = query.GetPolygonType(path[endIndex]) == NavMeshPolyTypes.OffMeshConnection ? StraightPathFlags.OffMeshConnection : 0;
        return(++n);
        // }
        // else
        // {
        //     // Debug.LogWarning($"寻路出现错误 {termPos}");
        //     // 拐角的时候可能多一个,然后就错误,暂时这样改
        //     straightPath[n - 1] = query.CreateLocation(termPos, path[endIndex]);
        //     straightPathFlags[n - 1] = query.GetPolygonType(path[endIndex]) == NavMeshPolyTypes.OffMeshConnection ? StraightPathFlags.OffMeshConnection : 0;
        //     // for (var i = 0; i < straightPath.Length; i++)
        //     // {
        //     //     Debug.Log(straightPath[i].position);
        //     // }
        // }

        // // if (n > straightPath.Length - 1) // Fix for IndexOutOfRangeException with one point on straightPath[n]
        // // {
        // //     return n;
        // // }

        // // straightPath[n] = query.CreateLocation(termPos, path[endIndex]);
        // // straightPathFlags[n] = query.GetPolygonType(path[endIndex]) == NavMeshPolyTypes.OffMeshConnection ? StraightPathFlags.OffMeshConnection : 0;
        // // return ++n;

        // return n;
    }
示例#2
0
        void CalculateClosestLandmark(ILandmarkController landmark)
        {
            var settings = landmark.settings as ClosestLandmarkSettings;

            if (settings == null)
            {
                return;
            }

            if (worldVertices == null || settings.target == null)
            {
                return;
            }

            if (m_WorldVerts.Count < 3)
            {
                return;
            }

            Vector3 edgeVertA;
            Vector3 edgeVertB;

            switch (landmark.output)
            {
            case LandmarkOutputPoint landmarkPoint:
            {
                var targetPolygon = settings.target as LandmarkOutputPolygon;
                if (targetPolygon && targetPolygon.worldVertices.Count > 0)
                {
                    Vector3 closestOnThis, closestOnOther;
                    GeometryUtils.ClosestPolygonApproach(m_WorldVerts, targetPolygon.worldVertices, out closestOnThis, out closestOnOther);
                    landmarkPoint.position = closestOnThis;
                }
                else
                {
                    var targetPosition       = settings.target.transform.position;
                    var planeNormal          = Vector3.Cross(m_WorldVerts[0] - m_WorldVerts[1], m_WorldVerts[2] - m_WorldVerts[1]).normalized;
                    var pointOnInfinitePlane = GeometryUtils.ProjectPointOnPlane(planeNormal, m_WorldVerts[1], targetPosition);
                    if (GeometryUtils.PointInPolygon3D(pointOnInfinitePlane, m_WorldVerts))
                    {
                        landmarkPoint.position = pointOnInfinitePlane;
                    }
                    else
                    {
                        GeometryUtils.FindClosestEdge(m_WorldVerts, targetPosition, out edgeVertA, out edgeVertB);
                        landmarkPoint.position = GeometryUtils.ClosestPointOnLineSegment(targetPosition, edgeVertA, edgeVertB);
                    }
                }
            }
            break;

            case LandmarkOutputEdge landmarkEdge:
            {
                var targetPosition = settings.target.transform.position;
                GeometryUtils.FindClosestEdge(m_WorldVerts, targetPosition, out edgeVertA, out edgeVertB);
                landmarkEdge.startPoint = edgeVertA;
                landmarkEdge.endPoint   = edgeVertB;
            }
            break;

            case LandmarkOutputPose landmarkPose:
            {
                var     targetPolygon = settings.target as LandmarkOutputPolygon;
                Vector3 closestOnThis, closestOnOther;

                if (targetPolygon && targetPolygon.worldVertices.Count > 0)
                {
                    GeometryUtils.ClosestPolygonApproach(m_WorldVerts, targetPolygon.worldVertices, out closestOnThis, out closestOnOther);
                }
                else
                {
                    closestOnOther = settings.target.transform.position;
                    var planeNormal          = Vector3.Cross(m_WorldVerts[0] - m_WorldVerts[1], m_WorldVerts[2] - m_WorldVerts[1]).normalized;
                    var pointOnInfinitePlane = GeometryUtils.ProjectPointOnPlane(planeNormal, m_WorldVerts[1], closestOnOther);
                    if (GeometryUtils.PointInPolygon3D(pointOnInfinitePlane, m_WorldVerts))
                    {
                        closestOnThis = pointOnInfinitePlane;
                    }
                    else
                    {
                        GeometryUtils.FindClosestEdge(m_WorldVerts, closestOnOther, out edgeVertA, out edgeVertB);
                        closestOnThis = GeometryUtils.ClosestPointOnLineSegment(closestOnOther, edgeVertA, edgeVertB);
                    }
                }
                // Make sure look direction is flattened along the plane
                var lookDirection = closestOnOther - closestOnThis;
                lookDirection            = Vector3.Cross(Vector3.Cross(lookDirection, transform.up), transform.up);
                landmarkPose.currentPose = new Pose {
                    position = closestOnThis, rotation = Quaternion.LookRotation(lookDirection)
                };
            }
            break;
            }
        }
示例#3
0
        private IEnumerable <IPath> GetConnectLineCandidates(
            [NotNull] IPoint forUnpairedSourcePoint,
            [NotNull] IPath reshapePath,
            [NotNull] IList <IGeometry> geometriesToReshape,
            IPointCollection sketchOriginalIntersectionPoints)
        {
            var touchingPaths = new List <IPath>();

            if (_sourceIntersectionLines != null)
            {
                foreach (IPath intersectionPath in
                         GeometryUtils.GetPaths(_sourceIntersectionLines))
                {
                    if (
                        GeometryUtils.AreEqualInXY(intersectionPath.FromPoint,
                                                   forUnpairedSourcePoint) ||
                        GeometryUtils.AreEqualInXY(intersectionPath.ToPoint, forUnpairedSourcePoint)
                        )
                    {
                        touchingPaths.Add(intersectionPath);
                    }
                }
            }

            var connectLineCandidates = new List <IPath>();

            foreach (IPath sharedBoundary in touchingPaths)
            {
                if (IntersectsOtherSourceTargetConnection(sharedBoundary,
                                                          sketchOriginalIntersectionPoints,
                                                          SourceTargetPairs))
                {
                    continue;
                }

                IList <IGeometry> sharedBoundaryPolys;
                if (PathRunsAlongSeveralPolygons(sharedBoundary, geometriesToReshape,
                                                 forUnpairedSourcePoint,
                                                 out sharedBoundaryPolys))
                {
                    IGeometry sharedBoundaryPoly = sharedBoundaryPolys[0];

                    double xyTolerance = GeometryUtils.GetXyTolerance(sharedBoundaryPoly);

                    var curveToReshape =
                        (ICurve)
                        GeometryUtils.GetHitGeometryPart(forUnpairedSourcePoint, sharedBoundaryPoly,
                                                         xyTolerance);

                    Assert.NotNull(curveToReshape);

                    IPoint targetConnectPoint;
                    IPath  connectLineCandidate = GetSharedBoundaryProlongation(
                        curveToReshape, sharedBoundary, forUnpairedSourcePoint, reshapePath,
                        xyTolerance,
                        out targetConnectPoint);

                    // Only change those polygons that have not already been reshaped using the sketch.
                    if (connectLineCandidate != null &&
                        AllPolygonsAreDisjoint(sharedBoundaryPolys, targetConnectPoint) &&
                        !CrossesOtherGeometry(connectLineCandidate, geometriesToReshape))
                    {
                        connectLineCandidates.Add(connectLineCandidate);
                    }
                }
            }

            return(connectLineCandidates);
        }
示例#4
0
        override protected void CreateResources()
        {
            // RgbaFloat lightColor = RgbaFloat.Orange;
            RgbaFloat lightColor = RgbaFloat.Blue;
            //RgbaFloat lightColor = RgbaFloat.LightGrey;
            var spotLightPos = new Vector4(0.0f, 5.0f, 7.0f, 1.0f);
            var lightLookAt  = spotLightPos - Light.DEFAULT_POSITION;
            var lightCam     = new OrthographicCamera(35, 35, Light.DEFAULT_POSITION, lightLookAt);
            var spotLightCam = new OrthographicCamera(RenderResoultion.Horizontal, RenderResoultion.Vertical, spotLightPos, Light.DEFAULT_LOOKAT);

            // RgbaFloat lightColor = new RgbaFloat(1.0f,0.36f,0.0f,0.2f);
            _sceneRuntimeState.Light  = new Light(lightCam, lightColor, 0.1f);
            _sceneRuntimeState.Camera = Camera;
            _sceneRuntimeState.SpotLight
                = new Light(
                      spotLightCam,
                      RgbaFloat.DarkRed,
                      1.0f,
                      0.02f,
                      new Vector4(Math.Cos(17.5f.ToRadians()).ToFloat(), Math.Cos(12.5f.ToRadians()).ToFloat(), 0.0f, 1.0f));

            // Sun //TODO: Make this VertexPositionNormalColor
            _sun = new Model <VertexPositionNormal, RealtimeMaterial>(String.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 1), new RealtimeMaterial());
            var sunMeshZero     = _sun.GetMesh(0);
            var sunMaterialZero = _sun.GetMaterial(0);

            // _sun.meshes[0].TryGetMaterial().ambient = new Vector4(0.0f,0.0f,0.0f,0.0f);
            sunMaterialZero.ambient = lightColor.ToVector4();
            Vector4 lightPos       = _sceneRuntimeState.Light.LightPos;
            Vector3 newTranslation = new Vector3(lightPos.X, lightPos.Y, lightPos.Z);

            _sun.SetNewWorldTranslation(ref newTranslation, true);

            //TODO: This geometry will cause problems for shadow mapping. Has to be ignored in the shadowmap generation process.
            var sunRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormal>(_sun, "Phong", "PhongNoShadow", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sunRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;
            _modelPNDescriptorList.Add(sunRuntimeState);

            var spotlight             = new Model <VertexPositionNormal, RealtimeMaterial>(String.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 1), new RealtimeMaterial());
            var spotlightMeshZero     = spotlight.GetMesh(0);
            var spotlightMaterialZero = spotlight.GetMaterial(0);

            //TODO: @Bug: Seems to be an issue with ambient selecting the wrong color
            spotlightMaterialZero.ambient = _sceneRuntimeState.SpotLight.Color_DontMutate;
            // spotlight.meshes[0].TryGetMaterial().ambient = new Vector4(1.0f,1.0f,1.0f,1.0f);
            // _sun.meshes[0].TryGetMaterial().ambient = lightColor.ToVector4();
            Vector4 lightPosSpot       = _sceneRuntimeState.SpotLight.LightPos;
            Vector3 newTranslationSpot = new Vector3(lightPosSpot.X, lightPosSpot.Y, lightPosSpot.Z);

            spotlight.SetNewWorldTranslation(ref newTranslationSpot, true);

            var spotLightRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormal>(spotlight, "Phong", "PhongNoShadow", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            spotLightRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;
            _modelPNDescriptorList.Add(spotLightRuntimeState);

            // Colored Quad
            // var offsets = new Vector3[] {new Vector3(-1.0f,0.0f,0f),new Vector3(1.0f,0.0f,0.0f)};
            // // var offsets = new Vector3[] {new Vector3(0.0f,0.0f,0.0f)};
            // var instancingData = new InstancingData {Positions = offsets};
            // var floor = new Model<VertexPositionColor>(String.Empty,GeometryFactory.GenerateColorQuad(RgbaFloat.Red,RgbaFloat.Yellow,RgbaFloat.Green,RgbaFloat.LightGrey));
            // var floorRuntimeState = new ModelRuntimeDescriptor<VertexPositionColor>(floor,"OffsetColor","Color",VertexTypes.VertexPositionColor,PrimitiveTopology.TriangleStrip);
            // floorRuntimeState.TotalInstanceCount = offsets.Length.ToUnsigned();
            // floorRuntimeState.CallVertexLayoutGeneration+=ResourceGenerator.GenerateVertexLayoutForPC;
            // floorRuntimeState.CallVertexInstanceLayoutGeneration+=ResourceGenerator.GenerateVertexInstanceLayoutForPC;
            // _modelPCDescriptorList.Add(floorRuntimeState);

            //Quad Textured
            // var offsets = new Vector3[] {new Vector3(-1.0f,0.0f,0f),new Vector3(1.0f,0.0f,0.0f)};
            // // var offsets = new Vector3[] {new Vector3(0.0f,0.0f,0.0f)};
            // var instancingData = new InstancingData {Positions = offsets};
            // var floor = new Model<VertexPositionTexture>("paving",GeometryFactory.GenerateTexturedQuad());
            // floor.meshes[0].TryGetMaterial().textureDiffuse="pavingColor.jpg";
            // var floorRuntimeState = new ModelRuntimeDescriptor<VertexPositionTexture>(floor,"PositionOffsetTexture","Texture",VertexTypes.VertexPositionTexture,PrimitiveTopology.TriangleStrip);
            // floorRuntimeState.TotalInstanceCount = offsets.Length.ToUnsigned();

            // floorRuntimeState.CallVertexLayoutGeneration+=ResourceGenerator.GenerateVertexLayoutForPT;
            // floorRuntimeState.CallVertexInstanceLayoutGeneration+=ResourceGenerator.GenerateVertexInstanceLayoutForPositionOffset;
            // floorRuntimeState.CallTextureResourceLayoutGeneration+=ResourceGenerator.GenerateTextureResourceLayoutForDiffuseMapping;
            // floorRuntimeState.CallTextureResourceSetGeneration+=ResourceGenerator.GenerateTextureResourceSetForDiffuseMapping;
            // floorRuntimeState.CallSamplerGeneration+=ResourceGenerator.GenerateLinearSampler;
            // _modelPTDescriptorList.Add(floorRuntimeState);

            // floor
            // var offsets = new Vector3[] {new Vector3(-1.0f,0.0f,0f),new Vector3(1.0f,0.0f,0.0f)};
            // var offsets = new Vector3[] {new Vector3(0.0f,0.0f,0.0f)};
            var offsets = GeometryUtils.CreateTilingList_XZ(-20, 20, -10, 10, 0, GeometryFactory.QUAD_WIDTH, GeometryFactory.QUAD_HEIGHT);
            // var offsets = GeometryUtils.CreateTilingList_XZ(-1,1,0,0,0,GeometryFactory.QUAD_WIDTH,GeometryFactory.QUAD_HEIGHT);
            var instancingData = new InstanceData {
                Flag = InstancingDataFlags.POSITION, Positions = offsets
            };

            var floor             = new Model <VertexPositionNormalTextureTangentBitangent, RealtimeMaterial>("paving/", GeometryFactory.GenerateQuadPNTTB_XZ(), new RealtimeMaterial());
            var floorMeshZero     = floor.GetMesh(0);
            var flootMaterialZero = floor.GetMaterial(0);

            flootMaterialZero.textureDiffuse = "pavingColor.jpg";
            flootMaterialZero.textureNormal  = "pavingNorm.jpg";
            flootMaterialZero.ambient        = new Vector4(0.3f, 0.3f, 0.3f, 1.0f);
            var floorTranslation = new Vector3(0.0f, -2.0f, 0.0f);

            floor.SetNewWorldTranslation(ref floorTranslation, true);
            var floorRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(floor, "PositionOffsetPhongBitangentTexture", "PhongBitangentTexture", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleStrip, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.SHADOW_MAP, InstancingDataFlags.POSITION));

            floorRuntimeState.TotalInstanceCount = offsets.Length.ToUnsigned();

            //TODO: Test ViewMatrix Instancing
            // Matrix4x4 test = Camera.ViewMatrix;
            // Matrix4x4 test2 = Camera.ViewMatrix;
            // test.Translation = new Vector3(0,1,-10);
            // test2.Translation = new Vector3(0,0,-10);
            // var viewMatrices = new Matrix4x4[] {test2, test};


            // var viewInstancingData = new InstancingData{
            //     Types = InstancingTypes.ViewMatricies,
            //     ViewMatrices = viewMatrices
            //     };
            // var floorRuntimeState = new ModelRuntimeDescriptor<VertexPositionNormalTextureTangentBitangent>(floor, "ViewMatInstancePhongBitangentTexture", "PhongBitangentTexture", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleStrip, RenderFlags.NORMAL | RenderFlags.SHADOW_MAP);
            //floorRuntimeState.TotalInstanceCount = viewMatrices.Length.ToUnsigned();

            floorRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPNTTB;
            floorRuntimeState.AddVertexInstanceDelegate(InstancingDataFlags.POSITION, ResourceGenerator.GenerateVertexInstanceLayoutForPositionOffset);
            floorRuntimeState.AddPreEffectsVertexInstanceDelegate(RenderFlags.SHADOW_MAP, ResourceGenerator.GenerateVertexLayoutForPNTTB);
            //floorRuntimeState.CallVertexInstanceLayoutGeneration+=ResourceGenerator.GenerateVertexInstanceLayoutForViewMatrixOffset; //viewMatInstance
            floorRuntimeState.CallTextureResourceLayoutGeneration += ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            floorRuntimeState.CallTextureResourceSetGeneration    += ResourceGenerator.GenerateTextureResourceSetForNormalMapping;
            floorRuntimeState.CallSamplerGeneration += ResourceGenerator.GenerateTriLinearSampler;
            _modelPNTTBDescriptorList.Add(floorRuntimeState);


            InstanceData[] instancingDataPN    = { InstanceData.NO_DATA };
            InstanceData[] instancingDataPNTTB = { instancingData };

            foreach (var modelDescriptor in _modelPNDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingDataPN);
                PNRuntimeGeometry.AddModel(modelDescriptor);
            }

            // foreach(var modelDescriptor in _modelPTDescriptorList){
            //     FillRuntimeDescriptor(modelDescriptor,_sceneRuntimeState,InstancingData.NO_DATA);
            // }

            foreach (var modelDescriptor in _modelPNTTBDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingDataPNTTB);
                PNTTBRuntimeGeometry.AddModel(modelDescriptor);
            }
        }
示例#5
0
        public DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuffer cmd, float time)
        {
            DensityVolumeList densityVolumes = new DensityVolumeList();

            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics))
            {
                return(densityVolumes);
            }

            var visualEnvironment = VolumeManager.instance.stack.GetComponent <VisualEnvironment>();

            if (visualEnvironment.fogType.value != FogType.Volumetric)
            {
                return(densityVolumes);
            }

            using (new ProfilingSample(cmd, "Prepare Visible Density Volume List"))
            {
                Vector3 camPosition = hdCamera.camera.transform.position;
                Vector3 camOffset   = Vector3.zero;// World-origin-relative

                if (ShaderConfig.s_CameraRelativeRendering != 0)
                {
                    camOffset = camPosition; // Camera-relative
                }

                m_VisibleVolumeBounds.Clear();
                m_VisibleVolumeData.Clear();

                // Collect all visible finite volume data, and upload it to the GPU.
                DensityVolume[] volumes = DensityVolumeManager.manager.PrepareDensityVolumeData(cmd, hdCamera.camera, time);

                for (int i = 0; i < Math.Min(volumes.Length, k_MaxVisibleVolumeCount); i++)
                {
                    DensityVolume volume = volumes[i];

                    // TODO: cache these?
                    var obb = new OrientedBBox(Matrix4x4.TRS(volume.transform.position, volume.transform.rotation, volume.parameters.size));

                    // Handle camera-relative rendering.
                    obb.center -= camOffset;

                    // Frustum cull on the CPU for now. TODO: do it on the GPU.
                    // TODO: account for custom near and far planes of the V-Buffer's frustum.
                    // It's typically much shorter (along the Z axis) than the camera's frustum.
                    // XRTODO: fix combined frustum culling
                    if (GeometryUtils.Overlap(obb, hdCamera.frustum, 6, 8) || hdCamera.camera.stereoEnabled)
                    {
                        // TODO: cache these?
                        var data = volume.parameters.ConvertToEngineData();

                        m_VisibleVolumeBounds.Add(obb);
                        m_VisibleVolumeData.Add(data);
                    }
                }

                s_VisibleVolumeBoundsBuffer.SetData(m_VisibleVolumeBounds);
                s_VisibleVolumeDataBuffer.SetData(m_VisibleVolumeData);

                // Fill the struct with pointers in order to share the data with the light loop.
                densityVolumes.bounds  = m_VisibleVolumeBounds;
                densityVolumes.density = m_VisibleVolumeData;

                return(densityVolumes);
            }
        }
示例#6
0
 public void TestCalcTriangleArea8_ThrowsException()
 {
     double area = GeometryUtils.CalcTriangleArea(18.24, 100, 31.0057);
 }
示例#7
0
        public SubcurveFilter PrepareFilter(
            [NotNull] IList <IPolyline> preprocessedSourceLines,
            [NotNull] IList <IGeometry> targetGeometries,
            bool useMinimalTolerance,
            [NotNull] ReshapeCurveFilterOptions filterOptions)
        {
            _useMinimalTolerance = useMinimalTolerance;
            _filterOptions       = filterOptions;

            ReleaseFilterObjects();

            if (filterOptions.OnlyInVisibleExtent)
            {
                Assert.NotNull(_extentProvider);
                _currentlyVisibleExtents = new List <IEnvelope>();

                // add the lens window extents
                _currentlyVisibleExtents.AddRange(
                    _extentProvider.GetVisibleLensWindowExtents());

                // plus the main map window
                _currentlyVisibleExtents.Add(_extentProvider.GetCurrentExtent());
            }

            if (filterOptions.ExcludeOutsideTolerance)
            {
                // NOTE: Buffer lines / outlines -> otherwise we miss lines for individual reshapes
                //		 and clip on extent (pre-process) before buffering to improve performance

                var sourceOutline =
                    (IPolyline)GeometryUtils.UnionGeometries(preprocessedSourceLines);

                const int logInfoPointCountThreshold = 10000;
                var       bufferNotifications        = new NotificationCollection();

                if (AdjustUtils.TryBuffer(sourceOutline,
                                          filterOptions.ExcludeTolerance,
                                          logInfoPointCountThreshold,
                                          "Calculating reshape line tolerance buffer...",
                                          bufferNotifications,
                                          out _mustBeWithinSourceBuffer))
                {
                    ExclusionOutsideSourceBufferLine =
                        GeometryFactory.CreatePolyline(
                            Assert.NotNull(_mustBeWithinSourceBuffer));
                }
                else
                {
                    _msg.WarnFormat(
                        "Unable to calculate reshape line tolerance buffer: {0}",
                        bufferNotifications.Concatenate(". "));
                }

                Marshal.ReleaseComObject(sourceOutline);
            }

            if (filterOptions.ExcludeResultingInOverlaps)
            {
                _targetUnionPoly = ReshapeUtils.CreateUnionPolygon(
                    targetGeometries, _useMinimalTolerance);
            }

            return(this);
        }
示例#8
0
        public void TestCalcDistance1()
        {
            double distance = GeometryUtils.CalcDistance(0, 0, 1, 1);

            Assert.AreEqual(Math.Sqrt(2), distance);
        }
示例#9
0
        public void TestCalcDistance2()
        {
            double distance = GeometryUtils.CalcDistance(1, 1, 5, 4);

            Assert.AreEqual(5, distance);
        }
示例#10
0
        private IMultiPatch ReadMultipatch(BinaryReader reader,
                                           Ordinates expectedOrdinates,
                                           bool groupPartsByPointIDs = false)
        {
            IMultiPatch result = new MultiPatchClass();

            if (groupPartsByPointIDs)
            {
                GeometryUtils.MakePointIDAware(result);
            }

            int polyhedraCount = checked ((int)reader.ReadUInt32());

            for (int i = 0; i < polyhedraCount; i++)
            {
                WkbGeometryType geometryType;
                Ordinates       ordinates;
                ReadWkbType(reader, false,
                            out geometryType, out ordinates);

                Assert.AreEqual(WkbGeometryType.PolyhedralSurface, geometryType,
                                "Unexpected geometry type");

                Assert.AreEqual(expectedOrdinates, ordinates,
                                "Unexpected ordinates dimension");

                int polygonCount = checked ((int)reader.ReadUInt32());

                for (int p = 0; p < polygonCount; p++)
                {
                    ReadWkbType(reader, false,
                                out geometryType, out expectedOrdinates);

                    Assert.AreEqual(WkbGeometryType.Polygon, geometryType,
                                    "Unexpected geometry type");

                    var rings = ReadSingleExteriorRingPolygon(reader, ordinates, false).ToList();

                    if (rings.Count == 0)
                    {
                        continue;
                    }

                    if (groupPartsByPointIDs)
                    {
                        AssignPointIds(rings, i);
                    }

                    var outerRingType = rings.Count > 1
                                                                    ? esriMultiPatchRingType.esriMultiPatchOuterRing
                                                                    : p == 0 || groupPartsByPointIDs
                                                                            ? esriMultiPatchRingType.esriMultiPatchFirstRing
                                                                            : esriMultiPatchRingType.esriMultiPatchRing;

                    IRing outerRing = rings[0];
                    GeometryFactory.AddRingToMultiPatch(outerRing, result, outerRingType);

                    if (rings.Count > 1)
                    {
                        for (int r = 1; r < rings.Count; r++)
                        {
                            IRing innerRing = rings[r];
                            GeometryFactory.AddRingToMultiPatch(
                                innerRing, result, esriMultiPatchRingType.esriMultiPatchInnerRing);
                        }
                    }
                }
            }

            return(result);
        }
示例#11
0
            private void ProcessFeature([NotNull] Feature feature)
            {
                var shape = feature.GetShape();
                var point = Assert.NotNull(shape as MapPoint, "Input shape is not MapPoint");

                IDictionary <Feature, double> distanceByFeature =
                    GetNearFeatures(point, _referenceDatasets, _searchDistance);

                if (distanceByFeature.Count == 0)
                {
                    _msg.DebugFormat(
                        "Marker feature {0}: No reference feature found within search distance of {1}",
                        ProcessingUtils.Format(feature), _searchDistance);
                    return;
                }

                var nearest = distanceByFeature.OrderBy(f => f.Value).First();

                var referenceFeature = Assert.NotNull(nearest.Key, "Oops, bug");
                var distance         = nearest.Value;         // may be zero

                var referenceShape = referenceFeature.GetShape();
                var referenceCurve = Assert.NotNull(referenceShape as Multipart,
                                                    "Reference shape is not Multipart");

                double distanceAlongCurve = GeometryUtils.GetDistanceAlongCurve(referenceCurve, point);

                double normalLength = Math.Max(_inputDataset.XYTolerance, distance);
                var    normalPoly   = GeometryEngine.Instance.QueryNormal(
                    referenceCurve, SegmentExtension.NoExtension, distanceAlongCurve,
                    AsRatioOrLength.AsLength, normalLength);
                var normal = (LineSegment)normalPoly.Parts[0][0];                  // TODO safety guards

                double tangentLength = Math.Max(_inputDataset.XYTolerance, distance);
                var    tangentPoly   = GeometryEngine.Instance.QueryTangent(
                    referenceCurve, SegmentExtension.NoExtension, distanceAlongCurve,
                    AsRatioOrLength.AsLength, tangentLength);
                var tangent = (LineSegment)tangentPoly.Parts[0][0];                  // TODO safety guards

                // ILine.Angle is the angle between line and positive x axis,
                // but the Angle property of a representation marker has its
                // zero point at North: add 90° to ILine.Angle to fix:

                double normalOffset = MathUtils.ToDegrees(normal.Angle) - 90;
                double normalAngle  = ProcessingUtils.ToPositiveDegrees(normalOffset);

                double tangentOffset = MathUtils.ToDegrees(tangent.Angle) - 90;
                double tangentAngle  = ProcessingUtils.ToPositiveDegrees(tangentOffset);

                _markerFieldSetter.ForgetAll()
                .DefineFields(feature, InputQualifier)
                .DefineFields(referenceFeature, ReferenceQualifier)
                .DefineValue("normalAngle", normalAngle)
                .DefineValue("tangentAngle", tangentAngle)
                .DefineValue("distance", distance)
                .Execute(feature);

                feature.Store();

                FeaturesAligned += 1;

                _msg.DebugFormat(
                    "Marker feature {0}: aligned to {1} (normalAngle: {2}, tangentAngle: {3}, distance: {4})",
                    ProcessingUtils.Format(feature), ProcessingUtils.Format(referenceFeature),
                    normalAngle, tangentAngle, distance);

                // TODO need some mechanism to ensure disposal (required by Pro SDK documentation); see also OneNote
                foreach (var pair in distanceByFeature)
                {
                    pair.Key.Dispose();
                }
            }
 protected override void AdaptMZAware(IGeometry geometry)
 {
     GeometryUtils.MakeMAware(geometry);
 }
示例#13
0
        private Geometry GetNearestSearchReference([NotNull] Geometry reference)
        {
            const int maxPointCount = 10000;

            // todo daro: old implementation
            //bool useCentroid = !GeometryUtils.IsGeometryValid(reference);

            bool useCentroid = true;

            if (!useCentroid && GeometryUtils.GetPointCount(reference) > maxPointCount)
            {
                _msg.Debug("Too many points on reference geometry for searching, using center of envelope");
                useCentroid = true;
            }

            if (useCentroid)
            {
                MapPoint centroid = null;

                try
                {
                    // todo daro: old implementation
                    //var area = reference.Extent as IArea;
                    //if (area != null && ! area.Centroid.IsEmpty)
                    //{
                    //	centroid = area.Centroid;
                    //}

                    if (!reference.IsEmpty)
                    {
                        centroid = GeometryEngine.Instance.Centroid(reference);
                    }
                }
                catch (Exception e)
                {
                    _msg.Debug("Error trying to get centroid of geometry", e);
                    // todo daro: old implementation
                    //_msg.Debug(GeometryUtils.ToString(reference));
                }

                if (centroid == null)
                {
                    return(null);
                }

                reference = centroid;
            }
            // todo daro: old implementation
            //else
            //{
            //	if (reference is IMultiPatch)
            //	{
            //		reference = ((IMultiPatch)reference).XYFootprint;
            //	}
            //}

            // todo daro: old implementation
            //reference = GetInWorkListSpatialReference(reference);

            return(reference);
        }
示例#14
0
        private double ExecuteGJKAlgorithm(
            VertexProperties[] vertexShape1,
            VertexProperties[] vertexShape2,
            ref CollisionPoint cp,
            ref List <SupportTriangle> triangles,
            ref Vector3d centroid,
            ref bool isIntersection)
        {
            double minDistance      = double.MaxValue;
            int    minTriangleIndex = -1;
            var    result           = new CollisionPointOutput();
            var    oldDirection     = new Vector3d();
            var    simplex          = new Simplex();

            //Primo punto del simplex
            simplex.Support.Add(GetFarthestPoint(vertexShape1, vertexShape2, vertexShape2.Length / 2));

            //Secondo punto del simplex
            Vector3d direction = Vector3d.Normalize(simplex.Support[0].s * -1.0);

            if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, direction)))
            {
                return(-1.0);
            }

            //Terzo punto del simplex
            direction = Vector3d.Normalize(GetDirectionOnSimplex2(simplex));
            if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, direction)))
            {
                return(-1.0);
            }

            //Quarto punto del simplex
            direction = Vector3d.Normalize(GeometryUtils.CalculateTriangleNormal(
                                               simplex.Support[0].s,
                                               simplex.Support[1].s,
                                               simplex.Support[2].s));

            if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, direction)))
            {
                simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, -1.0 * direction));
            }

            //Costruisco il poliedro
            centroid = Helper.SetStartTriangle(
                ref triangles,
                simplex.Support.ToArray());

            //Verifico che l'origine sia contenuta nel poliedro
            if (Helper.IsInConvexPoly(origin, triangles))
            {
                isIntersection = true;
                return(-1.0);
            }

            Vector3d triangleDistance = GetMinDistance(ref triangles, origin, ref minTriangleIndex);

            result.SetDist(triangleDistance);
            result.SetNormal(Vector3d.Normalize(triangleDistance));
            Helper.GetVertexFromMinkowsky(triangles[minTriangleIndex], vertexShape1, vertexShape2, ref result);

            minDistance = triangleDistance.Length();

            for (int i = 0; i < MaxIterations; i++)
            {
                direction = -1.0 * triangleDistance.Normalize();

                if (Vector3d.Length(direction) < constTolerance)
                {
                    direction = origin - centroid;
                }

                if (direction == oldDirection)
                {
                    break;
                }

                oldDirection = direction;

                if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, direction)))
                {
                    for (int j = 0; j < triangles.Count; j++)
                    {
                        direction = triangles[j].Normal;
                        if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, direction)))
                        {
                            if (simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(vertexShape1, vertexShape2, -1.0 * direction)))
                            {
                                break;
                            }

                            continue;
                        }
                        break;
                    }
                }

                triangles = Helper.AddPointToConvexPolygon(triangles, simplex.Support[simplex.Support.Count - 1], centroid);

                //Verifico che l'origine sia contenuta nel poliedro
                if (Helper.IsInConvexPoly(origin, triangles))
                {
                    isIntersection = true;
                    return(-1.0);
                }

                triangleDistance = GetMinDistance(ref triangles, origin, ref minTriangleIndex);

                double mod = triangleDistance.Length();

                if (mod < minDistance)
                {
                    result.SetDist(triangleDistance);
                    result.SetNormal(triangles[minTriangleIndex].Normal);

                    Helper.GetVertexFromMinkowsky(triangles[minTriangleIndex], vertexShape1, vertexShape2, ref result);

                    minDistance = mod;
                }
            }

            cp = new CollisionPoint(result.A, result.B);

            return(minDistance);
        }
示例#15
0
 public void TestCalcTriangleArea4_ThrowsException()
 {
     double area = GeometryUtils.CalcTriangleArea(10, 30, 0);
 }
示例#16
0
        public void TestCalcDistance3()
        {
            double distance = GeometryUtils.CalcDistance(12.8, 9.73, 12.8, 9.73);

            Assert.AreEqual(0, distance);
        }
示例#17
0
 public void TestCalcTriangleArea7_ThrowsException()
 {
     double area = GeometryUtils.CalcTriangleArea(5, 12, -13);
 }
示例#18
0
 public void TestIsLineHorizontal1_ThrowsException()
 {
     bool horizontal = GeometryUtils.IsLineHorizontal(12.8, 9.73, 12.8, 9.73);
 }
示例#19
0
        public void TestCalcTriangleArea9()
        {
            double area = GeometryUtils.CalcTriangleArea(60, 91, 109);

            Assert.AreEqual(2730, area);
        }
示例#20
0
        public void TestCalcTriangleArea1()
        {
            double area = GeometryUtils.CalcTriangleArea(3, 4, 5);

            Assert.AreEqual(6, area);
        }
示例#21
0
        public static CalculateOverlapsResponse CalculateOverlaps(
            [NotNull] CalculateOverlapsRequest request,
            [CanBeNull] ITrackCancel trackCancel)
        {
            var watch = Stopwatch.StartNew();

            IList <IFeature> sourceFeatures =
                ProtobufConversionUtils.FromGdbObjectMsgList(
                    request.SourceFeatures, request.ClassDefinitions);

            IList <IFeature> targetFeatures =
                ProtobufConversionUtils.FromGdbObjectMsgList(
                    request.TargetFeatures, request.ClassDefinitions);

            _msg.DebugStopTiming(watch, "Unpacked feature lists from request params");

            Overlaps selectableOverlaps = RemoveOverlapsUtils.GetSelectableOverlaps(
                sourceFeatures, targetFeatures, trackCancel);

            watch = Stopwatch.StartNew();

            var result = new CalculateOverlapsResponse();

            foreach (var overlapByGdbRef
                     in selectableOverlaps.OverlapsBySourceRef)
            {
                var gdbObjRefMsg = ProtobufGdbUtils.ToGdbObjRefMsg(overlapByGdbRef.Key);

                var overlap = overlapByGdbRef.Value;

                var overlapsMsg = new OverlapMsg()
                {
                    OriginalFeatureRef = gdbObjRefMsg
                };

                foreach (IGeometry geometry in overlap)
                {
                    // TODO: At some point the SR-XY tol/res should be transferred separately (via class-lookup?)
                    var shapeFormat = ShapeMsg.FormatOneofCase.EsriShape;
                    var srFormat    = SpatialReferenceMsg.FormatOneofCase.SpatialReferenceEsriXml;

                    overlapsMsg.Overlaps.Add(
                        ProtobufGeometryUtils.ToShapeMsg(
                            geometry, shapeFormat, srFormat));

                    if (_msg.IsVerboseDebugEnabled)
                    {
                        _msg.VerboseDebug(
                            $"Calculated overlap: {GeometryUtils.ToString(geometry)}");
                    }
                }

                result.Overlaps.Add(overlapsMsg);
            }

            foreach (var notification in selectableOverlaps.Notifications)
            {
                result.Notifications.Add(notification.Message);
            }

            _msg.DebugStopTiming(watch, "Packed overlaps into response");

            return(result);
        }
示例#22
0
        public void TestIsLineHorizontal2()
        {
            bool horizontal = GeometryUtils.IsLineHorizontal(12.8, 9.73, -12.8, 9.73);

            Assert.AreEqual(true, horizontal);
        }
        /// <inheritdoc />
        public override void GetGripPoints(
            Entity entity, GripDataCollection grips, double curViewUnitSize, int gripSize, Vector3d curViewDir, GetGripPointsFlags bitFlags)
        {
            try
            {
                if (IsApplicable(entity))
                {
                    // Удаляю все ручки - это удалит ручку вставки блока
                    grips.Clear();

                    var section = EntityReaderService.Instance.GetFromEntity <Section>(entity);
                    if (section != null)
                    {
                        // insertion (start) grip
                        var vertexGrip = new SectionVertexGrip(section, 0)
                        {
                            GripPoint = section.InsertionPoint
                        };
                        grips.Add(vertexGrip);

                        // middle points
                        for (var index = 0; index < section.MiddlePoints.Count; index++)
                        {
                            vertexGrip = new SectionVertexGrip(section, index + 1)
                            {
                                GripPoint = section.MiddlePoints[index]
                            };
                            grips.Add(vertexGrip);

                            var removeVertexGrip = new SectionRemoveVertexGrip(section, index + 1)
                            {
                                GripPoint = section.MiddlePoints[index] - (Vector3d.YAxis * 20 * curViewUnitSize)
                            };
                            grips.Add(removeVertexGrip);
                        }

                        // end point
                        vertexGrip = new SectionVertexGrip(section, section.MiddlePoints.Count + 1)
                        {
                            GripPoint = section.EndPoint
                        };
                        grips.Add(vertexGrip);

                        #region AddVertex grips

                        // add vertex grips
                        for (var i = 0; i < section.MiddlePoints.Count; i++)
                        {
                            if (i == 0)
                            {
                                var addVertexGrip = new SectionAddVertexGrip(
                                    section,
                                    section.InsertionPoint, section.MiddlePoints[i])
                                {
                                    GripPoint = GeometryUtils.GetMiddlePoint3d(section.InsertionPoint, section.MiddlePoints[i])
                                };
                                grips.Add(addVertexGrip);
                            }
                            else
                            {
                                var addVertexGrip = new SectionAddVertexGrip(
                                    section,
                                    section.MiddlePoints[i - 1], section.MiddlePoints[i])
                                {
                                    GripPoint = GeometryUtils.GetMiddlePoint3d(section.MiddlePoints[i - 1], section.MiddlePoints[i])
                                };
                                grips.Add(addVertexGrip);
                            }

                            // last segment
                            if (i == section.MiddlePoints.Count - 1)
                            {
                                var addVertexGrip = new SectionAddVertexGrip(
                                    section,
                                    section.MiddlePoints[i], section.EndPoint)
                                {
                                    GripPoint = GeometryUtils.GetMiddlePoint3d(section.MiddlePoints[i], section.EndPoint)
                                };
                                grips.Add(addVertexGrip);
                            }
                        }

                        if (!section.MiddlePoints.Any())
                        {
                            var addVertexGrip = new SectionAddVertexGrip(section, section.InsertionPoint, section.EndPoint)
                            {
                                GripPoint = GeometryUtils.GetMiddlePoint3d(section.InsertionPoint, section.EndPoint)
                            };
                            grips.Add(addVertexGrip);
                        }

                        #endregion

                        #region Reverse Grips

                        var reverseGrip = new SectionReverseGrip(section)
                        {
                            GripPoint = section.EntityDirection == EntityDirection.LeftToRight
                                ? section.TopShelfEndPoint - (Vector3d.XAxis * 20 * curViewUnitSize)
                                : section.TopShelfEndPoint + (Vector3d.XAxis * 20 * curViewUnitSize)
                        };
                        grips.Add(reverseGrip);
                        reverseGrip = new SectionReverseGrip(section)
                        {
                            GripPoint = section.EntityDirection == EntityDirection.LeftToRight
                                ? section.BottomShelfEndPoint - (Vector3d.XAxis * 20 * curViewUnitSize)
                                : section.BottomShelfEndPoint + (Vector3d.XAxis * 20 * curViewUnitSize)
                        };
                        grips.Add(reverseGrip);

                        #endregion

                        #region Text grips

                        if (section.TopDesignationPoint != Point3d.Origin && section.HasTextValue())
                        {
                            var textGrip = new SectionTextGrip(section)
                            {
                                GripPoint = section.TopDesignationPoint,
                                Name      = TextGripName.TopText
                            };
                            grips.Add(textGrip);
                        }

                        if (section.BottomDesignationPoint != Point3d.Origin && section.HasTextValue())
                        {
                            var textGrip = new SectionTextGrip(section)
                            {
                                GripPoint = section.BottomDesignationPoint,
                                Name      = TextGripName.BottomText
                            };
                            grips.Add(textGrip);
                        }

                        #endregion
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception.ErrorStatus != ErrorStatus.NotAllowedForThisProxy)
                {
                    ExceptionBox.Show(exception);
                }
            }
        }
示例#24
0
 public void TestIsLineVertical1_ThrowsException()
 {
     bool vertical = GeometryUtils.IsLineVertical(12.8, 9.73, 12.8, 9.73);
 }
示例#25
0
        public void MouseMove(Vector p)
        {
            CurrentPos = p;
            if (Moving)
            {
                AdjustForGrid(p);
                if (_lockingLines)
                {
                    p = GeometryUtils.OrthogonalProjection(_lockCenter,
                                                           GeometryUtils.DistanceFromLine(_lockCenter, _lockNext, p) <
                                                           GeometryUtils.DistanceFromLine(_lockCenter, _lockPrev, p)
                            ? _lockNext
                            : _lockPrev, p);
                }

                Vector delta = p - _moveStartPosition;
                if (delta.Length > 0)
                {
                    _anythingMoved = true;
                }
                Vector.MarkDefault = VectorMark.Selected;
                foreach (Polygon x in Lev.Polygons)
                {
                    bool anythingMoved = false;
                    for (int i = 0; i < x.Vertices.Count; i++)
                    {
                        if (x.Vertices[i].Mark != VectorMark.Selected)
                        {
                            continue;
                        }
                        x.Vertices[i] += delta;
                        anythingMoved  = true;
                    }

                    if (anythingMoved)
                    {
                        x.UpdateDecomposition();
                    }
                }

                foreach (LevObject x in Lev.Objects.Where(x => x.Position.Mark == VectorMark.Selected))
                {
                    x.Position += delta;
                }

                foreach (Picture z in Lev.Pictures.Where(z => z.Position.Mark == VectorMark.Selected))
                {
                    z.Position += delta;
                }

                Vector.MarkDefault = VectorMark.None;
                _moveStartPosition = p;
            }
            else if (FreeSelecting)
            {
                _mouseTrip        += (p - _lastMousePosition).Length;
                _lastMousePosition = p;
                double step = 0.02 * ZoomCtrl.ZoomLevel;
                if (_mouseTrip > step)
                {
                    while (!(_mouseTrip < step))
                    {
                        _mouseTrip -= step;
                    }
                    _selectionPoly.Add(p);
                }
            }
            else if (!Busy)
            {
                ResetHighlight();
                int nearestVertex       = GetNearestVertexIndex(p);
                int nearestObject       = GetNearestObjectIndex(p);
                int nearestTextureIndex = GetNearestPictureIndex(p);
                if (nearestVertex == -1)
                {
                    ChangeCursorToHand();
                    NearestPolygon.Mark            = PolygonMark.Highlight;
                    LevEditor.HighlightLabel.Text  = NearestPolygon.IsGrass ? "Grass" : "Ground";
                    LevEditor.HighlightLabel.Text += " polygon, " + NearestPolygon.Count + " vertices";
                }
                else if (nearestVertex >= 0)
                {
                    ChangeCursorToHand();
                    Vector b = NearestPolygon.Vertices[nearestVertex];
                    if (b.Mark == VectorMark.None)
                    {
                        b.Mark = VectorMark.Highlight;
                    }
                    LevEditor.HighlightLabel.Text  = NearestPolygon.IsGrass ? "Grass" : "Ground";
                    LevEditor.HighlightLabel.Text += " polygon, vertex " + (nearestVertex + 1) + " of " +
                                                     NearestPolygon.Count + " vertices";
                }
                else if (nearestObject >= 0)
                {
                    ChangeCursorToHand();
                    if (Lev.Objects[nearestObject].Position.Mark == VectorMark.None)
                    {
                        Lev.Objects[nearestObject].Position.Mark = VectorMark.Highlight;
                    }
                    ShowObjectInfo(nearestObject);
                }
                else if (nearestTextureIndex >= 0)
                {
                    ChangeCursorToHand();
                    if (Lev.Pictures[nearestTextureIndex].Position.Mark == VectorMark.None)
                    {
                        Lev.Pictures[nearestTextureIndex].Position.Mark = VectorMark.Highlight;
                    }
                    ShowTextureInfo(nearestTextureIndex);
                }
                else
                {
                    ChangeToDefaultCursorIfHand();
                    LevEditor.HighlightLabel.Text = "";
                }
            }
        }
示例#26
0
        public void TestIsLineVertical2()
        {
            bool vertical = GeometryUtils.IsLineVertical(12.8, -9.73, 12.8, 9.73);

            Assert.AreEqual(true, vertical);
        }
示例#27
0
        private int CheckIntersection([NotNull] IPoint intersectionPoint,
                                      [NotNull] IFeature feature1, int tableIndex1,
                                      [NotNull] IFeature feature2, int tableIndex2)
        {
            double feature1Z = intersectionPoint.Z;

            if (double.IsNaN(feature1Z))
            {
                return(NoError);
            }

            double feature2Z = GeometryUtils.GetZValueFromGeometry(
                feature2.Shape, intersectionPoint,
                GeometryUtils.GetXyTolerance(feature2));

            if (double.IsNaN(feature2Z))
            {
                return(NoError);
            }

            double dz = Math.Abs(feature1Z - feature2Z);

            double minimumZDifference =
                feature1Z >= feature2Z
                                        ? GetMinimumZDifference(feature1, tableIndex1,
                                                                feature2, tableIndex2)
                                        : GetMinimumZDifference(feature2, tableIndex2,
                                                                feature1, tableIndex1);

            double maximumZDifference =
                feature1Z >= feature2Z
                                        ? GetMaximumZDifference(feature1, tableIndex1,
                                                                feature2, tableIndex2)
                                        : GetMaximumZDifference(feature2, tableIndex2,
                                                                feature1, tableIndex1);

            int errorCount = 0;

            if (minimumZDifference > 0 && dz < minimumZDifference)
            {
                // a z difference smaller than the minimum is always an error
                errorCount += ReportIssue(
                    $"Z distance is {dz:N2}. Minimum allowed distance is {minimumZDifference}",
                    intersectionPoint,
                    Codes[Code.ZDifferenceAtLineIntersection_SmallerThanLimit],
                    TestUtils.GetShapeFieldName(feature1),
                    dz, feature1, feature2);
            }

            if (maximumZDifference > 0 && dz > maximumZDifference)
            {
                // a z difference larger than the maximum is always an error
                errorCount += ReportIssue(
                    $"Z distance is {dz:N2}. Maximum allowed distance is {maximumZDifference}",
                    intersectionPoint,
                    Codes[Code.ZDifferenceAtLineIntersection_LargerThanLimit],
                    TestUtils.GetShapeFieldName(feature1),
                    dz, feature1, feature2);
            }

            return(errorCount +
                   (feature1Z >= feature2Z
                                        ? CheckConstraint(feature1, tableIndex1,
                                                          feature2, tableIndex2,
                                                          intersectionPoint, dz)
                                        : CheckConstraint(feature2, tableIndex2,
                                                          feature1, tableIndex1,
                                                          intersectionPoint, dz)));
        }
示例#28
0
 public void TestCalcTriangleArea2_ThrowsException()
 {
     double area = GeometryUtils.CalcTriangleArea(0, 40, 50);
 }
示例#29
0
        private void selectGameObjects(Rect selectionRect)
        {
            // Is Deselection Mode?
            if (SimulationGame.KeyboardState.IsKeyDown(Keys.LeftAlt) || SimulationGame.KeyboardState.IsKeyDown(Keys.RightAlt))
            {
                if (SimulationGame.Player.InteriorID == Interior.Outside)
                {
                    // Check collision with interactive && contained objects
                    Point chunkTopLeft     = GeometryUtils.GetChunkPosition(selectionRect.Left, selectionRect.Top, WorldGrid.WorldChunkPixelSize.X, WorldGrid.WorldChunkPixelSize.Y);
                    Point chunkBottomRight = GeometryUtils.GetChunkPosition(selectionRect.Right, selectionRect.Bottom, WorldGrid.WorldChunkPixelSize.X, WorldGrid.WorldChunkPixelSize.Y);

                    for (int chunkX = chunkTopLeft.X - 1; chunkX <= chunkBottomRight.X + 1; chunkX++)
                    {
                        for (int chunkY = chunkTopLeft.Y - 1; chunkY <= chunkBottomRight.Y + 1; chunkY++)
                        {
                            WorldGridChunk worldGridChunk = SimulationGame.World.GetFromChunkPoint(chunkX, chunkY);

                            addSelectedObjectsFromWorldPart(selectionRect, worldGridChunk, true);
                        }
                    }
                }
                else
                {
                    addSelectedObjectsFromWorldPart(selectionRect, SimulationGame.World.InteriorManager.Get(SimulationGame.Player.InteriorID), true);
                }

                if (SelectedGameObjects.Count > 0)
                {
                    gameObjectSelection?.Invoke(SelectedGameObjects);
                }
            }
            else
            {
                if (SimulationGame.KeyboardState.IsKeyDown(Keys.LeftShift) == false && SimulationGame.KeyboardState.IsKeyDown(Keys.RightShift) == false)
                {
                    SelectedBlockPosition = Point.Zero;
                    SelectedBlockType     = null;
                    SelectedWorldLink     = null;
                    SelectedGameObjects.Clear();
                }

                if (SimulationGame.Player.InteriorID == Interior.Outside)
                {
                    // Check collision with interactive && contained objects
                    Point chunkTopLeft     = GeometryUtils.GetChunkPosition(selectionRect.Left, selectionRect.Top, WorldGrid.WorldChunkPixelSize.X, WorldGrid.WorldChunkPixelSize.Y);
                    Point chunkBottomRight = GeometryUtils.GetChunkPosition(selectionRect.Right, selectionRect.Bottom, WorldGrid.WorldChunkPixelSize.X, WorldGrid.WorldChunkPixelSize.Y);

                    for (int chunkX = chunkTopLeft.X - 1; chunkX <= chunkBottomRight.X + 1; chunkX++)
                    {
                        for (int chunkY = chunkTopLeft.Y - 1; chunkY <= chunkBottomRight.Y + 1; chunkY++)
                        {
                            WorldGridChunk worldGridChunk = SimulationGame.World.GetFromChunkPoint(chunkX, chunkY);

                            addSelectedObjectsFromWorldPart(selectionRect, worldGridChunk);
                        }
                    }
                }
                else
                {
                    addSelectedObjectsFromWorldPart(selectionRect, SimulationGame.World.InteriorManager.Get(SimulationGame.Player.InteriorID));
                }

                if (SelectedGameObjects.Count == 0)
                {
                    WorldPart worldPart = (SimulationGame.Player.InteriorID == Interior.Outside) ? SimulationGame.World.GetFromRealPoint((int)selectionRect.X, (int)selectionRect.Y) : (WorldPart)SimulationGame.World.InteriorManager.Get(SimulationGame.Player.InteriorID);

                    if (worldPart.WorldLinks != null)
                    {
                        foreach (var worldLinkItem in worldPart.WorldLinks)
                        {
                            Rect renderPosition = new Rect(worldLinkItem.Value.FromBlock.X * WorldGrid.BlockSize.X, worldLinkItem.Value.FromBlock.Y * WorldGrid.BlockSize.Y, WorldGrid.BlockSize.X, WorldGrid.BlockSize.Y);

                            if (renderPosition.Contains(selectionRect.GetPosition()))
                            {
                                SelectedWorldLink = worldLinkItem.Value;
                                worldLinkSelection?.Invoke(SelectedWorldLink);

                                return;
                            }
                        }
                    }

                    // We get the block
                    SelectedBlockPosition = GeometryUtils.GetBlockFromReal((int)SimulationGame.RealWorldMousePosition.X, (int)SimulationGame.RealWorldMousePosition.Y);
                    SelectedBlockType     = BlockType.lookup[SimulationGame.World.GetBlockType(SelectedBlockPosition.X, SelectedBlockPosition.Y, SimulationGame.Player.InteriorID)];

                    blockSelection?.Invoke(SelectedBlockType);
                }
                else
                {
                    gameObjectSelection?.Invoke(SelectedGameObjects);
                }
            }
        }
        private static void RunTest(Stream stream, double minimumMeasure)
        {
            var geoms = GeometryUtils.ReadWKTFile(stream);

            Assert.IsTrue(Tester.Test(geoms, minimumMeasure));
        }