/// <summary>
 /// Perform the 'get' operation.
 /// </summary>
 /// <param name="line"></param>
 /// <returns></returns>
 public Commands.Result Get(out Geometry.Line line)
 {
   IntPtr ptr_this = NonConstPointer();
   line = Geometry.Line.Unset;
   int rc = UnsafeNativeMethods.RHC_RhinoGetLine2(ptr_this, ref line, IntPtr.Zero);
   return (Commands.Result)rc;
 }
Example #2
0
        /// <summary>
        /// Slices a polygon by a circle with some thickness.
        /// Input circle may be a line.
        /// </summary>
        /// <remarks>The input polygon might get reversed</remarks>
        public static void SlicePolygon( Polygon p, CircleNE c, Geometry g, double thickness, out List<Polygon> output )
        {
            output = new List<Polygon>();

            // Setup the two slicing circles.
            CircleNE c1 = c.Clone(), c2 = c.Clone();
            Mobius m = new Mobius();
            Vector3D pointOnCircle = c.IsLine ? c.P1 : c.Center + new Vector3D( c.Radius, 0 );
            m.Hyperbolic2( g, c1.CenterNE, pointOnCircle, thickness / 2 );
            c1.Transform( m );
            m.Hyperbolic2( g, c2.CenterNE, pointOnCircle, -thickness / 2 );
            c2.Transform( m );

            // ZZZ - alter Clip method to work on Polygons and use that.

            // Slice it up.
            List<Polygon> sliced1, sliced2;
            Slicer.SlicePolygon( p, c1, out sliced1 );
            Slicer.SlicePolygon( p, c2, out sliced2 );

            // Keep the ones we want.
            foreach( Polygon newPoly in sliced1 )
            {
                bool outside = !c1.IsPointInsideNE( newPoly.CentroidApprox );
                if( outside )
                    output.Add( newPoly );
            }

            foreach( Polygon newPoly in sliced2 )
            {
                bool inside = c2.IsPointInsideNE( newPoly.CentroidApprox );
                if( inside )
                    output.Add( newPoly );
            }
        }
Example #3
0
 /// <summary>
 /// Returns the underlying non-const ON_Geometry* for a RhinoCommon class. You should
 /// only be interested in using this function if you are writing C++ code.
 /// </summary>
 /// <param name="geometry">A geometry object. This can be null and in such a case <see cref="IntPtr.Zero"/> is returned.</param>
 /// <returns>A pointer to the non-const geometry.</returns>
 public static IntPtr NativeGeometryNonConstPointer(Geometry.GeometryBase geometry)
 {
   IntPtr rc = IntPtr.Zero;
   if (geometry != null)
     rc = geometry.NonConstPointer();
   return rc;
 }
Example #4
0
        public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters)
        {
            DiskParameters vmdkParams = new DiskParameters();
            vmdkParams.Capacity = capacity;
            vmdkParams.Geometry = geometry;

            switch (variant)
            {
                case "fixed":
                    vmdkParams.CreateType = DiskCreateType.MonolithicFlat;
                    break;
                case "dynamic":
                    vmdkParams.CreateType = DiskCreateType.MonolithicSparse;
                    break;
                case "vmfsfixed":
                    vmdkParams.CreateType = DiskCreateType.Vmfs;
                    break;
                case "vmfsdynamic":
                    vmdkParams.CreateType = DiskCreateType.VmfsSparse;
                    break;
                default:
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown VMDK disk variant '{0}'", variant), "variant");
            }

            return Disk.Initialize(locator, path, vmdkParams);
        }
Example #5
0
 /// <summary>
 /// Creates a new empty model.
 /// </summary>
 public Model(Matrix transform)
 {
     Enabled = true;
     this.transform = transform;
     inverseTranspose = Matrix.InverseTranspose(transform);
     geometry = new Geometry(SceneFlags.Static | SceneFlags.HighQuality, TraversalFlags.Single | TraversalFlags.Packet4);
 }
 private static bool WallCollision(Geometry.Circle2D c, double objectZ, double objectHeight, Wall wall)
 {
     if (Geometry.Intersections.CirclePolygonIntersection(c,
            wall.Area))
         return true;
     return false;
 }
Example #7
0
        public void SetGeometry(Geometry converted)
        {
            if (converted == null)
                throw new ArgumentNullException("converted");

            this.Geometry = converted;
        }
Example #8
0
 public static Geometry SymDifference(Geometry g1, Geometry g2)
 {
     SqlGeometry sg1 = SqlGeometryConverter.ToSqlGeometry(g1);
     SqlGeometry sg2 = SqlGeometryConverter.ToSqlGeometry(g2);
     SqlGeometry sgSymDifference = sg1.STSymDifference(sg2);
     return SqlGeometryConverter.ToSharpMapGeometry(sgSymDifference);
 }
Example #9
0
        public void ParseGeometryLibrary_GeometryMesh(XmlNode MeshNode, Geometry CurrentGeometry)
        {
            Console.WriteLine("Entered MeshNode");

            Mesh CurrentMesh = new Mesh();

            for (int i = 0; i < MeshNode.ChildNodes.Count; i++)
            {
                if (MeshNode.ChildNodes[i].Name.Equals("source"))
                {
                    ParseGeometryLibrary_GeometryMeshSource(MeshNode.ChildNodes[i], CurrentMesh);
                }

                if (MeshNode.ChildNodes[i].Name.Equals("vertices"))
                {
                    ParseGeometryLibrary_GeometryMeshVertices(MeshNode.ChildNodes[i], CurrentMesh);
                }

                if (MeshNode.ChildNodes[i].Name.Equals("triangles"))
                {
                    ParseGeometryLibrary_GeometryMeshTriangles(MeshNode.ChildNodes[i], CurrentMesh);
                }
            }

            CurrentGeometry.mMeshes.Add(CurrentMesh);
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="nginz.Model"/> class.
 /// </summary>
 /// <param name="geometry">Geometry.</param>
 public Model(Geometry geometry)
 {
     Geometry = geometry;
     Position = Vector3.Zero;
     Scale = Vector3.One;
     Rotation = Vector3.Zero;
 }
Example #11
0
 public static Geometry Intersection(Geometry g1, Geometry g2)
 {
     SqlGeometry sg1 = SqlGeometryConverter.ToSqlGeometry(g1);
     SqlGeometry sg2 = SqlGeometryConverter.ToSqlGeometry(g2);
     SqlGeometry sgIntersection = sg1.STIntersection(sg2);
     return SqlGeometryConverter.ToSharpMapGeometry(sgIntersection);
 }
Example #12
0
 public GeographyContains(Geometry ContainingObject, Geometry ContainedObject)
 {
     this.ContainingObject = ContainingObject;
     this.ContainingObjectType = ValueObjectType.Value;
     this.ContainedObject = ContainedObject;
     this.ContainedObjectType = ValueObjectType.Value;
 }
Example #13
0
        public void RemoveVertex(Geometry.Point vertex)
        {
            int indexToRemove;
            for (indexToRemove = 0; indexToRemove < _vertices.Count; ++indexToRemove)
            {
                if(_vertices[indexToRemove].Equals(vertex))
                    break;
            }
            if (indexToRemove == _vertices.Count)
                return;

            ++_holeCount;
            if (_vertices.Count == 1)
            {
                _vertices.RemoveAt(indexToRemove);
                return;
            }

            if (_vertices.Count <= 2)
            {
                HandleVertexRemovalTwoPoint(indexToRemove);
                return;
            }

            //TODO: Find new vertices that will emerge from removing the vertex
            //TODO: preserve the cyclical ordering of the vertices to aid in area calculation.
        }
Example #14
0
        private Display(Surface surface, Color[][] colors)
        {
            geometry = surface;

            // Transpose the colors array. This is required
            // to correctly align the colors on the surface with
            // the UV space of the surface.

            var rows = colors.GetLength(0);
            var columns = colors[0].Count();

            colorMap = new Color[columns][];
            for (var c = 0; c < columns; c++)
            {
                colorMap[c] = new Color[rows];
            }

            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < columns; j++)
                {
                    colorMap[j][i] = colors[i][j];
                }
            } 
        }
Example #15
0
 /// <summary>
 /// 拷贝构造函数。
 /// </summary>
 /// <param name="geometry">几何对象。</param>
 /// <exception cref="ArgumentNullException">几何对象为 null 时抛出异常。</exception>
 public Geometry(Geometry geometry)
 {
     if (geometry == null) throw new ArgumentNullException();
     this.Id = geometry.Id;
     if (geometry.Parts != null)
     {
         int length = geometry.Parts.Length;
         this.Parts = new int[length];
         for (int i = 0; i < length; i++)
         {
             this.Parts[i] = geometry.Parts[i];
         }
     }
     if (geometry.Points != null)
     {
         int length = geometry.Points.Length;
         this.Points = new Point2D[length];
         for (int i = 0; i < length; i++)
         {
             this.Points[i] = new Point2D(geometry.Points[i]);
         }
     }
     if (Style != null)
     {
         this.Style = new Style(geometry.Style);
     }
     this.Type = geometry.Type;
 }
Example #16
0
        public Tile( Polygon boundary, Polygon drawn, Geometry geometry )
            : this()
        {
            Boundary = boundary;
            Drawn = drawn;
            Geometry = geometry;

            // Make the vertex circle.
            VertexCircle = boundary.CircumCircle;

            // ZZZ - we shouldn't do this here (I did it for the slicing study page).
            //VertexCircle.Radius = 1.0;

            //
            // Below are experimentations with different vertex circle sizes.
            //

            //VertexCircle.Radius *= (1+1.0/9);

            // cuts adjacent cells at midpoint
            // Math.Sqrt(63)/6 for {3,6}
            // (1 + 1.0/5) for {3,7}
            // (1 + 1.0/9) for {3,8}
            // (1 + 1.0/20) for {3,9}

            // cuts at 1/3rd
            // 2/Math.Sqrt(3) for {3,6}
        }
        private async Task DoGeodesicLength()
        {
            ResetButton.IsEnabled = false;

            try
            {
                if (mapView1.Editor.IsActive)
                    mapView1.Editor.Cancel.Execute(null);

                //Get the input polygon geometry from the user
                inputGeom = await mapView1.Editor.RequestShapeAsync(DrawShape.Polyline);

                if (inputGeom != null)
                {
                    //Add the polygon drawn by the user
                    var g = new Graphic
                    {
                        Geometry = inputGeom,
                    };
                    myGraphicsLayer.Graphics.Add(g);


                    //Get the label point for the input geometry
                    var length = GeometryEngine.GeodesicLength(inputGeom);
                    LineLengthTextBlock.Text = length.ToString("N2") + " m";
                    LineLengthTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
            }
            catch (Exception)
            {

            }
            ResetButton.IsEnabled = true;

        }
        internal static BiosParameterBlock Initialized(Geometry diskGeometry, int clusterSize, uint partitionStartLba, long partitionSizeLba, int mftRecordSize, int indexBufferSize)
        {
            BiosParameterBlock bpb = new BiosParameterBlock();
            bpb.OemId = "NTFS    ";
            bpb.BytesPerSector = Sizes.Sector;
            bpb.SectorsPerCluster = (byte)(clusterSize / bpb.BytesPerSector);
            bpb.ReservedSectors = 0;
            bpb.NumFats = 0;
            bpb.FatRootEntriesCount = 0;
            bpb.TotalSectors16 = 0;
            bpb.Media = 0xF8;
            bpb.FatSize16 = 0;
            bpb.SectorsPerTrack = (ushort)diskGeometry.SectorsPerTrack;
            bpb.NumHeads = (ushort)diskGeometry.HeadsPerCylinder;
            bpb.HiddenSectors = partitionStartLba;
            bpb.TotalSectors32 = 0;
            bpb.BiosDriveNumber = 0x80;
            bpb.ChkDskFlags = 0;
            bpb.SignatureByte = 0x80;
            bpb.PaddingByte = 0;
            bpb.TotalSectors64 = partitionSizeLba - 1;
            bpb.RawMftRecordSize = bpb.CodeRecordSize(mftRecordSize);
            bpb.RawIndexBufferSize = bpb.CodeRecordSize(indexBufferSize);
            bpb.VolumeSerialNumber = GenSerialNumber();

            return bpb;
        }
Example #19
0
        Geometry.Figures.Point target; //точка цели

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Конструктор текущего действия (движения)
        /// </summary>
        /// <param name="a">Действие</param>
        /// <param name="curPoint">Текущее положение отряда</param>
        public OrderPresenter(AbstractGameEngine.Action a, Geometry.Figures.Point curPoint)
        {
            double ratio = Transformer.Ratio;
            this.origin = curPoint;
            this.target = (a as GameEngine.Characters.MoveAction).Destination;
            OrderOrigin = new Point(curPoint.X * ratio, curPoint.Y * ratio);
            OrderTarget = new Point(target.X * ratio, target.Y * ratio);
            this.OrderType = 0;

            VisibleWayAim = Visibility.Visible;
            this.TurnsToComplete = (a as GameEngine.Characters.MoveAction).TurnsToComplete;

            double dX=0;//смещение значка цели перемещения относительно положения отряда по оси X
            double dY=0;//смещение значка цели перемещения относительно положения отряда по оси Y

            if ((target.X - origin.X) < 0) dX = 2 * (target.X - origin.X) * ratio;//если отряд двигается влево
            else dX = (target.X - origin.X) * ratio - 12.5;//если отряд двигается вправо
            if ((origin.Y - target.Y) < 0) dY = 2 * (origin.Y - target.Y) * ratio;//если отряд двигается вверх
            else dY = (origin.Y - target.Y) * ratio - 12.5;//если отряд двигается вниз
            this.Margin = new Thickness(dX, dY, 0, 0);

            DeltaHorisontal = (target.X - origin.X) * ratio;
            DeltaVertical = (origin.Y - target.Y) * ratio;

            this.WayLine = new System.Windows.Media.PointCollection();
            Point aimPos = new Point(dX, dY);//получение точки цели перемещения отряда
            this.WayLine.Add(new Point(0, 0));//точка нахождения отряда относительно отряда
            this.WayLine.Add(new Point((target.X - origin.X) * ratio, (origin.Y - target.Y) * ratio));
        }
        public static string CoordinatesConvertor(double InputX,double InputY, int InputWKID, int OutputWKID)
        {
            Geometry_GeometryServer geometryService = new Geometry_GeometryServer();

            SpatialReference inputSpatialReference = new GeographicCoordinateSystem();

            inputSpatialReference.WKID = InputWKID;

            inputSpatialReference.WKIDSpecified = true;

            SpatialReference outputSpatialReference = new ProjectedCoordinateSystem();

            outputSpatialReference.WKID = OutputWKID;

            outputSpatialReference.WKIDSpecified = true;

            PointN pt = new PointN();
            pt.X = InputX;
            pt.Y = InputY;

            Geometry[] inGeo = new Geometry[] { pt };

            Geometry[] geo = geometryService.Project(inputSpatialReference, outputSpatialReference, false, null, null, inGeo);
            PointN nPt = (PointN)geo[0];

            return (nPt.X.ToString() + ',' + nPt.Y.ToString());
        }
Example #21
0
 public GeographyContains(Geometry outerValue, Geometry innerValue)
 {
     this.OuterValue = outerValue;
     this.OuterValueType = ValueObjectType.Value;
     this.InnerValue = innerValue;
     this.InnerValueType = ValueObjectType.Value;
 }
Example #22
0
 public virtual void Create(int x, int y, Geometry geometry, Tile[] sides)
 {
     geometry.CreateFace(x, 0, y, Geometry.Direction.east);
     geometry.CreateFace(x, 0, y, Geometry.Direction.west);
     geometry.CreateFace(x, 0, y, Geometry.Direction.up);
     geometry.CreateFace(x, 0, y, Geometry.Direction.down);
 }
        private async Task RunQuery(Geometry geometry)
        {
            var l = mapView1.Map.Layers["GraphicsWellsLayer"] as GraphicsLayer;
            l.Graphics.Clear();
            QueryTask queryTask =
                new QueryTask(new Uri("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSPetro/MapServer/0"));

            Query query = new Query("1=1")
             {
                 Geometry = geometry,
                 ReturnGeometry = true,
                 //OutSpatialReference = mapView1.SpatialReference,
                 OutFields = OutFields.All
             };
            try
            {
                var result = await queryTask.ExecuteAsync(query);
                if (result.FeatureSet.Features != null && result.FeatureSet.Features.Count > 0)
                {
                    ResultsGrid.ItemsSource = result.FeatureSet.Features;
                    l.Graphics.AddRange(from g in result.FeatureSet.Features select g);
                }
            }
            catch (Exception)
            {
            }
        }
Example #24
0
        public SatResult? FindIntersection(Geometry a, Geometry b)
        {
            var aAxes = a.GetAxes(b);
            var bAxes = b.GetAxes(a);
            var totalAxes = aAxes.Length + bAxes.Length;

            Vector2 normal = Vector2.Zero;
            Vector2 deepestPoint = Vector2.Zero;
            float smallestOverlap = float.MaxValue;

            for (int i = 0; i < totalAxes; i++)
            {
                Vector2 axis;
                if (i < aAxes.Length)
                    axis = aAxes[i];
                else
                    axis = bAxes[i - aAxes.Length];

                Vector2.Normalize(ref axis, out axis);

                var aProjection = a.Project(axis);
                var bProjection = b.Project(axis);

                float overlap;
                int order;
                if (!aProjection.Overlaps(bProjection, out overlap, out order))
                    return null;

                if (overlap < smallestOverlap)
                {
                    smallestOverlap = overlap;
                    normal = axis;

                    if (order < 0)
                        normal = -normal;

                    if (i < aAxes.Length)
                    {
                        if (order > 0) // if a is before b
                            deepestPoint = bProjection.StartPoint;
                        else
                            deepestPoint = bProjection.EndPoint;
                    }
                    else
                    {
                        if (order > 0)
                            deepestPoint = aProjection.EndPoint;
                        else
                            deepestPoint = aProjection.StartPoint;
                    }
                }
            }

            var axisMagnitude = normal.Length();
            normal /= axisMagnitude;
            smallestOverlap /= axisMagnitude;

            return new SatResult() { A = a, B = b, NormalAxis = normal, Penetration = smallestOverlap, DeepestPoint = deepestPoint };
        }
Example #25
0
 private static Geometry<EntityVertex> Gables(Geometry<EntityVertex> roof, out int tag)
 {
     var gableHeight = roof.BoundingBox.Size.Y * 0.85f;
     var frontGable = Triangle<EntityVertex>.Isosceles (2 * gableHeight, gableHeight);
     tag = frontGable.TagVertex (frontGable.Vertices.Furthest (Dir3D.Up).Single ());
     var backGable = frontGable.ReflectZ ().Translate (0f, 0f, -roof.BoundingBox.Size.Z * 0.9f);
     return Composite.Create (frontGable, backGable);
 }
Example #26
0
        public void DoQuery(Geometry geometry)
        {
            CancelBusyQueries();

            StartQuery(geometry, QueryType.PointsOfInterest);
            StartQuery(geometry, QueryType.EvacuationPerimeter);
            StartQuery(geometry, QueryType.FirePerimeter);
        }
Example #27
0
        public GeoJSON(Geometry geometry, IDictionary<string, object> values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            this.Geometry = geometry;
            this.Values = values;
        }
		/// <summary>
		/// Returns true if the intersection of the two geometries results in a geometry whose dimension is less than
		/// the maximum dimension of the two geometries and the intersection geometry is not equal to either.
		/// geometry.
		/// </summary>
		public static Boolean Crosses(Geometry g1, Geometry g2)
		{
			IGeometry g = g2.Intersection(g1);
		    Int32 maxDimension = Math.Max((Int32) g1.Dimension, (Int32) g2.Dimension);

            return ((Int32)g.Intersection(g1).Dimension < maxDimension 
                && !g.Equals(g1) && !g.Equals(g2));
		}
 public static CanvasPosition CanvasFromPlotter(Geometry.Position point, double zoomScale, CanvasPosition origin)
 {
     return new CanvasPosition
     {
         X = (point.X * zoomScale) + origin.X,
         Y = origin.Y - (point.Y * zoomScale)
     };
 }
Example #30
0
        public override Vector2[] GetAxes(Geometry otherObject)
        {
            axes[0] = otherObject.GetClosestVertex(transformedCentre) - transformedCentre;
            if (axes[0] == Vector2.Zero)
                axes[0] = Vector2.UnitY;

            return axes;
        }
        public static CanvasGeometry AsPath(this PathF path, float ox, float oy, float fx, float fy, ICanvasResourceCreator creator, CanvasFilledRegionDetermination fillMode = CanvasFilledRegionDetermination.Winding)
        {
            var builder = new CanvasPathBuilder(creator);

#if DEBUG
            try
            {
#endif
            builder.SetFilledRegionDetermination(fillMode);

            var pointIndex        = 0;
            var arcAngleIndex     = 0;
            var arcClockwiseIndex = 0;
            var figureOpen        = false;
            var segmentIndex      = -1;

            var lastOperation = PathOperation.Move;

            foreach (var type in path.SegmentTypes)
            {
                segmentIndex++;

                if (type == PathOperation.Move)
                {
                    if (lastOperation != PathOperation.Close && lastOperation != PathOperation.Move)
                    {
                        builder.EndFigure(CanvasFigureLoop.Open);
                    }

                    var point = path[pointIndex++];
                    var begin = CanvasFigureFill.Default;
                    builder.BeginFigure(ox + point.X * fx, oy + point.Y * fy, begin);
                    figureOpen = true;
                }
                else if (type == PathOperation.Line)
                {
                    var point = path[pointIndex++];
                    builder.AddLine(ox + point.X * fx, oy + point.Y * fy);
                }

                else if (type == PathOperation.Quad)
                {
                    var controlPoint = path[pointIndex++];
                    var endPoint     = path[pointIndex++];

                    builder.AddQuadraticBezier(
                        new Vector2(ox + controlPoint.X * fx, oy + controlPoint.Y * fy),
                        new Vector2(ox + endPoint.X * fx, oy + endPoint.Y * fy));
                }
                else if (type == PathOperation.Cubic)
                {
                    var controlPoint1 = path[pointIndex++];
                    var controlPoint2 = path[pointIndex++];
                    var endPoint      = path[pointIndex++];
                    builder.AddCubicBezier(
                        new Vector2(ox + controlPoint1.X * fx, oy + controlPoint1.Y * fy),
                        new Vector2(ox + controlPoint2.X * fx, oy + controlPoint2.Y * fy),
                        new Vector2(ox + endPoint.X * fx, oy + endPoint.Y * fy));
                }
                else if (type == PathOperation.Arc)
                {
                    var topLeft     = path[pointIndex++];
                    var bottomRight = path[pointIndex++];
                    var startAngle  = path.GetArcAngle(arcAngleIndex++);
                    var endAngle    = path.GetArcAngle(arcAngleIndex++);
                    var clockwise   = path.GetArcClockwise(arcClockwiseIndex++);

                    while (startAngle < 0)
                    {
                        startAngle += 360;
                    }

                    while (endAngle < 0)
                    {
                        endAngle += 360;
                    }

                    var rotation    = Geometry.GetSweep(startAngle, endAngle, clockwise);
                    var absRotation = Math.Abs(rotation);

                    var rectX      = ox + topLeft.X * fx;
                    var rectY      = oy + topLeft.Y * fy;
                    var rectWidth  = (ox + bottomRight.X * fx) - rectX;
                    var rectHeight = (oy + bottomRight.Y * fy) - rectY;

                    var startPoint = Geometry.OvalAngleToPoint(rectX, rectY, rectWidth, rectHeight, -startAngle);
                    var endPoint   = Geometry.OvalAngleToPoint(rectX, rectY, rectWidth, rectHeight, -endAngle);


                    if (!figureOpen)
                    {
                        var begin = CanvasFigureFill.Default;
                        builder.BeginFigure(startPoint.X, startPoint.Y, begin);
                        figureOpen = true;
                    }
                    else
                    {
                        builder.AddLine(startPoint.X, startPoint.Y);
                    }

                    builder.AddArc(
                        new Vector2(endPoint.X, endPoint.Y),
                        rectWidth / 2,
                        rectHeight / 2,
                        0,
                        clockwise ? CanvasSweepDirection.Clockwise : CanvasSweepDirection.CounterClockwise,
                        absRotation >= 180 ? CanvasArcSize.Large : CanvasArcSize.Small
                        );
                }
                else if (type == PathOperation.Close)
                {
                    builder.EndFigure(CanvasFigureLoop.Closed);
                }

                lastOperation = type;
            }

            if (segmentIndex >= 0 && lastOperation != PathOperation.Close)
            {
                builder.EndFigure(CanvasFigureLoop.Open);
            }

            var geometry = CanvasGeometry.CreatePath(builder);
            return(geometry);

#if DEBUG
        }

        catch (Exception exc)
        {
            builder.Dispose();

            var definition = path.ToDefinitionString();
            Logger.Debug(string.Format("Unable to convert the path to a Win2D Path: {0}", definition), exc);
            return(null);
        }
#endif
        }
Example #32
0
        public static Weapon Load(int modelId)
        {
            WeaponDef def = Item.GetDefinition <WeaponDef> (modelId);

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

            WeaponData weaponData = WeaponData.LoadedWeaponsData.FirstOrDefault(wd => wd.modelId1 == def.Id);

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

            var geoms = Geometry.Load(def.ModelName, def.TextureDictionaryName);

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

            if (null == s_weaponsContainer)
            {
                s_weaponsContainer = new GameObject("Weapons");
                //	weaponsContainer.SetActive (false);
            }

            GameObject go = new GameObject(def.ModelName);

            go.transform.SetParent(s_weaponsContainer.transform);

            geoms.AttachFrames(go.transform, MaterialFlags.Default);

            Weapon weapon = AddWeaponComponent(go, weaponData);

            weapon.definition = def;
            weapon.data       = weaponData;
            // cache gun aiming offset
            if (weapon.data.gunData != null)
            {
                weapon.gunAimingOffset = weapon.data.gunData.aimingOffset;
            }

            // load hud texture
            try {
                weapon.HudTexture = TextureDictionary.Load(def.TextureDictionaryName).GetDiffuse(def.TextureDictionaryName + "icon").Texture;
            } catch {
                Debug.LogErrorFormat("Failed to load hud icon for weapon: model {0}, txd {1}", def.ModelName, def.TextureDictionaryName);
            }

            // weapon sound
            F.RunExceptionSafe(() => {
                if (weaponSoundIndexes.ContainsKey(modelId))
                {
                    var audioSource         = go.GetOrAddComponent <AudioSource> ();
                    audioSource.playOnAwake = false;
                    Debug.LogFormat("loading weapon sound, bank index {0}", weaponSoundIndexes [modelId]);
                    var audioClip = Audio.AudioManager.CreateAudioClipFromSfx("GENRL", 136, 0,
                                                                              Audio.AudioManager.SfxGENRL137Timings[weaponSoundIndexes [modelId]]);
                    audioSource.clip     = audioClip;
                    weapon.m_audioSource = audioSource;
                }
            });

            return(weapon);
        }
        private void Initialize()
        {
            // Create a new map using the WebMercator spatial reference.
            Map newMap = new Map(SpatialReferences.WebMercator)
            {
                // Set the basemap of the map to be a topographic layer.
                Basemap = Basemap.CreateTopographic()
            };

            // Create a graphics overlay to hold the input geometries for the clip operation.
            _inputGeometriesGraphicsOverlay = new GraphicsOverlay();

            // Add the input geometries graphics overlay to the MapView.
            MyMapView.GraphicsOverlays.Add(_inputGeometriesGraphicsOverlay);

            // Create a graphics overlay to hold the resulting geometries from the three GeometryEngine.Clip operations.
            _clipAreasGraphicsOverlay = new GraphicsOverlay();

            // Add the resulting geometries graphics overlay to the MapView.
            MyMapView.GraphicsOverlays.Add(_clipAreasGraphicsOverlay);

            // Create a simple line symbol for the 1st parameter of the GeometryEngine.Clip operation - it follows the
            // boundary of Colorado.
            SimpleLineSymbol coloradoSimpleLineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, Colors.Blue, 4);

            // Create the color that will be used as the fill for the Colorado graphic. It will be a semi-transparent, blue color.
            Colors coloradoFillColor = Colors.FromArgb(34, 0, 0, 255);

            // Create the simple fill symbol for the Colorado graphic - comprised of a fill style, fill color and outline.
            SimpleFillSymbol coloradoSimpleFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, coloradoFillColor, coloradoSimpleLineSymbol);

            // Create the geometry of the Colorado graphic.
            Envelope colorado = new Envelope(
                new MapPoint(-11362327.128340, 5012861.290274, SpatialReferences.WebMercator),
                new MapPoint(-12138232.018408, 4441198.773776, SpatialReferences.WebMercator));

            // Create the graphic for Colorado - comprised of a polygon shape and fill symbol.
            _coloradoGraphic = new Graphic(colorado, coloradoSimpleFillSymbol);

            // Add the Colorado graphic to the input geometries graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_coloradoGraphic);

            // Create a simple line symbol for the three different clip geometries.
            SimpleLineSymbol clipGeomtriesSimpleLineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Dot, Colors.Red, 5);

            // Create an envelope outside Colorado.
            Envelope outsideEnvelope = new Envelope(
                new MapPoint(-11858344.321294, 5147942.225174, SpatialReferences.WebMercator),
                new MapPoint(-12201990.219681, 5297071.577304, SpatialReferences.WebMercator));

            // Create the graphic for an envelope outside Colorado - comprised of a polyline shape and line symbol.
            _outsideGraphic = new Graphic(outsideEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope outside Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_outsideGraphic);

            // Create an envelope intersecting Colorado.
            Envelope intersectingEnvelope = new Envelope(
                new MapPoint(-11962086.479298, 4566553.881363, SpatialReferences.WebMercator),
                new MapPoint(-12260345.183558, 4332053.378376, SpatialReferences.WebMercator));

            // Create the graphic for an envelope intersecting Colorado - comprised of a polyline shape and line symbol.
            _intersectingGraphic = new Graphic(intersectingEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope intersecting Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_intersectingGraphic);

            // Create a envelope inside Colorado.
            Envelope containedEnvelope = new Envelope(
                new MapPoint(-11655182.595204, 4741618.772994, SpatialReferences.WebMercator),
                new MapPoint(-11431488.567009, 4593570.068343, SpatialReferences.WebMercator));

            // Create the graphic for an envelope inside Colorado - comprised of a polyline shape and line symbol.
            _containedGraphic = new Graphic(containedEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope inside Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_containedGraphic);

            // Get the extent of all of the graphics in the graphics overlay with a little padding to used as the initial zoom extent of the map.
            Geometry visibleExtent = GetExtentOfGraphicsOverlay(_inputGeometriesGraphicsOverlay, 1.3, SpatialReferences.WebMercator);

            // Set the initial visual extent of the map view to the extent of the graphics overlay.
            newMap.InitialViewpoint = new Viewpoint(visibleExtent);

            // Assign the map to the MapView.
            MyMapView.Map = newMap;
        }
Example #34
0
        private CoursePage PdfNonScaledPage(CourseDesignator designator)
        {
            RectangleF pageArea = new RectangleF(0, 0, Geometry.HundredthsInchesFromMm(mapBounds.Width), Geometry.HundredthsInchesFromMm(mapBounds.Height));

            return(new CoursePage()
            {
                courseDesignator = designator,
                landscape = false,
                mapRectangle = mapBounds,
                printRectangle = pageArea,
                paperSize = new PaperSize("", (int)Math.Round(pageArea.Width), (int)Math.Round(pageArea.Height))
            });
        }
Example #35
0
        public void Push(Matrix transform, Geometry clip, double opacity, Brush opacityMask, Rect maskBounds, bool onePrimitive)
        {
            AssertState(DeviceState.PageStarted, DeviceState.NoChange);

            opacity = Utility.NormalizeOpacity(opacity);

            if (!Utility.IsValid(transform))
            {
                // treat as invisible subtree
                opacity   = 0.0;
                transform = Matrix.Identity;
            }

            _stack.Push(_root);
            _stack.Push(_clip);
            _stack.Push(_opacity);
            _stack.Push(_opacityMask);

            bool noTrans = transform.IsIdentity;

            if (onePrimitive && noTrans && (opacityMask == null))
            {
                bool empty;

                _clip        = Utility.Intersect(_clip, clip, Matrix.Identity, out empty);
                _opacity    *= opacity;
                _opacityMask = null;

                if (empty)
                {
                    _opacity = 0;
                }
            }
            else
            {
                CanvasPrimitive c = new CanvasPrimitive();

                if (noTrans)
                {
                    c.Transform = Matrix.Identity;
                }
                else
                {
                    c.Transform = transform;

                    Matrix invertTransform = transform;
                    invertTransform.Invert();

                    _clip = Utility.TransformGeometry(_clip, invertTransform); // transform inherited clip to this level
                }

                bool empty;

                c.Clip    = Utility.Intersect(clip, _clip, Matrix.Identity, out empty); // Combined with inherited attributes
                c.Opacity = opacity * _opacity;

                if (empty)
                {
                    c.Opacity = 0; // Invisible
                }

                if (opacityMask != null)
                {
                    double op;

                    if (Utility.ExtractOpacityMaskOpacity(opacityMask, out op, maskBounds))
                    {
                        c.Opacity = opacity * _opacity * op;
                    }
                    else
                    {
                        c.OpacityMask = BrushProxy.CreateOpacityMaskBrush(opacityMask, maskBounds);
                    }
                }

                _root.Children.Add(c);

                _root = c;

                _clip        = null;
                _opacity     = 1.0;
                _opacityMask = null;
            }
        }
Example #36
0
        public static List <Vector2> GetEvadePoints(int speed = -1, int delay = 0, bool onlyGood = false)
        {
            var goodCandidates     = new List <Vector2>();
            var badCandidates      = new List <Vector2>();
            var polygonList        = new List <Geometry.Polygon>();
            var takeClosestPath    = false;
            var detectedSkillshots = DetectedSkillshots.ToArray();

            foreach (var ally in bestAllies)
            {
                speed = speed == -1
                    ? (int)ally.MoveSpeed
                    : speed;


                foreach (var skillshot in detectedSkillshots)
                {
                    if (skillshot.Evade())
                    {
                        if (skillshot.SpellData.TakeClosestPath && skillshot.IsDanger(ally.Position.ToVector2()))
                        {
                            takeClosestPath = true;
                        }

                        polygonList.Add(skillshot.EvadePolygon);
                    }
                }

                var dangerPolygons = Geometry.ClipPolygons(polygonList).ToPolygons().ToArray();
                var myPosition     = ally.Position.ToVector2();

                foreach (var poly in dangerPolygons)
                {
                    for (var i = 0; i <= poly.Points.Count - 1; i++)
                    {
                        var sideStart            = poly.Points[i];
                        var sideEnd              = poly.Points[i == poly.Points.Count - 1 ? 0 : i + 1];
                        var originalCandidate    = myPosition.ProjectOn(sideStart, sideEnd).SegmentPoint;
                        var distanceToEvadePoint = Vector2.DistanceSquared(originalCandidate, myPosition);

                        if (distanceToEvadePoint < 600 * 600)
                        {
                            var sideDistance = Vector2.DistanceSquared(sideEnd, sideStart);
                            var direction    = (sideEnd - sideStart).Normalized();
                            var s            = distanceToEvadePoint < 200 * 200 && sideDistance > 90 * 90 ? 7 : 0;

                            for (var j = -s; j <= s; j++)
                            {
                                var candidate   = originalCandidate + j * 20 * direction;
                                var pathToPoint = ally.GetPath(candidate.ToVector3())
                                                  .To2DList();

                                if (IsSafePath(pathToPoint, 250, speed, delay).IsSafe)
                                {
                                    goodCandidates.Add(candidate);
                                }

                                if (IsSafePath(pathToPoint, 80, speed, delay).IsSafe&& j == 0)
                                {
                                    badCandidates.Add(candidate);
                                }
                            }
                        }
                    }
                }

                if (takeClosestPath)
                {
                    if (goodCandidates.Count > 0)
                    {
                        goodCandidates = new List <Vector2>
                        {
                            goodCandidates.MinOrDefault(vector2 => ally.Distance(vector2, true))
                        };
                    }

                    if (badCandidates.Count > 0)
                    {
                        badCandidates = new List <Vector2>
                        {
                            badCandidates.MinOrDefault(vector2 => ally.Distance(vector2, true))
                        };
                    }
                }
            }


            return(goodCandidates.Count > 0 ? goodCandidates : (onlyGood ? new List <Vector2>() : badCandidates));
        }
Example #37
0
        public override void RenderText(SvgTextContentElement element, ref Point ctp,
                                        string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            double emSize         = GetComputedFontSize(element);
            var    fontFamilyInfo = GetTextFontFamilyInfo(element);

            WpfTextStringFormat stringFormat = GetTextStringFormat(element);

            if (fontFamilyInfo.FontFamilyType == WpfFontFamilyType.Svg ||
                fontFamilyInfo.FontFamilyType == WpfFontFamilyType.Private)
            {
                WpfTextTuple textInfo = new WpfTextTuple(fontFamilyInfo, emSize, stringFormat, element);
                this.RenderText(textInfo, ref ctp, text, rotate, placement);
                return;
            }

            FontFamily  fontFamily  = fontFamilyInfo.Family;
            FontStyle   fontStyle   = fontFamilyInfo.Style;
            FontWeight  fontWeight  = fontFamilyInfo.Weight;
            FontStretch fontStretch = fontFamilyInfo.Stretch;

            // Fix the use of Postscript fonts...
            WpfFontFamilyVisitor fontFamilyVisitor = _context.FontFamilyVisitor;

            if (!string.IsNullOrWhiteSpace(_actualFontName) && fontFamilyVisitor != null)
            {
                WpfFontFamilyInfo familyInfo = fontFamilyVisitor.Visit(_actualFontName,
                                                                       fontFamilyInfo, _context);
                if (familyInfo != null && !familyInfo.IsEmpty)
                {
                    fontFamily  = familyInfo.Family;
                    fontWeight  = familyInfo.Weight;
                    fontStyle   = familyInfo.Style;
                    fontStretch = familyInfo.Stretch;
                }
            }

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            bool isForcedPathMode = false;

            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            else
            {
                // WPF gradient fill does not work well on text, use geometry to render it
                isForcedPathMode = (fillPaint.FillType == WpfFillType.Gradient);
            }
            if (textPen != null)
            {
                textPen.LineJoin = PenLineJoin.Round; // Better for text rendering
                isForcedPathMode = true;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);
            TextAlignment            alignment  = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            var typeFace = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            //bool isRightToLeft = false;
            //var xmlLang = _textElement.XmlLang;
            //if (!string.IsNullOrWhiteSpace(xmlLang))
            //{
            //    if (string.Equals(xmlLang, "ar", StringComparison.OrdinalIgnoreCase)      // Arabic language
            //        || string.Equals(xmlLang, "he", StringComparison.OrdinalIgnoreCase))  // Hebrew language
            //    {
            //        isRightToLeft = true;
            //    }
            //}

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                for (int i = 0; i < text.Length; i++)
                {
                    var nextText = new string(text[i], 1);

                    FormattedText formattedText = new FormattedText(nextText,
                                                                    _context.CultureInfo, stringFormat.Direction, typeFace, emSize, textBrush);
//#if NET40
//                    FormattedText formattedText = new FormattedText(nextText,
//                        _context.CultureInfo, stringFormat.Direction, typeFace, emSize, textBrush);
//#else
//                    FormattedText formattedText = new FormattedText(nextText, _context.CultureInfo,
//                        stringFormat.Direction, typeFace, emSize, textBrush, _context.PixelsPerDip);
//#endif
                    //                    formattedText.FlowDirection = isRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
                    formattedText.TextAlignment = stringFormat.Alignment;
                    formattedText.Trimming      = stringFormat.Trimming;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        formattedText.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && i < textPosCount)
                    {
                        textPosition = textPositions[i];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = formattedText.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(textStart.X, textStart.Y - yCorrection);

                    if (_context.TextAsGeometry || isForcedPathMode)
                    {
                        Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                        if (textGeometry != null && !textGeometry.IsEmpty())
                        {
                            _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));

                            this.IsTextPath = true;
                        }
                        else
                        {
                            _drawContext.DrawText(formattedText, textPoint);
                        }
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                }
            }
            else
            {
                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
                                                                stringFormat.Direction, typeFace, emSize, textBrush);
//#if NET40
//                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
//                    stringFormat.Direction, typeFace, emSize, textBrush);
//#else
//                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
//                    stringFormat.Direction, typeFace, emSize, textBrush, _context.PixelsPerDip);
//#endif

                formattedText.TextAlignment = stringFormat.Alignment;
                formattedText.Trimming      = stringFormat.Trimming;

//                formattedText.FlowDirection = isRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

                if (textDecors != null && textDecors.Count != 0)
                {
                    formattedText.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = formattedText.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                if (_context.TextAsGeometry || isForcedPathMode)
                {
                    Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }
                }
                else
                {
                    _drawContext.DrawText(formattedText, textPoint);
                }

                //float bboxWidth = (float)formattedText.Width;
                double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Example #38
0
        private void RenderTextRun(WpfTextTuple textInfo, ref Point ctp,
                                   string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            WpfFontFamilyInfo     familyInfo   = textInfo.Item1;
            double                emSize       = textInfo.Item2;
            WpfTextStringFormat   stringFormat = textInfo.Item3;
            SvgTextContentElement element      = textInfo.Item4;

            FontFamily  fontFamily  = familyInfo.Family;
            FontWeight  fontWeight  = familyInfo.Weight;
            FontStyle   fontStyle   = familyInfo.Style;
            FontStretch fontStretch = familyInfo.Stretch;

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            if (textPen != null)
            {
                textPen.LineJoin   = PenLineJoin.Miter; // Better for text rendering
                textPen.MiterLimit = 1;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);

            if (textDecors == null)
            {
                SvgTextBaseElement textElement = element.ParentNode as SvgTextBaseElement;

                if (textElement != null)
                {
                    textDecors = GetTextDecoration(textElement);
                }
            }

            TextAlignment alignment = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            WpfTextBuilder textBuilder = WpfTextBuilder.Create(familyInfo, this.TextCulture, emSize);

            this.IsTextPath = true;

            if (textPositions != null && textPositions.Count != 0)
            {
                if (textPositions.Count == text.Trim().Length) //TODO: Best way to handle this...
                {
                    text = text.Trim();
                }
            }

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                double spacing = Convert.ToDouble(letterSpacing);

                int startSpaces = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (char.IsWhiteSpace(text[i]))
                    {
                        startSpaces++;
                    }
                    else
                    {
                        break;
                    }
                }

                int j = 0;

                string inputText = string.Empty;
                for (int i = 0; i < text.Length; i++)
                {
                    // Avoid rendering only spaces at the start of text run...
                    if (i == 0 && startSpaces != 0)
                    {
                        inputText = text.Substring(0, startSpaces + 1);
                        i        += startSpaces;
                    }
                    else
                    {
                        inputText = new string(text[i], 1);
                    }

                    if (this.IsMeasuring)
                    {
                        var textSize = textBuilder.MeasureText(element, inputText);
                        this.AddTextWidth(ctp, textSize.Width);
                        continue;
                    }

                    textBuilder.Trimming      = stringFormat.Trimming;
                    textBuilder.TextAlignment = stringFormat.Alignment;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        textBuilder.TextDecorations = textDecors;
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && j < textPosCount)
                    {
                        textPosition = textPositions[j];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = textBuilder.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(ctp.X, ctp.Y - yCorrection);

                    Geometry textGeometry = textBuilder.Build(element, inputText, textPoint.X, textPoint.Y);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
//                        _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));
                        _drawContext.DrawGeometry(textBrush, textPen, textGeometry);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = textGeometry.Bounds.Width;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                    j++;
                }
            }
            else
            {
                if (this.IsMeasuring)
                {
                    var textSize = textBuilder.MeasureText(element, text);
                    this.AddTextWidth(ctp, textSize.Width);
                    return;
                }

                var textContext = this.TextContext;
                if (textContext != null && textContext.IsPositionChanged(element) == false)
                {
                    if (alignment == TextAlignment.Center && this.TextWidth > 0)
                    {
                        alignment = TextAlignment.Left;
                    }
                }

                textBuilder.TextAlignment = alignment;
                textBuilder.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    textBuilder.TextDecorations = textDecors;
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = textBuilder.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                Geometry textGeometry = textBuilder.Build(element, text, textPoint.X, textPoint.Y);
                if (textGeometry != null && !textGeometry.IsEmpty())
                {
//                    _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));
                    _drawContext.DrawGeometry(textBrush, textPen, textGeometry);
                }

                //float bboxWidth = (float)formattedText.Width;
                //                double bboxWidth = textGeometry.Bounds.Width;
                double bboxWidth = textBuilder.Width;

                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Example #39
0
 public static void SetGeometria(DependencyObject element, Geometry value)
 {
     element.SetValue(GeometriaProperty, value);
 }
Example #40
0
 public static Geometry Transform(this Geometry geometry, int srid)
 {
     throw new SpatialLinqMethodException();
 }
Example #41
0
 protected override bool IsEquivalentType(Geometry other)
 {
     return(other.GeometryType == GeometryType.LinearRing);
 }
Example #42
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //绘制界面
            System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
            String str = "M 0,0 " + Width / 26 * 18 + ",0 " + Width / 26 * 5 + "," + Height + " " + "0," + Height;

            path.Data = Geometry.Parse(str);
            path.Fill = new SolidColorBrush(Color.FromArgb(255, 40, 40, 40));
            cMain.Children.Add(path);

            System.Windows.Shapes.Path path2 = new System.Windows.Shapes.Path();
            String str2 = "M " + Width / 26 * 18 + ",0 " + Width / 26 * 21 + ",0 " + Width / 26 * 8 + "," + Height + " " + Width / 26 * 5 + "," + Height;

            path2.Data = Geometry.Parse(str2);
            path2.Fill = new SolidColorBrush(Color.FromArgb(255, 57, 57, 57));
            cMain.Children.Add(path2);

            System.Windows.Shapes.Path path3 = new System.Windows.Shapes.Path();
            String str3 = "M " + Width / 26 * 21 + ",0 " + Width + ",0 " + Width + "," + Height + " " + Width / 26 * 8 + "," + Height;

            path3.Data = Geometry.Parse(str3);
            path3.Fill = new SolidColorBrush(Color.FromArgb(255, 83, 83, 83));
            cMain.Children.Add(path3);

            Thread t = new Thread(() =>
            {
                while (time <= 10 && bIsClose != true)
                {
                    Thread.Sleep(2000);
                    time++;
                    System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                                                                         new DeleFunc(Func));
                }
            })
            {
                IsBackground = true
            };

            t.SetApartmentState(ApartmentState.STA);//设置单线程
            t.Start();

            //读取信息
            //输入
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/input.xml");
                XmlNode inputRoot         = doc.DocumentElement;
                XmlNode inputFontAndColor = inputRoot.SelectSingleNode("FontAndColor");
                //颜色
                XmlNode ForeColor = inputFontAndColor.SelectSingleNode("ForeColor");
                mw.strsInputForecolor = ForeColor.InnerText.Split(',');
                //字体
                XmlNode Name = inputFontAndColor.SelectSingleNode("Name");
                mw.strInputFontName = Name.InnerText;
                XmlNode Style = inputFontAndColor.SelectSingleNode("Style");
                mw.strInputFontStyle = Style.InnerText;
                XmlNode Size = inputFontAndColor.SelectSingleNode("Size");
                mw.strInputFontSize = Size.InnerText;
                XmlNode Strikeout = inputFontAndColor.SelectSingleNode("Strikeout");
                mw.strInputFontStrikeout = Strikeout.InnerText;
                XmlNode Underline = inputFontAndColor.SelectSingleNode("Underline");
                mw.strInputFontUnderline = Underline.InnerText;
                //格式
                XmlNode inputFormat = inputRoot.SelectSingleNode("Format");
                XmlNode Delimiter   = inputFormat.SelectSingleNode("Delimiter");
                mw.strInputFormatDelimiter = Delimiter.InnerText;
                XmlNode Range = inputFormat.SelectSingleNode("Range");
                mw.strInputFormatRange = Range.InnerText;
            }
            //工具
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/tool.xml");
                XmlNode toolRoot = doc.DocumentElement;
                XmlNode toolOtherDrawingSoftware     = toolRoot.SelectSingleNode("OtherDrawingSoftware");
                XmlNode toolOtherDrawingSoftwarePath = toolOtherDrawingSoftware.SelectSingleNode("Path");
                mw.strToolOtherDrawingSoftwarePath = toolOtherDrawingSoftwarePath.InnerText;
            }
            //颜色表
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/colortab.xml");
                XmlNode colortabRoot = doc.DocumentElement;
                XmlNode colortabPath = colortabRoot.SelectSingleNode("Path");
                if (colortabPath.InnerText.Equals(String.Empty) || !File.Exists(colortabPath.InnerText))
                {
                    mw.strColortabPath = AppDomain.CurrentDomain.BaseDirectory + @"Color\color.color";
                }
                else
                {
                    mw.strColortabPath = colortabPath.InnerText;
                }
            }

            ////更新输入区文字颜色
            //mw.iuc.tbFastGenerationrTime.Foreground = new SolidColorBrush(Color.FromRgb(Convert.ToByte(mw.strsInputForecolor[0]), Convert.ToByte(mw.strsInputForecolor[1]), Convert.ToByte(mw.strsInputForecolor[2])));
            //FontFamilyConverter ffc = new FontFamilyConverter();
            ////更新输入区文字
            //mw.iuc.tbFastGenerationrTime.FontFamily = (FontFamily)ffc.ConvertFromString(mw.strInputFontName);
            //if (mw.strInputFontStyle.Contains("粗体"))
            //{
            //    mw.iuc.tbFastGenerationrTime.FontWeight = FontWeights.UltraBold;
            //}
            //if (mw.strInputFontStyle.Contains("斜体"))
            //{
            //    mw.iuc.tbFastGenerationrTime.FontStyle = FontStyles.Italic;
            //}
            ////同时有删除线和下划线
            //if (mw.strInputFontStrikeout.Equals("是") && mw.strInputFontUnderline.Equals("是"))
            //{
            //    TextDecorationCollection myCollection = new TextDecorationCollection();
            //    TextDecoration myUnderline = new TextDecoration
            //    {
            //        Location = TextDecorationLocation.Underline
            //    };
            //    TextDecoration myStrikeThrough = new TextDecoration
            //    {
            //        Location = TextDecorationLocation.Strikethrough
            //    };
            //    myCollection.Add(myUnderline);
            //    myCollection.Add(myStrikeThrough);
            //    mw.iuc.tbFastGenerationrTime.TextDecorations = myCollection;
            //}
            //else if (mw.strInputFontStrikeout.Equals("是"))
            //{
            //    mw.iuc.tbFastGenerationrTime.TextDecorations = TextDecorations.Strikethrough;
            //}
            //else if (mw.strInputFontUnderline.Equals("是"))
            //{
            //    mw.iuc.tbFastGenerationrTime.TextDecorations = TextDecorations.Underline;
            //}
            //mw.iuc.tbFastGenerationrTime.FontSize = Double.Parse(mw.strInputFontSize);
            //窗口
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/view.xml");
                XmlNode viewRoot        = doc.DocumentElement;
                XmlNode viewFileManager = viewRoot.SelectSingleNode("FileManager");
                if (viewFileManager.InnerText.Equals("True") || viewFileManager.InnerText.Equals("true"))
                {
                    mw.bViewFileManager            = true;
                    mw.cbViewFileManager.IsChecked = true;
                }
                else
                {
                    mw.bViewFileManager            = false;
                    mw.cbViewFileManager.IsChecked = false;
                    mw.cdFileManager.Width         = new GridLength(0, GridUnitType.Pixel);
                    mw.mainDockPanel.Width         = mw.gMain.ActualWidth;
                }
            }
            //测试
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/test.xml");
                XmlNode testRoot   = doc.DocumentElement;
                XmlNode testIsWork = testRoot.SelectSingleNode("IsWork");
                if (testIsWork.InnerText.Equals("true"))
                {
                    mw.bIsWork = true;
                    mw.iuc.gMain.Visibility = Visibility.Collapsed;
                }
                XmlNode testOpacity = testRoot.SelectSingleNode("Opacity");
                mw.strStyleOpacity = testOpacity.InnerText;
                mw.Opacity         = int.Parse(testOpacity.InnerText) / 100.0;
                XmlNode testShowMode = testRoot.SelectSingleNode("ShowMode");
                if (testShowMode.InnerText.Equals("Launchpad"))
                {
                    mw.iuc.mShow             = InputUserControl.ShowMode.Launchpad;
                    mw.iuc.dgMain.Visibility = Visibility.Collapsed;
                }
                else if (testShowMode.InnerText.Equals("DataGrid"))
                {
                    mw.iuc.mShow             = InputUserControl.ShowMode.Launchpad;
                    mw.iuc.dgMain.Visibility = Visibility.Collapsed;
                }
                else if (testShowMode.InnerText.Equals("PianoRoll"))
                {
                    mw.iuc.mShow = InputUserControl.ShowMode.DataGrid;
                }
            }
            //版本
            {
                //XmlDocument doc = new XmlDocument();
                //doc.Load("Config/version.xml");
                //XmlNode versionRoot = doc.DocumentElement;
                //XmlNode versionNowVersion = versionRoot.SelectSingleNode("NowVersion");
                //mw.strNowVersion = versionNowVersion.InnerText;
                //XmlNode versionAutoUpdate = versionRoot.SelectSingleNode("AutoUpdate");
                //if (versionAutoUpdate.InnerText.Equals("true"))
                //{
                //    mw.bIsAutoUpdate = true;
                //    try
                //    {
                //        //检测版本
                //        string paraUrlCoded = System.Web.HttpUtility.UrlEncode("NowVersion");
                //        paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(mw.strNowVersion);
                //        string result = NoFileRequestUtils.NoFilePostRequest("http://www.launchpadlight.com/maker/CheckVersion", paraUrlCoded);

                //        if (result.Equals("fail"))
                //        {
                //            System.Windows.Forms.MessageBoxButtons mssBoxBt = System.Windows.Forms.MessageBoxButtons.OKCancel;
                //            System.Windows.Forms.MessageBoxIcon mssIcon = System.Windows.Forms.MessageBoxIcon.Warning;
                //            System.Windows.Forms.MessageBoxDefaultButton mssDefbt = System.Windows.Forms.MessageBoxDefaultButton.Button1;
                //            System.Windows.Forms.DialogResult dr;
                //            if (mw.strMyLanguage.Equals("en-US"))
                //            {
                //                dr = System.Windows.Forms.MessageBox.Show("Whether a new version is updated or not?", "Hints", mssBoxBt, mssIcon, mssDefbt);
                //            }
                //           // else if (mw.strMyLanguage.Equals("zh-CN"))
                //            else
                //            {
                //                dr = System.Windows.Forms.MessageBox.Show("有新版本是否更新?", "提示", mssBoxBt, mssIcon, mssDefbt);
                //            }
                //            if (dr == System.Windows.Forms.DialogResult.OK)
                //            {
                //                //有新版本
                //                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Update.exe"))
                //                {
                //                    File.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\Update.exe");
                //                }
                //                DownloadFile("http://www.launchpadlight.com/File/Update/Update.exe", AppDomain.CurrentDomain.BaseDirectory + @"\Update.exe");
                //                Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"\Update.exe");
                //                System.Environment.Exit(0);
                //            }
                //        }
                //    }
                //    catch
                //    {
                //        new MessageDialog(this, "CheckTheVersionFailed").ShowDialog();
                //    }
                //}
                //else
                //{
                //    mw.bIsAutoUpdate = false;
                //}
            }
            //画板
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/inkcanvas.xml");
                XmlNode  inkcanvasRoot  = doc.DocumentElement;
                XmlNode  inkcanvasColor = inkcanvasRoot.SelectSingleNode("Color");
                String[] strs           = inkcanvasColor.InnerText.Split(',');
                mw.colorInkCanvas = Color.FromArgb(Convert.ToByte(strs[0]), Convert.ToByte(strs[1]), Convert.ToByte(strs[2]), Convert.ToByte(strs[3]));
                XmlNode inkcanvasImageSize = inkcanvasRoot.SelectSingleNode("ImageSize");
                mw.iInkCanvasSize = Convert.ToInt32(inkcanvasImageSize.InnerText);
            }
            //隐藏
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Config/hide.xml");
                XmlNode hideRoot = doc.DocumentElement;
                XmlNode hideTip  = hideRoot.SelectSingleNode("Tip");
                if (hideTip.InnerText.Equals("true"))
                {
                    mw.bIsShowTip = true;
                }
                else
                {
                    mw.bIsShowTip = false;
                }
                XmlNode hideRangeListNumber = hideRoot.SelectSingleNode("RangeListNumber");
                if (hideRangeListNumber.InnerText.Equals("true"))
                {
                    mw.bIsRangeListNumber = true;
                }
                else
                {
                    mw.bIsRangeListNumber = false;
                }
            }

            MainToLogin();
            bIsRead = true;
        }
Example #43
0
        private bool showCutOff()
        {       // nur wenn beide Kurven gültig sind
            base.ActiveObject = null;
            base.FeedBack.ClearSelected();
            if ((iCurve1 != null) && (iCurve2 != null) && (iCurve1 != iCurve2))
            {
                Plane pl; // nur bei gemeisamer Ebene
                if (Curves.GetCommonPlane(iCurve1, iCurve2, out pl))
                {
                    if (composedSplit)
                    {
                        if (iCurveComposedSplit != null)
                        {
                            owner = (iCurveComposedSplit as IGeoObject).Owner;                              // owner merken für löschen und Einfügen
                        }
                        else
                        {
                            owner = ownerCreated;
                        }
                    }
                    //                        owner = (iCurveComposedSplit as IGeoObject).Owner; // owner merken für löschen und Einfügen
                    else
                    {
                        owner = (iCurve1 as IGeoObject).Owner;          // owner merken für löschen und Einfügen
                    }
                    pl.Align(base.ActiveDrawingPlane, false);           // Winkel anpassen
                    ICurve2D curve1_2D = iCurve1.GetProjectedCurve(pl); // die 2D-Kurven
                    if (curve1_2D is Path2D)
                    {
                        (curve1_2D as Path2D).Flatten();
                    }
                    ICurve2D curve2_2D = iCurve2.GetProjectedCurve(pl);
                    if (curve2_2D is Path2D)
                    {
                        (curve2_2D as Path2D).Flatten();
                    }
                    ICurve newCurve = iCurve1.Clone();                                                                // neue Kurve bis zum Schnittpunkt
                                                                                                                      // hier die Schnittpunkte bestimmen und den cutPoint auf den nächsten Schnittpunt setzen
                    GeoPoint2DWithParameter cutPoint;
                    if (Curves2D.NearestPoint(curve1_2D.Intersect(curve2_2D), pl.Project(objectPoint), out cutPoint)) // fasen war möglich
                    {
                        GeoVector2D v1 = curve1_2D.DirectionAt(cutPoint.par1);                                        // die Richtung im Schnittpunkt
                        if (cutPoint.par1 > 0.5)
                        {
                            v1 = v1.Opposite();                      // evtl rumdrehen, falls am Ende
                        }
                        v1.Norm();
                        GeoVector2D v2 = curve2_2D.DirectionAt(cutPoint.par2); // die Richtung im Schnittpunkt
                        if (cutPoint.par2 > 0.5)
                        {
                            v2 = v2.Opposite();                      // evtl rumdrehen, falls am Ende
                        }
                        v2.Norm();
                        GeoVector2D v = (v1 + v2); // Winkelhalbierende
                        if (Precision.IsNullVector(pl.ToGlobal(v)))
                        {
                            return(false);
                        }
                        v.Norm();
                        v = cutOffLen * v;                                      // Winkelhalbierende mit Fas-Abstand
                        GeoPoint2D dirPoint = cutPoint.p + v;                   // wird unten auch als Auswahlpunkt für die Richtung genutzt
                        Line2D     line2D   = new Line2D(dirPoint, cutPoint.p); // Linie vorbesetzen, Punkte eigentlich egal
                        if ((methodSelect == 0) || (methodSelect == 1))
                        {                                                       // 0: Länge cutOffLen = Seitenlänge Kurve1   1: Länge cutOffLen = Fasenlänge
                            double sideLength;
                            if (methodSelect == 1)                              // Länge cutOffLen = Fasenlänge
                                                                                // Geometrie, Pythagoras, bekannt Seite=cutOffLen, Winkel 1 = cutOffAng, Winkel 2 = Winkel der Kurven im Schnittpunkt
                            {
                                sideLength = cutOffLen * (Math.Cos(cutOffAng.Radian) + (Math.Sin(cutOffAng.Radian) / Math.Tan(Math.Abs(new SweepAngle(v1, v2).Radian))));
                            }
                            else
                            {
                                sideLength = cutOffLen;
                            }
                            // neue Kurve bis zum Schnittpunkt synthetisieren, dazu: Schnittpunkt finden des Abschnitts mit der iCurve1

                            Ellipse arcTmp = Ellipse.Construct();
                            arcTmp.SetCirclePlaneCenterRadius(pl, pl.ToGlobal(cutPoint.p), sideLength);
                            ICurve2D curveArc_2D = (arcTmp as ICurve).GetProjectedCurve(pl); // die 2D-Kurve
                            GeoPoint2DWithParameter cutArc;
                            GeoPoint2D startPoint;
                            if (Curves2D.NearestPoint(curve1_2D.Intersect(curveArc_2D), dirPoint, out cutArc)) // war möglich
                            {
                                startPoint = cutArc.p;
                            }
                            else
                            {
                                return(false);
                            }

                            /*
                             *                          double parCut;
                             *
                             *                          // neue Kurve bis zum Schnittpunkt synthetisieren:
                             *                          if (cutPoint.par1 <= 0.5)
                             *                          {
                             *                              newCurve.Trim(cutPoint.par1,1.0);
                             *                              parCut = (sideLength)/newCurve.Length; // der Parameter des Fasenpunktes
                             *                          }
                             *                          else
                             *                          {
                             *                              newCurve.Trim(0.0,cutPoint.par1);
                             *                              parCut = (newCurve.Length-sideLength)/newCurve.Length; // der Parameter des Fasenpunktes
                             *                          }
                             *                          GeoPoint2D startPoint = pl.Project(newCurve.PointAt(parCut));
                             *                          GeoVector2D vc = curve1_2D.DirectionAt(parCut); // die Richtung im Schnittpunkt
                             */
                            GeoVector2D vc = curve1_2D.DirectionAt(curve1_2D.PositionOf(startPoint)); // die Richtung im Schnittpunkt
                            if (cutPoint.par1 <= 0.5)
                            {
                                vc = vc.Opposite();                            // evtl rumdrehen, falls am Ende
                            }
                            if (Geometry.OnLeftSide(dirPoint, startPoint, vc)) // Richtung festlegen für Winkeloffset
                            {
                                vc.Angle = vc.Angle + new SweepAngle(cutOffAng);
                            }
                            else
                            {
                                vc.Angle = vc.Angle - new SweepAngle(cutOffAng);
                            }
                            // Hilfslinie im Fasabstand, im Offsetwinkel
                            line2D = new Line2D(startPoint, startPoint + vc);
                        }
                        if (methodSelect == 2)                             // Länge cutOffLen = Winkelhalbierendenlänge
                        {
                            v.Angle = v.Angle + new SweepAngle(cutOffAng); // Winkelhalbierendenwinkel + Offset
                                                                           // Hilfslinie im Fasabstand, senkrecht auf der Winkelhalbierenden v
                            line2D = new Line2D(dirPoint, dirPoint + v.ToLeft());
                        }

                        GeoPoint2DWithParameter cutPoint1;
                        GeoPoint2DWithParameter cutPoint2;
                        // schnittpunkte der Hilfslinie mit den beiden Kurven
                        if (Curves2D.NearestPoint(curve1_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint1))
                        {
                            if (Curves2D.NearestPoint(curve2_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint2))
                            {   // da isse, die Fas-Linie, nur, wenn die Punkte echt auf der Kurve bis zum Schnittpunkt  liegen:
                                bool onCurve1, onCurve2;
                                // Berechnung, ob die Kurven realen Schnittpunkt haben
                                //								if ((cutPoint.par1 <= 1.0001) & (cutPoint.par1 >= -0.0001) & (cutPoint.par2 <= 1.0001) & (cutPoint.par2 >= -0.0001))
                                if (curve1_2D.IsParameterOnCurve(cutPoint.par1) & curve2_2D.IsParameterOnCurve(cutPoint.par2))
                                {
                                    onCurve1 = (cutPoint1.par1 > 0.0) & (cutPoint1.par1 < 1.0);
                                    onCurve2 = (cutPoint2.par1 > 0.0) & (cutPoint2.par1 < 1.0);
                                }
                                else
                                {
                                    if (cutPoint.par1 > 0.5)
                                    {
                                        onCurve1 = (cutPoint1.par1 > 0.0) & (cutPoint1.par1 < 100);
                                    }
                                    // im Quasi-Parallelfall stehen in par1 riesige Werte
                                    else
                                    {
                                        onCurve1 = (cutPoint1.par1 < 1.0) & (cutPoint1.par1 > -100);
                                    }
                                    if (cutPoint.par2 > 0.5)
                                    {
                                        onCurve2 = (cutPoint2.par1 > 0.0) & (cutPoint2.par1 < 100);
                                    }
                                    else
                                    {
                                        onCurve2 = (cutPoint2.par1 < 1.0) & (cutPoint2.par1 > -100);
                                    }
                                }
                                if (onCurve1 && onCurve2)
                                {
                                    line.SetTwoPoints(pl.ToGlobal(cutPoint1.p), pl.ToGlobal(cutPoint2.p));
                                    // Fasenlänge vorgegeben, aber mit obiger Berechnung falsch, da dort Linien vorausgesetzt werden
                                    if ((methodSelect == 1) && (Math.Abs(line.Length - cutOffLen) > Precision.eps))
                                    {   // jetzt mit Iteration annähern
                                        double parInd      = 0.5;
                                        double parIndDelta = 0.25;
                                        for (int i = 0; i < 49; ++i) // 48 Schritte müssen reichen, par kann zwischen 0 und 1 liegen
                                        {
                                            GeoPoint2D  startPoint = pl.Project(newCurve.PointAt(parInd));
                                            GeoVector2D vc         = curve1_2D.DirectionAt(parInd); // die Richtung im Schnittpunkt
                                            if (cutPoint.par1 <= 0.5)
                                            {
                                                vc = vc.Opposite();                            // evtl rumdrehen, falls am Ende
                                            }
                                            if (Geometry.OnLeftSide(dirPoint, startPoint, vc)) // Richtung festlegen für Winkeloffset
                                            {
                                                vc.Angle = vc.Angle + new SweepAngle(cutOffAng);
                                            }
                                            else
                                            {
                                                vc.Angle = vc.Angle - new SweepAngle(cutOffAng);
                                            }
                                            // Hilfslinie im Fasabstand, im Offsetwinkel
                                            line2D = new Line2D(startPoint, startPoint + vc);
                                            if (Curves2D.NearestPoint(curve1_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint1))
                                            {
                                                if (Curves2D.NearestPoint(curve2_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint2))
                                                {   // da isse, die Fas-Linie, nur, wenn die Punkte echt auf der Kurvr liegen:
                                                    if (cutPoint.par1 > 0.5)
                                                    {
                                                        onCurve1 = (cutPoint1.par1 > 0.0) & (cutPoint1.par1 < 100);
                                                    }
                                                    // im Quasi-Parallelfall stehen in par1 riesige Werte
                                                    else
                                                    {
                                                        onCurve1 = (cutPoint1.par1 < 1.0) & (cutPoint1.par1 > -100);
                                                    }
                                                    if (cutPoint.par2 > 0.5)
                                                    {
                                                        onCurve2 = (cutPoint2.par1 > 0.0) & (cutPoint2.par1 < 100);
                                                    }
                                                    else
                                                    {
                                                        onCurve2 = (cutPoint2.par1 < 1.0) & (cutPoint2.par1 > -100);
                                                    }
                                                    if (onCurve1 && onCurve2)
                                                    {
                                                        line.SetTwoPoints(pl.ToGlobal(cutPoint1.p), pl.ToGlobal(cutPoint2.p));
                                                        if ((Math.Abs(line.Length - cutOffLen) < Precision.eps)) // gefunden und raus
                                                        {
                                                            break;
                                                        }
                                                        else
                                                        {
                                                            if (line.Length < cutOffLen)
                                                            {                                    // Fase ist zu klein: Parameter parInd vergrößern
                                                                parInd      = parInd + parIndDelta;
                                                                parIndDelta = parIndDelta / 2.0; // delta halbieren (Bisection!!)
                                                                continue;                        // nächster Schritt in der For-Schleife
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // alle anderen Fälle: // Fase ist zu gross: Parameter parInd verkleinern
                                            parInd      = parInd - parIndDelta;
                                            parIndDelta = parIndDelta / 2.0; // delta halbieren (Bisection!!)
                                        } // for schleife Iteration
                                    } // Ende Iteration
                                    line.CopyAttributes(iCurve1 as IGeoObject);
                                    base.ActiveObject = line;        // merken
                                    base.FeedBack.AddSelected(line); // darstellen
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
Example #44
0
 void IMetroDrawingContext.DrawGeometry(Brush brush, Pen pen, Geometry geometry)
 {
     m_Flattener.DrawGeometry(brush, pen, geometry);
 }
Example #45
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint != SvgRenderingHint.Shape || hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (String.Equals(_svgElement.ParentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            string sVisibility = styleElm.GetPropertyValue("visibility");
            string sDisplay    = styleElm.GetPropertyValue("display");

            if (String.Equals(sVisibility, "hidden") || String.Equals(sDisplay, "none"))
            {
                return;
            }

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

            Geometry geometry = CreateGeometry(_svgElement, context.OptimizePath);

            if (geometry != null && !geometry.IsEmpty())
            {
                SetClip(context);

                WpfSvgPaint fillPaint = new WpfSvgPaint(context, styleElm, "fill");

                string fileValue = styleElm.GetAttribute("fill");

                Brush brush = fillPaint.GetBrush(geometry);

                WpfSvgPaint strokePaint = new WpfSvgPaint(context, styleElm, "stroke");
                Pen         pen         = strokePaint.GetPen();

                if (brush != null || pen != null)
                {
                    Transform transform = this.Transform;
                    if (transform != null && !transform.Value.IsIdentity)
                    {
                        geometry.Transform = transform;
                        if (brush != null)
                        {
                            Transform brushTransform = brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                brush.Transform = groupTransform;
                            }
                        }
                    }
                    else
                    {
                        transform = null; // render any identity transform useless...
                    }

                    GeometryDrawing drawing = new GeometryDrawing(brush, pen, geometry);

                    string elementId = this.GetElementName();
                    if (!String.IsNullOrEmpty(elementId) && !context.IsRegisteredId(elementId))
                    {
                        SvgObject.SetName(drawing, elementId);

                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetId(drawing, elementId);
                        }
                    }

                    Brush    maskBrush = this.Masking;
                    Geometry clipGeom  = this.ClipGeometry;
                    if (clipGeom != null || maskBrush != null)
                    {
                        //Geometry clipped = Geometry.Combine(geometry, clipGeom,
                        //    GeometryCombineMode.Exclude, null);

                        //if (clipped != null && !clipped.IsEmpty())
                        //{
                        //    geometry = clipped;
                        //}
                        DrawingGroup clipMaskGroup = new DrawingGroup();

                        Rect geometryBounds = geometry.Bounds;

                        if (clipGeom != null)
                        {
                            clipMaskGroup.ClipGeometry = clipGeom;

                            SvgUnitType clipUnits = this.ClipUnits;
                            if (clipUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(
                                    new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(
                                    new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                clipGeom.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    clipGeom.Transform = transform;
                                }
                            }
                        }
                        if (maskBrush != null)
                        {
                            SvgUnitType maskUnits = this.MaskUnits;
                            if (maskUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(
                                    new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(
                                    new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                DrawingGroup maskGroup = ((DrawingBrush)maskBrush).Drawing as DrawingGroup;
                                if (maskGroup != null)
                                {
                                    DrawingCollection maskDrawings = maskGroup.Children;
                                    for (int i = 0; i < maskDrawings.Count; i++)
                                    {
                                        Drawing         maskDrawing  = maskDrawings[i];
                                        GeometryDrawing maskGeomDraw = maskDrawing as GeometryDrawing;
                                        if (maskGeomDraw != null)
                                        {
                                            if (maskGeomDraw.Brush != null)
                                            {
                                                ConvertColors(maskGeomDraw.Brush);
                                            }
                                            if (maskGeomDraw.Pen != null)
                                            {
                                                ConvertColors(maskGeomDraw.Pen.Brush);
                                            }
                                        }
                                    }
                                }

                                //if (transformGroup != null)
                                //{
                                //    drawingBounds = transformGroup.TransformBounds(drawingBounds);
                                //}

                                //maskBrush.Viewbox = drawingBounds;
                                //maskBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                //maskBrush.Stretch = Stretch.Uniform;

                                //maskBrush.Viewport = drawingBounds;
                                //maskBrush.ViewportUnits = BrushMappingMode.Absolute;

                                maskBrush.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    maskBrush.Transform = transform;
                                }
                            }

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

                        clipMaskGroup.Children.Add(drawing);
                        drawGroup.Children.Add(clipMaskGroup);
                    }
                    else
                    {
                        drawGroup.Children.Add(drawing);
                    }
                }
            }

            RenderMarkers(renderer, styleElm, context);
        }
        public static CanvasGeometry AsPathFromSegment(this PathF path, int segmentIndex, float zoom, ICanvasResourceCreator creator)
        {
            float scale = 1 / zoom;

            var builder = new CanvasPathBuilder(creator);

            var type = path.GetSegmentType(segmentIndex);

            if (type == PathOperation.Line)
            {
                int segmentStartingPointIndex = path.GetSegmentPointIndex(segmentIndex);
                var startPoint = path[segmentStartingPointIndex - 1];
                builder.BeginFigure(startPoint.X * scale, startPoint.Y * scale, CanvasFigureFill.Default);

                var point = path[segmentStartingPointIndex];
                builder.AddLine(point.X * scale, point.Y * scale);
            }
            else if (type == PathOperation.Quad)
            {
                int segmentStartingPointIndex = path.GetSegmentPointIndex(segmentIndex);
                var startPoint = path[segmentStartingPointIndex - 1];
                builder.BeginFigure(startPoint.X * scale, startPoint.Y * scale, CanvasFigureFill.Default);

                var controlPoint = path[segmentStartingPointIndex++];
                var endPoint     = path[segmentStartingPointIndex];
                builder.AddQuadraticBezier(
                    new Vector2(controlPoint.X * scale, controlPoint.Y * scale),
                    new Vector2(endPoint.X * scale, endPoint.Y * scale));
            }
            else if (type == PathOperation.Cubic)
            {
                int segmentStartingPointIndex = path.GetSegmentPointIndex(segmentIndex);
                var startPoint = path[segmentStartingPointIndex - 1];
                builder.BeginFigure(startPoint.X * scale, startPoint.Y * scale, CanvasFigureFill.Default);

                var controlPoint1 = path[segmentStartingPointIndex++];
                var controlPoint2 = path[segmentStartingPointIndex++];
                var endPoint      = path[segmentStartingPointIndex];
                builder.AddCubicBezier(
                    new Vector2(controlPoint1.X * scale, controlPoint1.Y * scale),
                    new Vector2(controlPoint2.X * scale, controlPoint2.Y * scale),
                    new Vector2(endPoint.X * scale, endPoint.Y * scale));
            }
            else if (type == PathOperation.Arc)
            {
                path.GetSegmentInfo(segmentIndex, out var pointIndex, out var arcAngleIndex, out var arcClockwiseIndex);

                var topLeft     = path[pointIndex++];
                var bottomRight = path[pointIndex];
                var startAngle  = path.GetArcAngle(arcAngleIndex++);
                var endAngle    = path.GetArcAngle(arcAngleIndex);
                var clockwise   = path.GetArcClockwise(arcClockwiseIndex);

                while (startAngle < 0)
                {
                    startAngle += 360;
                }

                while (endAngle < 0)
                {
                    endAngle += 360;
                }

                var rotation    = Geometry.GetSweep(startAngle, endAngle, clockwise);
                var absRotation = Math.Abs(rotation);

                var rectX      = topLeft.X * scale;
                var rectY      = topLeft.Y * scale;
                var rectWidth  = (bottomRight.X * scale) - rectX;
                var rectHeight = (bottomRight.Y * scale) - rectY;

                var startPoint = Geometry.OvalAngleToPoint(rectX, rectY, rectWidth, rectHeight, -startAngle);
                var endPoint   = Geometry.OvalAngleToPoint(rectX, rectY, rectWidth, rectHeight, -endAngle);

                builder.BeginFigure(startPoint.X * scale, startPoint.Y * scale, CanvasFigureFill.Default);

                builder.AddArc(
                    new Vector2(endPoint.X, endPoint.Y),
                    rectWidth / 2,
                    rectHeight / 2,
                    0,
                    clockwise ? CanvasSweepDirection.Clockwise : CanvasSweepDirection.CounterClockwise,
                    absRotation >= 180 ? CanvasArcSize.Large : CanvasArcSize.Small
                    );
            }

            builder.EndFigure(CanvasFigureLoop.Open);

            return(CanvasGeometry.CreatePath(builder));
        }
Example #47
0
        public override void RenderTextRun(SvgTextContentElement element, ref Point ctp,
                                           string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            double emSize         = GetComputedFontSize(element);
            var    fontFamilyInfo = GetTextFontFamilyInfo(element);

            WpfTextStringFormat stringFormat = GetTextStringFormat(element);

            if (fontFamilyInfo.FontFamilyType == WpfFontFamilyType.Svg)
            {
                WpfTextTuple textInfo = new WpfTextTuple(fontFamilyInfo, emSize, stringFormat, element);
                this.RenderTextRun(textInfo, ref ctp, text, rotate, placement);
                return;
            }

            FontFamily  fontFamily  = fontFamilyInfo.Family;
            FontStyle   fontStyle   = fontFamilyInfo.Style;
            FontWeight  fontWeight  = fontFamilyInfo.Weight;
            FontStretch fontStretch = fontFamilyInfo.Stretch;

            // Fix the use of Postscript fonts...
            WpfFontFamilyVisitor fontFamilyVisitor = _context.FontFamilyVisitor;

            if (!string.IsNullOrWhiteSpace(_actualFontName) && fontFamilyVisitor != null)
            {
                WpfFontFamilyInfo familyInfo = fontFamilyVisitor.Visit(_actualFontName,
                                                                       fontFamilyInfo, _context);
                if (familyInfo != null && !familyInfo.IsEmpty)
                {
                    fontFamily  = familyInfo.Family;
                    fontWeight  = familyInfo.Weight;
                    fontStyle   = familyInfo.Style;
                    fontStretch = familyInfo.Stretch;
                }
            }

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            bool isForcedPathMode = false;

            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            else
            {
                // WPF gradient fill does not work well on text, use geometry to render it
                isForcedPathMode = (fillPaint.FillType == WpfFillType.Gradient);
            }
            if (textPen != null)
            {
                textPen.LineJoin = PenLineJoin.Round; // Better for text rendering
                isForcedPathMode = true;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);

            if (textDecors == null)
            {
                SvgTextBaseElement textElement = element.ParentNode as SvgTextBaseElement;

                if (textElement != null)
                {
                    textDecors = GetTextDecoration(textElement);
                }
            }

            TextAlignment alignment = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            var typeFace = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            if (textPositions != null && textPositions.Count != 0)
            {
                if (textPositions.Count == text.Trim().Length) //TODO: Best way to handle this...
                {
                    text = text.Trim();
                }
            }

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                double spacing = Convert.ToDouble(letterSpacing);

                int startSpaces = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (char.IsWhiteSpace(text[i]))
                    {
                        startSpaces++;
                    }
                    else
                    {
                        break;
                    }
                }

                int j = 0;

                string inputText = string.Empty;
                for (int i = 0; i < text.Length; i++)
                {
                    // Avoid rendering only spaces at the start of text run...
                    if (i == 0 && startSpaces != 0)
                    {
                        inputText = text.Substring(0, startSpaces + 1);
                        i        += startSpaces;
                    }
                    else
                    {
                        inputText = new string(text[i], 1);
                    }

                    FormattedText formattedText = new FormattedText(inputText, _context.CultureInfo,
                                                                    stringFormat.Direction, typeFace, emSize, textBrush);
//#if NET40
//                    FormattedText formattedText = new FormattedText(inputText,  _context.CultureInfo,
//                        stringFormat.Direction, typeFace, emSize, textBrush);
//#else
//                    FormattedText formattedText = new FormattedText(inputText, _context.CultureInfo,
//                        stringFormat.Direction, typeFace, emSize, textBrush, _context.PixelsPerDip);
//#endif

                    if (this.IsMeasuring)
                    {
                        this.AddTextWidth(ctp, formattedText.WidthIncludingTrailingWhitespace);
                        continue;
                    }

                    formattedText.Trimming      = stringFormat.Trimming;
                    formattedText.TextAlignment = stringFormat.Alignment;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        formattedText.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && j < textPosCount)
                    {
                        textPosition = textPositions[j];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = formattedText.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(ctp.X, ctp.Y - yCorrection);

                    if (isForcedPathMode || _context.TextAsGeometry)
                    {
                        Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                        if (textGeometry != null && !textGeometry.IsEmpty())
                        {
                            _drawContext.DrawGeometry(textBrush, textPen,
                                                      ExtractTextPathGeometry(textGeometry));

                            this.IsTextPath = true;
                        }
                        else
                        {
                            _drawContext.DrawText(formattedText, textPoint);
                        }
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                    j++;
                }
            }
            else
            {
                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
                                                                stringFormat.Direction, typeFace, emSize, textBrush);
//#if !NET40
//                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
//                    stringFormat.Direction, typeFace, emSize, textBrush, _context.PixelsPerDip);
//#else
//                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
//                    stringFormat.Direction, typeFace,  emSize, textBrush);
//#endif

                if (this.IsMeasuring)
                {
                    this.AddTextWidth(ctp, formattedText.WidthIncludingTrailingWhitespace);
                    return;
                }

                var textContext = this.TextContext;
                if (textContext != null && textContext.IsPositionChanged(element) == false)
                {
                    if (alignment == TextAlignment.Center && this.TextWidth > 0)
                    {
                        alignment = TextAlignment.Left;
                    }
                }

                formattedText.TextAlignment = alignment;
                formattedText.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    formattedText.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = formattedText.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                if (isForcedPathMode || _context.TextAsGeometry)
                {
                    Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }
                }
                else
                {
                    _drawContext.DrawText(formattedText, textPoint);
                }

                //float bboxWidth = (float)formattedText.Width;
                double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Example #48
0
        async void InitializeMarkers()
        {
            // Get MapView from the view and assign map from view-model
            _mapView     = MyMapView;
            _mapView.Map = myMap;

            //add nearshore and offshore marine zones that correspond with the marine point forecasts
            WmsLayer zoneLayerOne   = new WmsLayer(new Uri("https://nowcoast.noaa.gov/arcgis/services/nowcoast/forecast_meteoceanhydro_pts_zones_geolinks/MapServer/WMSServer?request=GetCapabilities&service=WMS&version=1.3.0"), layerOne);
            WmsLayer zoneLayerTwo   = new WmsLayer(new Uri("https://nowcoast.noaa.gov/arcgis/services/nowcoast/forecast_meteoceanhydro_pts_zones_geolinks/MapServer/WMSServer?request=GetCapabilities&service=WMS&version=1.3.0"), layerTwo);
            WmsLayer zoneLayerThree = new WmsLayer(new Uri("https://nowcoast.noaa.gov/arcgis/services/nowcoast/forecast_meteoceanhydro_pts_zones_geolinks/MapServer/WMSServer?request=GetCapabilities&service=WMS&version=1.3.0"), layerThree);

            myMap.OperationalLayers.Add(zoneLayerOne);
            myMap.OperationalLayers.Add(zoneLayerTwo);
            myMap.OperationalLayers.Add(zoneLayerThree);

            var legendInfo = await zoneLayerTwo.GetLegendInfosAsync();

            // Create graphics overlay
            GraphicsOverlay userClick         = new GraphicsOverlay();
            GraphicsOverlay userLocationLayer = new GraphicsOverlay();

            // Create simple marker symbol for user location
            SimpleMarkerSymbol userMarker = new SimpleMarkerSymbol()
            {
                Color = Color.Red,
                Size  = 10,
                Style = SimpleMarkerSymbolStyle.Diamond
            };
            //get user location
            string userLat = "";
            string userLon = "";

            try
            {
                var request      = new GeolocationRequest(GeolocationAccuracy.Medium);
                var userLocation = await Geolocation.GetLocationAsync(request);

                if (userLocation != null)
                {
                    userLat = userLocation.Latitude.ToString();
                    userLon = userLocation.Longitude.ToString();

                    string   userLocationFormatted = userLat + " " + userLon;
                    MapPoint userMapPoint          = CoordinateFormatter.FromLatitudeLongitude(userLocationFormatted, SpatialReferences.Wgs84);
                    Graphic  userGraphic           = new Graphic(userMapPoint, userMarker);

                    userLocationLayer.Graphics.Add(userGraphic);
                    _mapView.GraphicsOverlays.Add(userLocationLayer);
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }


            // Create simple marker symbol for where the user clicks on the map
            SimpleMarkerSymbol userClickMarker = new SimpleMarkerSymbol()
            {
                Color = Color.Black,
                Size  = 10,
                Style = SimpleMarkerSymbolStyle.X
            };

            Graphic userClickGraphic = new Graphic();

            userClickGraphic.Symbol = userClickMarker;

            _mapView.GraphicsOverlays.Add(userClick);

            // add symbol where user has tapped on the map
            _mapView.GeoViewTapped += (s, e) =>
            {
                // get rid of any current markers from previous map taps
                userClick.Graphics.Clear();

                Geometry myGeo      = GeometryEngine.Project(e.Location, SpatialReferences.Wgs84);
                MapPoint projection = (MapPoint)myGeo;

                double latClick = Convert.ToDouble(projection.Y);
                double lonClick = Convert.ToDouble(projection.X);


                string   location         = latClick.ToString() + " " + lonClick.ToString();
                MapPoint startingLocation = CoordinateFormatter.FromLatitudeLongitude(location, SpatialReferences.Wgs84);

                userClickGraphic.Geometry = startingLocation;
                userClick.Graphics.Add(userClickGraphic);

                GetWeather(latClick, lonClick);
            };
        }
Example #49
0
 /// <summary>
 /// Constructs a RelateOp object.
 /// </summary>
 /// <param name="g0"></param>
 /// <param name="g1"></param>
 public RelateOp(Geometry g0, Geometry g1) : base(g0, g1)
 {
     _relate = new RelateComputer(_arg);
 }
Example #50
0
        // rendering
        protected override void OnRender(DrawingContext drawingContext)
        {
            // draw background
            drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, ActualWidth, ActualHeight)));
            drawingContext.DrawRectangle(BackgroundBrush, new Pen(), new Rect(0, 0, ActualWidth, ActualHeight));

            // draw text
            if (Text == string.Empty)
            {
                return;
            }
            var formattedText = new FormattedText(
                Text,
                System.Globalization.CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface(FontFamily.Source),
                FontSize, ForegroundBrush);

            var leftMargin = 4.0 + BorderThickness.Left + LineNumberMarginWidth;
            var topMargin  = 2.0 + BorderThickness.Top;

            // Background highlight
            if (HighlightText != null && HighlightText.Any())
            {
                foreach (string text in HighlightText)
                {
                    var index     = 0;
                    var lastIndex = Text.LastIndexOf(text, StringComparison.OrdinalIgnoreCase);

                    while (index <= lastIndex)
                    {
                        index = Text.IndexOf(text, index, StringComparison.OrdinalIgnoreCase);

                        Geometry geom = formattedText.BuildHighlightGeometry(new Point(leftMargin, topMargin - VerticalOffset), index, text.Length);
                        if (geom != null)
                        {
                            drawingContext.DrawGeometry(HighlightBrush, null, geom);
                        }
                        index += 1;
                    }
                }
            }

            HighlightSyntax(formattedText);

            // left from first char boundary

            var leftBorder = GetRectFromCharacterIndex(0).Left;

            if (!Double.IsInfinity(leftBorder))
            {
                _leftTextBorder = leftBorder;
            }

            drawingContext.DrawText(formattedText, new Point(_leftTextBorder - HorizontalOffset, topMargin - VerticalOffset));


            // draw lines
            if (GetLastVisibleLineIndex() != -1)
            {
                LastLineNumberFormat = GetLineNumbers();
            }
            if (LastLineNumberFormat != null)
            {
                LastLineNumberFormat.SetForegroundBrush(LineNumberBrush);
                drawingContext.DrawText(LastLineNumberFormat, new Point(3, topMargin));
            }
        }
Example #51
0
        public static CalcResult ElementCalc3(string fluid, double l, double Aa_fin, double Aa_tube, double A_r_cs, double Ar, Geometry geo, double tai,
                                              double RHi, double tri, double pri, double hri, double mr, double g, double ma, double ha, double haw,
                                              double eta_surface, double zh, double zdp, int hexType, double thickness, double conductivity, double Pwater, AbstractState coolprop, double[,] SourceTableData)
        {
            Model.HumidAirProp humidairprop = new Model.HumidAirProp();

            RHi = RHi > 1 ? 1 : RHi;
            double     dh         = geo.Di;
            double     Q          = 0;
            double     Tout_a     = 0;
            double     Q_sensible = 0;
            double     r_metal    = thickness / conductivity / Ar;
            CalcResult res        = new CalcResult();

            coolprop.update(input_pairs.HmassP_INPUTS, hri * 1000, (fluid == "Water" ? Pwater : pri) * 1000);
            double mu_r = coolprop.viscosity();
            //double mu_r = CoolProp.PropsSI("V", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double k_r = coolprop.conductivity();
            //double k_r = CoolProp.PropsSI("L", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double rho_r = coolprop.rhomass();
            //double rho_r = CoolProp.PropsSI("D", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double cp_r = coolprop.cpmass();
            //double cp_r = CoolProp.PropsSI("C", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);

            double Pr_r = cp_r * mu_r / k_r;

            res.Vel_r = g / rho_r;
            double Re_r    = rho_r * res.Vel_r * dh / mu_r;
            double fh      = RefrigerantSPHTC.ff_CHURCHILL(Re_r);
            double Nusselt = RefrigerantSPHTC.NU_GNIELINSKI(Re_r, Pr_r, fh);

            res.href = Nusselt * k_r / dh * zh;
            double cp_da = 1.0;

            cp_da = (hexType == 0 ? 1.027 : 1.02) * 1000;
            double Tin_a = tai;
            double Tin_r = tri;

            //double cp_da0 = CoolProp.HAPropsSI("C", "T", Tin_a + 273.15, "P", 101325, "R", RHi);
            //cp_da = 1005.1458551 + 0.1541627 * Tin_a + 4.3454442 * RHi - 0.0090904 * Math.Pow(Tin_a, 2) - 0.3409659 * Math.Pow(RHi, 2) - 0.0007819 * Tin_a * RHi + 0.0001851 * Math.Pow(Tin_a, 3) + 0.0049274 * Math.Pow(RHi, 3) + 0.0476513 * Tin_a * Math.Pow(RHi, 2) + 0.020268209 * Math.Pow(Tin_a, 2) * RHi;
            cp_da = humidairprop.Cp(Tin_a, RHi, SourceTableData);

            double h_r        = res.href;
            double k_fin      = 237;
            double Fthickness = geo.Fthickness;
            double Pt         = geo.Pt;
            double Pr         = geo.Pr;
            double Do         = geo.Do;

            //double h_fin = (Pt - Do) / 2;
            //double dc = Do + 2 * Fthickness;
            //double df = Math.Pow(4 / Math.PI * Pt * Pr, 0.5);
            //double eta_a = 1 / (1 + ha * Math.Pow(df - dc, 2) * Math.Pow(df, 0.5) / 6 / Fthickness / k_fin / Math.Pow(dc, 0.5));
            //double m = Math.Sqrt(2 * ha / (k_fin * Fthickness));
            //double eta_a= Math.Tanh(m * h_fin) / (m * h_fin);// may cause error
            //double eta_dry = eta_surface;

            double r_eta = Do / 2;
            double XD    = Math.Pow((Pr * Pr + Pt * Pt / 4), 0.5) / 2;
            double XT    = Pt / 2;
            double rf_r  = 1.27 * XT / r_eta * Math.Pow((XD / XT - 0.3), 0.5);
            double m     = Math.Pow((2 * ha / k_fin / Fthickness), 0.5);
            double fai   = (rf_r - 1) * (1 + (0.3 + Math.Pow((m * r_eta * (rf_r - r_eta) / 2.5), (1.5 - 1 / 12 * rf_r)) * (0.26 * Math.Pow(rf_r, 0.3) - 0.3)) * Math.Log(rf_r));
            double eta_0 = Math.Tanh(m * r_eta * fai) / m / r_eta / fai * Math.Cos(0.1 * m * r_eta * fai);
            double eta_a = (eta_0 * Aa_fin + Aa_tube) / (Aa_fin + Aa_tube);

            double UA_i        = h_r * Ar;
            double UA_o        = eta_a * (Aa_fin + Aa_tube) * ha;
            double Ntu_i       = UA_i / (mr * cp_r);
            double Ntu_o       = UA_o / (ma * cp_da);
            double UA          = 1 / (1 / (UA_i) + 1 / (UA_o) + r_metal);
            double Cmin        = Math.Min(cp_r * mr, cp_da * ma);
            double Cmax        = Math.Max(cp_r * mr, cp_da * ma);
            double C_star      = Cmin / Cmax;
            double Ntu_dry     = UA / Cmin;
            double epsilon_dry = (1 - Math.Exp(-Ntu_dry * (1 - C_star))) / (1 - C_star * Math.Exp(-Ntu_dry * (1 - C_star)));
            double Q_dry       = epsilon_dry * Cmin * (Tin_a - Tin_r) * Math.Pow(-1, hexType);//need to be modified//所以蒸发器算不出Q
            double Tout_a_dry  = Tin_a - Q_dry / (ma * cp_da) * Math.Pow(-1, hexType);
            double Tout_r      = Tin_r + Q_dry / (mr * cp_r) * Math.Pow(-1, hexType);
            double Tout_s      = (UA_o * Tout_a_dry + UA_i * Tin_r) / (UA_o + UA_i);
            double Tin_s       = (UA_o * Tin_a + UA_i * Tout_r) / (UA_o + UA_i);
            double Tout_r_dry  = Tout_r;
            double f_dry       = 1.0;
            //double omega_in0 = CoolProp.HAPropsSI("W", "T", Tin_a + 273.15, "P", 101325, "R", RHi);
            //double omega_in = (-0.0682340 + 0.0292341 * Tin_a + 4.1604535 * RHi - 0.0025985 * Math.Pow(Tin_a, 2) - 0.0769009 * Math.Pow(RHi, 2) + 0.1246489 * Tin_a * RHi + 6.008 * Math.Pow(10, -5) * Math.Pow(Tin_a, 3) - 0.0006775 * Math.Pow(RHi, 3) + 0.0267183 * Tin_a * Math.Pow(RHi, 2) + 0.019904969 * Math.Pow(Tin_a, 2) * RHi) / 1000;
            double omega_in = humidairprop.O(Tin_a, RHi, SourceTableData);

            //double omega_out = omega_in;
            double hin_a = 0;

            if (hexType == 0 && tri < tai)
            {
                bool isFullyWet = true;
                //double hin_a0 = CoolProp.HAPropsSI("H", "T", Tin_a + 273.15, "P", 101325, "R", RHi);
                //hin_a = -244.2924077 + 1135.8711 * Tin_a + 10101.404 * RHi - 12.968219 * Math.Pow(Tin_a, 2) - 11.356807 * Math.Pow(RHi, 2) + 357.25464 * Tin_a * RHi + 0.3178346 * Math.Pow(Tin_a, 3) - 0.0024329 * Math.Pow(RHi, 3) + 44.100799 * Tin_a * Math.Pow(RHi, 2) + 50.31444812 * Math.Pow(Tin_a, 2) * RHi;
                hin_a = humidairprop.H(Tin_a, "R", RHi, SourceTableData);

                double hout_a = hin_a - Q_dry / ma * Math.Pow(-1, hexType);

                //double Tdp0 = CoolProp.HAPropsSI("D", "T", Tin_a + 273.15, "P", 101325, "R", RHi) - 273.15;
                //double Tdp = -273.15 + 241.0212518 + 0.5718833 * tai + 84.99553 * RHi + 0.002691 * Math.Pow(tai, 2) - 95.003186 * Math.Pow(RHi, 2) + 0.7135779 * tai * RHi - 2.691 / Math.Pow(10, 5) * Math.Pow(tai, 3) + 42.58183 * Math.Pow(RHi, 3) - 0.3227474 * tai * Math.Pow(RHi, 2) - 0.000884612 * Math.Pow(tai, 2) * RHi;
                double Tdp = humidairprop.Tdp(Tin_a, RHi, SourceTableData);

                //***delete***//
                //res.RHout = CoolProp.HAPropsSI("R", "T", Tout_a_dry + 273.15, "P", 101325, "W", omega_out);
                //res.RHout = 0.0215344 - 0.0059467 * Tout_a_dry + 0.2386894 * (omega_out * 1000) + 0.0004378 * Math.Pow(Tout_a_dry, 2) + 0.0004635 * Math.Pow((omega_out * 1000), 2) - 0.0125912 * Tout_a_dry * (omega_out * 1000) - 9.134 * Math.Pow(10, -6) * Math.Pow(Tout_a_dry, 3) + 1.696 * Math.Pow(10, -6) * Math.Pow((omega_out * 1000), 3) - 2.214 * Math.Pow(10, -5) * Tout_a_dry * Math.Pow((omega_out * 1000), 2) + 0.000200865 * Math.Pow(Tout_a_dry, 2) * (omega_out * 1000);
                //***delete***//

                //res.RHout = CoolProp.HAPropsSI("R", "T", Tout_a_dry + 273.15, "P", 101325, "H", hout_a);
                //double resRHout0 = CoolProp.HAPropsSI("R", "T", Tout_a_dry + 273.15, "P", 101325, "H", hout_a);
                //res.RHout = 0.0259124 - 0.0996818 * Tout_a_dry + 0.0934877 * (hout_a / 1000) + 0.0040018 * Math.Pow(Tout_a_dry, 2) - 0.0003662 * Math.Pow((hout_a / 1000), 2) - 0.0034077 * Tout_a_dry * (hout_a / 1000) - 1.76447 * Math.Pow(10, -5) * Math.Pow(Tout_a_dry, 3) - 2.74524 * Math.Pow(10, -6) * Math.Pow((hout_a / 1000), 3) + 2.99291 * Math.Pow(10, -5) * Tout_a_dry * Math.Pow((hout_a / 1000), 2) - 9.56644 * Math.Pow(10, -6) * Math.Pow(Tout_a_dry, 2) * (hout_a / 1000);
                //double Tdp_out0 = CoolProp.HAPropsSI("T", "H", hout_a, "P", 101325, "R", 1.0) - 273.15;//@@@@@@@@@@@@@@@@@@@@@@@@@@
                double Tdp_out = humidairprop.Ts(hout_a / 1000, SourceTableData);
                res.RHout = humidairprop.RHI(Tout_a_dry, Tdp_out, SourceTableData);
                Tout_a    = Tout_a_dry;
                Q         = Q_dry;
                if (Tin_s < Tdp)
                {
                    isFullyWet = true;
                }
                else
                {
                    isFullyWet = false;
                }
                if (Tout_s < Tdp | isFullyWet == true)
                {
                    double x1 = Tin_r + 0.001;
                    double x2 = Tin_a - 0.001;
                    double eps = 1e-8;
                    int    iter = 1;
                    double change = 999;
                    double y1 = 0, y2 = 0, x3 = 0;
                    double m_star = 0, epsilon_wet = 0, h_s_w_i = 0, h_s_w_o = 0, h_s_s_e = 0, T_s_e = 0, h_a_x = 0, T_a_x = 0;
                    double Q_wet = 0, Ntu_owet = 0, mdot_min = 0;
                    double Ntu_wet = 0;
                    while ((iter <= 3 | change > eps) && iter < 100)
                    {
                        if (iter == 1)
                        {
                            Tout_r = x1;
                        }
                        if (iter > 1)
                        {
                            Tout_r = x2;
                        }
                        double Tout_r_start = Tout_r;
                        //double h_s_w_i0 = CoolProp.HAPropsSI("H", "T", Tin_r + 273.15, "P", 101325, "R", 1.0);
                        //h_s_w_i = 58.732687 * Math.Pow(Tin_r + 273.15, 2) - 30921.970577 * (Tin_r + 273.15) + 4075493.951473;
                        h_s_w_i = humidairprop.H(Tin_r, "R", 1, SourceTableData);
                        ///////
                        //double h10 = 58.732687 * Math.Pow((Tin_r + Tout_r) / 2 + 273.15 + 0.01, 2) - 30921.970577 * ((Tin_r + Tout_r) / 2 + 273.15 + 0.01) + 4075493.951473;
                        double h1 = humidairprop.H((Tin_r + Tout_r) / 2 + 0.01, "R", 1, SourceTableData);
                        //double h20 = 58.732687 * Math.Pow((Tin_r + Tout_r) / 2 + 273.15, 2) - 30921.970577 * ((Tin_r + Tout_r) / 2 + 273.15 ) + 4075493.951473;
                        double h2  = humidairprop.H((Tin_r + Tout_r) / 2, "R", 1, SourceTableData);
                        double c_s = (h1 - h2) / 0.01;
                        //double c_s = (CoolProp.HAPropsSI("H", "T", (Tin_r + Tout_r) / 2 + 273.15 + 0.01, "P", 101325, "R", 1) - CoolProp.HAPropsSI("H", "T", (Tin_r + Tout_r) / 2 + 273.15, "P", 101325, "R", 1)) / 0.01;

                        //double c_s = 2500;
                        //m = Math.Sqrt(2 * ha*c_s/cp_da / (k_fin * Fthickness));
                        //eta_a= Math.Tanh(m * h_fin) / (m * h_fin);// may cause error
                        //double m_star=ma/(mr*(cp_r/c_s));
                        //eta_a = eta_a * c_s / cp_da;
                        m     = Math.Pow((2 * haw / k_fin / Fthickness), 0.5);
                        fai   = (rf_r - 1) * (1 + (0.3 + Math.Pow((m * r_eta * (rf_r - r_eta) / 2.5), (1.5 - 1 / 12 * rf_r)) * (0.26 * Math.Pow(rf_r, 0.3) - 0.3)) * Math.Log(rf_r));
                        eta_0 = Math.Tanh(m * r_eta * fai) / m / r_eta / fai * Math.Cos(0.1 * m * r_eta * fai);
                        double eta_wet = (eta_0 * Aa_fin + Aa_tube) / (Aa_fin + Aa_tube);
                        Ntu_owet = (eta_0 * Aa_fin + Aa_tube) * haw / (ma * cp_da);//zzc
                        m_star   = Math.Min(cp_r * mr / c_s, ma) / Math.Max(cp_r * mr / c_s, ma);
                        mdot_min = Math.Min(cp_r * mr / c_s, ma);
                        Ntu_wet  = Ntu_owet / (1 + m_star * (Ntu_owet / Ntu_i));//zzc
                        if (cp_r * mr > c_s * ma)
                        {
                            Ntu_wet = Ntu_owet / (1 + m_star * (Ntu_owet / Ntu_i));//zzc
                        }
                        else
                        {
                            Ntu_wet = Ntu_i / (1 + m_star * (Ntu_i / Ntu_owet));
                        }
                        epsilon_wet = ((1 - Math.Exp(-Ntu_wet * (1 - m_star))) / (1 - m_star * Math.Exp(-Ntu_wet * (1 - m_star))));
                        Q_wet       = epsilon_wet * mdot_min * (hin_a - h_s_w_i);
                        hout_a      = hin_a - Q_wet / ma;
                        Tout_r      = Tin_r + ma / (mr * cp_r) * (hin_a - hout_a);

                        //double h_s_w_o0 = CoolProp.HAPropsSI("H", "T", Tout_r + 273.15, "P", 101325, "R", 1.0);
                        //h_s_w_o = 58.732687 * Math.Pow(Tout_r + 273.15, 2) - 30921.970577 * (Tout_r + 273.15) + 4075493.951473;
                        h_s_w_o = humidairprop.H(Tout_r, "R", 1, SourceTableData);

                        //double UA_star = 1 / (cp_da / (eta_a * Aa_fin + Aa_tube) / haw + CoolProp.HAPropsSI("C", "T", (Tin_a + Tout_r) / 2.0 + 273.15, "P", 101325, "R", 1) / h_r / Ar);//zzc
                        double UA_star = 1 / (cp_da / (eta_a * Aa_fin + Aa_tube) / haw + c_s / h_r / Ar); //zzc
                        Tin_s   = Tout_r + UA_star / h_r / Ar * (hin_a - h_s_w_o);
                        h_s_s_e = hin_a + (hout_a - hin_a) / (1 - Math.Exp(-Ntu_owet));                   //zzc

                        //double T_s_e0 = CoolProp.HAPropsSI("T", "H", h_s_s_e, "P", 101325, "R", 1.0) - 273.15;
                        //T_s_e = -273.15 - 1.96 * Math.Pow(10, -3) * Math.Pow(h_s_s_e / 1000, 2) + 0.5357597 * h_s_s_e / 1000 + 268.871551;
                        T_s_e = humidairprop.Ts(h_s_s_e, SourceTableData);

                        Tout_a     = T_s_e + (Tin_a - T_s_e) * Math.Exp(-Ntu_owet);//zzc
                        Q_sensible = ma * cp_da * (Tin_a - Tout_a);
                        double errorToutr = Tout_r - Tout_r_start;
                        if (iter == 1)
                        {
                            y1 = errorToutr;
                        }
                        if (iter > 1)
                        {
                            y2     = errorToutr;
                            x3     = x2 - y2 / (y2 - y1) * (x2 - x1);
                            change = Math.Abs(y2 / (y2 - y1) * (x2 - x1));
                            y1     = y2;
                            x1     = x2;
                            x2     = x3;
                        }
                        iter++;
                    }
                    //if (iter > 500)
                    //    Q = Q_dry;
                    double Tout_r_wet = Tout_r;
                    f_dry = 0.0;
                    if ((Tin_s > Tdp) && isFullyWet == false)
                    {
                        double iter1        = 1;
                        double error        = 1;
                        double Tout_r_guess = 0;
                        x1  = 0.0001;
                        x2  = 0.9999;
                        eps = 1e-8;
                        while ((iter1 <= 3 | change > eps) && iter < 100)
                        {
                            if (iter1 == 1)
                            {
                                f_dry = x1;
                            }
                            if (iter1 > 1)
                            {
                                f_dry = x2;
                            }
                            double K    = Ntu_dry * (1.0 - C_star);
                            double expk = Math.Exp(-K * f_dry);
                            if (cp_da * ma < cp_r * mr)
                            {
                                Tout_r_guess = (Tdp + C_star * (Tin_a - Tdp) - expk * (1 - K / Ntu_o) * Tin_a) / (1 - expk * (1 - K / Ntu_o));//zzc
                            }
                            else
                            {
                                Tout_r_guess = (expk * (Tin_a + (C_star - 1) * Tdp) - C_star * (1 + K / Ntu_o) * Tin_a) / (expk * C_star - C_star * (1 + K / Ntu_o));//zzc
                            }
                            epsilon_dry = ((1 - Math.Exp(-f_dry * Ntu_dry * (1 - C_star))) / (1 - C_star * Math.Exp(-f_dry * Ntu_dry * (1 - C_star))));
                            epsilon_wet = ((1 - Math.Exp(-(1 - f_dry) * Ntu_wet * (1 - m_star))) / (1 - m_star * Math.Exp(-(1 - f_dry) * Ntu_wet * (1 - m_star))));
                            double T_w_x = (Tin_r + (mdot_min) / (cp_r * mr) * epsilon_wet * (hin_a - h_s_w_i - epsilon_dry * Cmin / ma * Tin_a)) / (1 - (Cmin * mdot_min) / (cp_r * mr * ma) * epsilon_wet * epsilon_dry);
                            T_a_x  = Tin_a - epsilon_dry * Cmin * (Tin_a - T_w_x) / (ma * cp_da);
                            h_a_x  = hin_a - cp_da * (Tin_a - T_a_x);
                            Tout_r = (Cmin) / (cp_r * mr) * epsilon_dry * Tin_a + (1 - (Cmin) / (cp_r * mr) * epsilon_dry) * T_w_x;
                            error  = Tout_r - Tout_r_guess;
                            if (iter1 > 500)
                            {
                                Q = Q_dry;
                            }
                            if (iter1 == 1)
                            {
                                y1 = error;
                            }
                            if (iter1 > 1)
                            {
                                y2     = error;
                                x3     = x2 - y2 / (y2 - y1) * (x2 - x1);
                                change = Math.Abs(y2 / (y2 - y1) * (x2 - x1));
                                y1     = y2;
                                x1     = x2;
                                x2     = x3;
                            }
                            iter1++;
                        }
                        //if (iter1 > 500)
                        //    Q = Q_dry;
                        Q       = mr * cp_r * (Tout_r - Tin_r);
                        hout_a  = hin_a - Q / ma;
                        h_s_s_e = h_a_x + (hout_a - h_a_x) / (1 - Math.Exp(-(1 - f_dry) * Ntu_owet));//zzc
                        //double T_s_e0 = CoolProp.HAPropsSI("T", "H", h_s_s_e, "P", 101325, "R", 1.0) - 273.15;////////////////
                        //T_s_e = -273.15 - 1.96 * Math.Pow(10, -3) * Math.Pow(h_s_s_e / 1000, 2) + 0.5357597 * h_s_s_e / 1000 + 268.871551;
                        T_s_e      = humidairprop.Ts(h_s_s_e, SourceTableData);
                        Tout_a     = T_s_e + (T_a_x - T_s_e) * Math.Exp(-(1 - f_dry) * Ntu_owet);//zzc
                        Q_sensible = ma * cp_da * (Tin_a - Tout_a);
                    }
                    else
                    {
                        Q = Q_wet;
                    }
                    //res.RHout = CoolProp.HAPropsSI("R", "T", Tout_a + 273.15, "P", 101325, "H", hout_a);
                    //double  resRHout1 = CoolProp.HAPropsSI("R", "T", Tout_a + 273.15, "P", 101325, "H", hout_a);
                    //res.RHout = 0.0259124 - 0.0996818 * Tout_a + 0.0934877 * (hout_a / 1000) + 0.0040018 * Math.Pow(Tout_a, 2) - 0.0003662 * Math.Pow((hout_a / 1000), 2) - 0.0034077 * Tout_a * (hout_a / 1000) - 1.76447 * Math.Pow(10, -5) * Math.Pow(Tout_a, 3) - 2.74524 * Math.Pow(10, -6) * Math.Pow((hout_a / 1000), 3) + 2.99291 * Math.Pow(10, -5) * Tout_a * Math.Pow((hout_a / 1000), 2) - 9.56644 * Math.Pow(10, -6) * Math.Pow(Tout_a, 2) * (hout_a / 1000);
                    Tdp_out   = humidairprop.Ts(hout_a, SourceTableData);
                    res.RHout = humidairprop.RHI(Tout_a, Tdp_out, SourceTableData);
                    if (res.RHout > 1)
                    {
                        //res.RHout = 1;
                        //double Tout_a0 = CoolProp.HAPropsSI("T", "H", hout_a, "P", 101325, "R", 1)-273.15;
                        //Tout_a = -273.15 - 1.96 * Math.Pow(10, -3) * Math.Pow(hout_a / 1000, 2) + 0.5357597 * hout_a / 1000 + 268.871551;
                        //Tdp_out0 = CoolProp.HAPropsSI("T", "H", hout_a, "P", 101325, "R", 1.0) - 273.15;//@@@
                        Tout_a     = humidairprop.Ts(hout_a, SourceTableData);
                        Q_sensible = ma * cp_da * (Tin_a - Tout_a);
                    }
                }
            }
            else
            {
                Tout_a     = Tout_a_dry;
                Q          = Q_dry;
                Q_sensible = Q_dry;

                double hout_a = hin_a - Q / ma * Math.Pow(-1, hexType);

                //***delete***//
                //res.RHout = CoolProp.HAPropsSI("R", "T", Tout_a + 273.15, "P", 101325, "W", omega_out);
                //res.RHout = 0.0215344 - 0.0059467 * Tout_a + 0.2386894 * (omega_out * 1000) + 0.0004378 * Math.Pow(Tout_a, 2) + 0.0004635 * Math.Pow((omega_out * 1000), 2) - 0.0125912 * Tout_a * (omega_out * 1000) - 9.134 * Math.Pow(10, -6) * Math.Pow(Tout_a, 3) + 1.696 * Math.Pow(10, -6) * Math.Pow((omega_out * 1000), 3) - 2.214 * Math.Pow(10, -5) * Tout_a * Math.Pow((omega_out * 1000), 2) + 0.000200865 * Math.Pow(Tout_a, 2) * (omega_out * 1000);
                //***delete***//

                //res.RHout = CoolProp.HAPropsSI("R", "T", Tout_a + 273.15, "P", 101325, "H", hout_a);
                //double resRHout0 = CoolProp.HAPropsSI("R", "T", Tout_a + 273.15, "P", 101325, "H", hout_a);
                //res.RHout = 0.0259124 - 0.0996818 * Tout_a + 0.0934877 * (hout_a / 1000) + 0.0040018 * Math.Pow(Tout_a, 2) - 0.0003662 * Math.Pow((hout_a / 1000), 2) - 0.0034077 * Tout_a * (hout_a / 1000) - 1.76447 * Math.Pow(10, -5) * Math.Pow(Tout_a, 3) - 2.74524 * Math.Pow(10, -6) * Math.Pow((hout_a / 1000), 3) + 2.99291 * Math.Pow(10, -5) * Tout_a * Math.Pow((hout_a / 1000), 2) - 9.56644 * Math.Pow(10, -6) * Math.Pow(Tout_a, 2) * (hout_a / 1000);
                //double Tdp_out0 = CoolProp.HAPropsSI("T", "H", hout_a, "P", 101325, "R", 1.0) - 273.15;//@@@
                double Tdp_out = humidairprop.Ts(hout_a, SourceTableData);
                res.RHout = humidairprop.RHI(Tout_a, Tdp_out, SourceTableData);
            }
            res.Tao = Tout_a;
            res.Tro = Tout_r;
            res.Q   = Q / 1000;
            //res.hro = (hri + Math.Pow(-1, hexType) * res.Q / mr);
            double f_sp = RefrigerantSPDP.ff_Friction(Re_r);

            res.DP  = zdp * f_sp * l / dh * Math.Pow(g, 2.0) / rho_r / 2000;
            res.Pro = fluid == "Water" ? pri : pri - res.DP;
            if (res.Pro < 0)
            {
                res.Pro = -10000000; return(res);
            }
            res.hro  = hri + Math.Pow(-1, hexType) * res.Q / mr;
            res.R_1a = 1 / ((eta_0 * Aa_fin + Aa_tube) * ha);
            res.R_1r = 1 / (res.href * Ar);
            res.R_1  = res.R_1a + res.R_1r + r_metal;
            if (fluid != "Water")
            {
                coolprop.update(input_pairs.HmassP_INPUTS, res.hro * 1000, res.Pro * 1000);
                res.Tro = coolprop.T() - 273.15;
                //res.Tro = CoolProp.PropsSI("T", "P", res.Pro * 1000, "H", res.hro * 1000, fluid) - 273.15;
            }

            return(res);
        }
Example #52
0
        public void DrawGeometry(Brush brush, Pen pen, Geometry geometry)
        {
            // Ignore total transparent primitive
            if (Utility.IsTransparent(_opacity) || ((brush == null) && (pen == null || pen.Brush == null)) || (geometry == null))
            {
                return;
            }

            // Split if having both pen and brush
            if ((brush != null) && (pen != null))
            // if (!Utility.IsOpaque(_opacity) || (_opacityMask != null))
            {
                // Push a canvas to handle geometry with brush + pen properly
                Push(Matrix.Identity, null, 1.0, null, Rect.Empty, false);

                DrawGeometry(brush, null, geometry);
                DrawGeometry(null, pen, geometry);

                Pop();

                return;
            }

            AssertState(DeviceState.PageStarted, DeviceState.NoChange);

            GeometryPrimitive g = new GeometryPrimitive();

            g.Geometry    = geometry;
            g.Clip        = _clip;
            g.Opacity     = _opacity;
            g.OpacityMask = _opacityMask;

            int needBounds = 0; // 1 for fill, 2 for stroke

            if (brush != null)
            {
                // Fix bug 1427695: Need bounds for non-SolidColorBrushes to enable rebuilding Brush from BrushProxy.
                if (!(brush is SolidColorBrush))
                {
                    needBounds |= 1;
                }
            }

            if ((pen != null) && (pen.Brush != null))
            {
                if (!(pen.Brush is SolidColorBrush))
                {
                    needBounds |= 2;
                }
            }

            if (g.OpacityMask != null)
            {
                if (g.OpacityMask.BrushList == null && !(g.OpacityMask.Brush is SolidColorBrush))
                {
                    if (pen != null)
                    {
                        needBounds |= 2;
                    }
                    else
                    {
                        needBounds |= 1;
                    }
                }
            }

            Rect bounds = g.GetRectBounds((needBounds & 1) != 0);

            if (brush != null)
            {
                g.Brush = BrushProxy.CreateBrush(brush, bounds);
            }

            if ((needBounds & 2) != 0)
            {
                bounds = geometry.GetRenderBounds(pen);
            }

            if ((pen != null) && (pen.Brush != null))
            {
                g.Pen = PenProxy.CreatePen(pen, bounds);
            }

            if (g.OpacityMask != null)
            {
                if (!g.OpacityMask.MakeBrushAbsolute(bounds))
                {
                    // Fix bug 1463955: Brush has become empty; replace with transparent brush.
                    g.OpacityMask = BrushProxy.CreateColorBrush(Colors.Transparent);
                }
            }

            // Optimization: Unfold primitive DrawingBrush when possible to avoid rasterizing it.
            Primitive primitive = g.UnfoldDrawingBrush();

            if (primitive != null)
            {
                _root.Children.Add(primitive);
            }
        }
Example #53
0
        private List <IChartInteractiveObject> GetObjectUnderCursorPaneCoords(Point ptClient, int tolerance)
        {
            var list = new List <IChartInteractiveObject>();

            foreach (var line in data)
            {
                if (!line.Completed)
                {
                    continue;
                }
                var a = Conversion.WorldToScreen(new PointD(line.linePoints[0].X, line.linePoints[0].Y),
                                                 Owner.WorldRect, Owner.CanvasRect);
                var b = Conversion.WorldToScreen(new PointD(line.linePoints[1].X, line.linePoints[1].Y),
                                                 Owner.WorldRect, Owner.CanvasRect);
                var ptClientD = new PointD(ptClient.X, ptClient.Y);

                // проверить попадание в линию
                if (line.LineStyle == TrendLine.TrendLineStyle.Линия ||
                    line.LineStyle == TrendLine.TrendLineStyle.ЛинияСМаркерами)
                {
                    if (Geometry.IsDotOnLine(ptClientD, a, b, tolerance))
                    {
                        list.Add(line);
                    }
                    continue;
                }

                // проверить попадание в отрезок
                if (line.LineStyle == TrendLine.TrendLineStyle.Отрезок ||
                    line.LineStyle == TrendLine.TrendLineStyle.Стрелка ||
                    line.LineStyle == TrendLine.TrendLineStyle.ОтрезокСМаркерами)
                {
                    if (Geometry.IsDotOnSpan(ptClientD, a, b, tolerance))
                    {
                        list.Add(line);
                    }
                    continue;
                }

                // с прямоугольником все просто - попадание в область
                if (line.LineStyle == TrendLine.TrendLineStyle.Прямоугольник)
                {
                    if (Geometry.IsDotInArea(ptClientD, a, b, tolerance))
                    {
                        list.Add(line);
                    }
                    continue;
                }
                // маленький объект на свече
                if (line.LineStyle == TrendLine.TrendLineStyle.СвечнаяСтрелка)
                {
                    if (Geometry.IsDotInArea(ptClientD,
                                             new PointD(b.X - 1, b.Y), new PointD(b.X + 1, b.Y + 4), tolerance))
                    {
                        list.Add(line);
                    }
                    continue;
                }

                // проверить попадание в произвольную фигуру
                if (line.IsInObject(a, b, ptClient, tolerance))
                {
                    list.Add(line);
                }
                //if (Geometry.IsDotInArea(ptClientD, a, b, tolerance))
            }
            return(list);
        }
Example #54
0
        public static CalcResult ElementCalc(string fluid, double l, double Aa_fin, double Aa_tube, double A_r_cs, double Ar, Geometry geo, double tai,
                                             double RHi, double tri, double pri, double hri, double mr, double g, double ma, double ha, double haw,
                                             double eta_surface, double zh, double zdp, int hexType, double thickness, double conductivity, double Pwater, AbstractState coolprop)
        {
            //AbstractState coolprop = AbstractState.factory("HEOS", fluid);

            double     dh      = geo.Di;
            double     r_metal = thickness / conductivity / Ar;
            double     gg      = 9.8;
            CalcResult res     = new CalcResult();

            coolprop.update(input_pairs.HmassP_INPUTS, hri * 1000, (fluid == "Water" ? Pwater : pri) * 1000);
            double mu_r = coolprop.viscosity();
            //double mu_r = CoolProp.PropsSI("V", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double k_r = coolprop.conductivity();
            //double k_r = CoolProp.PropsSI("L", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double rho_r = coolprop.rhomass();
            //double rho_r = CoolProp.PropsSI("D", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double cp_r = coolprop.cpmass();
            //double cp_r = CoolProp.PropsSI("C", "H", hri * 1000, "P", (fluid == "Water" ? Pwater : pri) * 1000, fluid);
            double Pr_r = cp_r * mu_r / k_r;

            //for debugging, to check if the 1ph property is in 2ph region but not in 1ph, ruhao20180209

            /*
             * var rr = new Refrigerant.SATTTotalResult();
             * rr = Refrigerant.SATTTotal(fluid, composition, Refrigerant.SATP(fluid, composition, pri, 1).Temperature).SATTTotalResult; //satruration temperature
             * if ( rho_r > rr.DensityV && rho_r < rr.DensityL)
             * {
             *  throw new Exception("property is not in 1ph region");
             * }
             */
            res.Vel_r = g / rho_r;
            double Re_r    = rho_r * res.Vel_r * dh / mu_r;
            double fh      = RefrigerantSPHTC.ff_CHURCHILL(Re_r);
            double Nusselt = RefrigerantSPHTC.NU_GNIELINSKI(Re_r, Pr_r, fh);

            res.href = Nusselt * k_r / dh * zh;
            double cp_a = 1.0;

            cp_a = (hexType == 0 ? 1.027 : 1.02);
            double C_r = mr * cp_r / 1000;
            double C_a = ma * cp_a;

            res.R_1a = 1 / ((eta_surface * Aa_fin + Aa_tube) * ha);
            res.R_1r = 1 / (res.href * Ar);
            res.R_1  = res.R_1a + res.R_1r + r_metal;
            double UA      = 1 / res.R_1;
            double C_min   = Math.Min(C_a, C_r);
            double C_max   = Math.Max(C_a, C_r);
            double C_ratio = C_min / C_max;
            double NTU     = UA / (C_min * 1000);
            //流体不混合的一次交叉流
            //double epsilon_jc = 1 - Math.Exp(Math.Pow(C_ratio,-1.0)*Math.Pow(NTU,0.22)
            //*(Math.Exp(-C_ratio*Math.Pow(NTU,0.78))-1));
            //顺流计算公式
            //double epsilon_downflow = (1 - Math.Exp(-NTU * (1 + C_ratio))) / (1 + C_ratio);
            //逆流计算公式
            double epsilon_counterflow = (1 - Math.Exp(-NTU * (1 - C_ratio))) / (1 - C_ratio * Math.Exp(-NTU * (1 - C_ratio)));

            double epsilon = epsilon_counterflow;

            res.Q = epsilon * C_min * (tai - tri) * Math.Pow(-1, hexType);
            if (C_r < C_a)
            {                                                  // hexType=0 :evap, 1:cond
                res.Tro = tri + epsilon * (tai - tri);         //Math.Abs(tai - tri);
                res.Tao = tai - C_r * ((res.Tro - tri) / C_a); //Math.Abs(res.Tro - tri)
            }
            else
            {
                res.Tao = tai - epsilon * (tai - tri);         //Math.Abs(tai - tri)
                res.Tro = tri + C_a * ((tai - res.Tao) / C_r); //(Math.Abs(tai - res.Tao) / C_r)
            }
            double f_sp = RefrigerantSPDP.ff_Friction(Re_r);

            res.DP  = zdp * f_sp * l / dh * Math.Pow(g, 2.0) / rho_r / 2000;
            res.Pro = fluid == "Water" ? pri : pri - res.DP;
            if (res.Pro < 0)
            {
                res.Pro = -10000000; return(res);
            }
            res.hro = hri + Math.Pow(-1, hexType) * res.Q / mr;
            //re-calc tro for refrigerant to avoid Tro < Tsat
            if (fluid != "Water")
            {
                coolprop.update(input_pairs.HmassP_INPUTS, res.hro * 1000, res.Pro * 1000);
                res.Tro = coolprop.T() - 273.15;
                //res.Tro = CoolProp.PropsSI("T", "P", res.Pro * 1000, "H", res.hro * 1000, fluid) - 273.15;
            }

            res.RHout = 1.1 * RHi;

            string arr1 = Convert.ToString(res.Q);

            Console.WriteLine("Q={0}", arr1);
            return(res);
        }
Example #55
0
 public void CurveToLine(TestCase testCase)
 {
     Geometry.Deserialize <WktSerializer>(testCase.Data.Wkt).CurveToLine(1e-6);
 }
Example #56
0
        // Create a single PDF file
        void CreateOnePdfFile(string fileName, IEnumerable <CourseDesignator> courseDesignators)
        {
            List <CoursePage> pages     = LayoutPages(courseDesignators);
            PdfWriter         pdfWriter = new PdfWriter(Path.GetFileNameWithoutExtension(fileName), coursePdfSettings.ColorModel == ColorModel.CMYK);

            IGraphicsTarget grTarget = null;

            foreach (CoursePage page in pages)
            {
                CoursePage pageToDraw = page;

                SizeF paperSize = new SizeF(pageToDraw.paperSize.Width / 100F, pageToDraw.paperSize.Height / 100F);
                if (pageToDraw.landscape)
                {
                    paperSize = new SizeF(paperSize.Height, paperSize.Width);
                }

                if (controller.UpdateProgressDialog(string.Format(MiscText.CreatingFile, Path.GetFileName(fileName)), (double)currentPage / (double)totalPages))
                {
                    throw new Exception(MiscText.CancelledByUser);
                }

                PdfImporter pdfImporter = null;

                if (IsPdfMap)
                {
                    // We need to re-obtain a PdfImporter every time, or else very strange bugs start to crop up.

                    pdfImporter = new PdfImporter(sourcePdfMapFileName);

                    float scaleRatio = CourseView.CreatePrintingCourseView(eventDB, page.courseDesignator).ScaleRatio;
                    if (scaleRatio == 1.0)
                    {
                        // If we're doing a PDF at scale 1, we just copy the page directly.
                        grTarget   = pdfWriter.BeginCopiedPage(pdfImporter, 0);
                        pageToDraw = PdfNonScaledPage(page.courseDesignator);
                    }
                    else
                    {
                        Matrix     transform = Geometry.CreateInvertedRectangleTransform(page.printRectangle, page.mapRectangle);
                        RectangleF printedPortionInMapCoords = Geometry.TransformRectangle(transform, new RectangleF(0, 0, paperSize.Width * 100F, paperSize.Height * 100F));
                        RectangleF printedPortionInInches    = new RectangleF(
                            Geometry.InchesFromMm(printedPortionInMapCoords.Left),
                            Geometry.InchesFromMm(mapBounds.Height - printedPortionInMapCoords.Bottom),
                            Geometry.InchesFromMm(printedPortionInMapCoords.Width),
                            Geometry.InchesFromMm(printedPortionInMapCoords.Height));

                        grTarget = pdfWriter.BeginCopiedPartialPage(pdfImporter, 0, paperSize, printedPortionInInches);
                    }

                    // Don't draw the map normally.
                    mapDisplay.SetMapFile(MapType.None, null);
                }
                else
                {
                    if (page.startNewPage || grTarget == null)
                    {
                        if (grTarget != null)
                        {
                            pdfWriter.EndPage(grTarget);
                            grTarget.Dispose();
                            grTarget = null;
                        }
                        grTarget = pdfWriter.BeginPage(paperSize);
                    }
                }

                DrawPage(grTarget, pageToDraw);

                if (pdfImporter != null)
                {
                    pdfImporter.Dispose();
                    pdfImporter = null;
                }

                currentPage += 1;
            }
            if (grTarget != null)
            {
                pdfWriter.EndPage(grTarget);
                grTarget.Dispose();
                grTarget = null;
            }

            pdfWriter.Save(fileName);
        }
Example #57
0
 public static int GetDimension(this Geometry geometry)
 {
     throw new SpatialLinqMethodException();
 }
Example #58
0
 public static Geometry Simplify(this Geometry geometry, double distance)
 {
     throw new SpatialLinqMethodException();
 }
Example #59
0
 /// <summary>
 /// A fully compatible null checking. Use instead of " == null " expression.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Using an equality to null lambda expression throws an exception in SQL Server
 /// ("Invalid operator for data type. Operator equals equal to, type equals geometry.")
 /// because NHibernate is generating an HQL expression like this:
 /// </para>
 /// <code>
 ///     (t.geom is null) and (null is null) or t.geom = null
 /// </code>
 /// <para>
 /// Using this extension method, we generate just the following HQL:
 /// </para>
 /// <code>
 ///     t.geom is null
 /// </code>
 /// </remarks>
 /// <param name="geometry"></param>
 /// <returns></returns>
 public static bool IsNull(this Geometry geometry)
 {
     return(geometry == null);
 }
Example #60
0
 /// <summary>
 /// Constructs a <see cref="DistanceOp" /> that computes the distance and closest points between
 /// the two specified geometries.
 /// </summary>
 /// <param name="g0"></param>
 /// <param name="g1"></param>
 /// <param name="terminateDistance">The distance on which to terminate the search.</param>
 public DistanceOp(Geometry g0, Geometry g1, double terminateDistance)
 {
     _geom = new[] { g0, g1 };
     _terminateDistance = terminateDistance;
 }