/// <summary> /// Return whether the ControlTemplate can be selected for the specified size. /// </summary> /// <param name="size">The size the SizeControlTemplate is tested against.</param> /// <returns>Whether the ControlTemplate can be selected for the specified size.</returns> public bool IsSelectable(Size size) { return(DoubleUtilities.IsLessThanOrCloseTo(this.minWidth, size.Width) && DoubleUtilities.IsGreaterThanOrCloseTo(this.maxWidth, size.Width) && DoubleUtilities.IsLessThanOrCloseTo(this.minHeight, size.Height) && DoubleUtilities.IsGreaterThanOrCloseTo(this.maxHeight, size.Height)); }
/// <summary> /// Append a numeric value to the stream /// </summary> public static void AppendValue(StringBuilder output, double val) { string valstr = DoubleUtilities.FormatString(val); output.Append(valstr); output.Append(' '); }
/// <summary> /// Formats a single point /// </summary> public static string FormatPointParamter(Point point) { var xStr = DoubleUtilities.FormatString(point.X); var yStr = DoubleUtilities.FormatString(point.Y); return($"{xStr},{yStr}"); }
/// <summary> /// Application-wide handler for MouseWheel event. /// </summary> /// <param name="e">EventArgs describing the event.</param> public static void OnMouseWheel(MouseWheelEventArgs e) { if (!e.Handled && (ServiceProvider.ViewManager.Dialog == null)) { // I think this is wrong. Not changing it for now for risk of breaking something unknown... // Try removing all but the ctrl handlers for this at some time when we can afford more risk. if (!(e.OriginalSource is FlowDocumentPageViewer || e.OriginalSource is Paragraph || e.OriginalSource is FlowDocument || e.OriginalSource is Run || Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) )) { if (DoubleUtilities.IsStrictlyLessThan(e.Delta, 0)) { _SafeExecuteCommand(ServiceProvider.ViewManager.NavigationCommands.NavigateToNextCommand); } else if (DoubleUtilities.IsStrictlyGreaterThan(e.Delta, 0)) { _SafeExecuteCommand(ServiceProvider.ViewManager.NavigationCommands.NavigateToPriorCommand); } e.Handled = true; } } }
/// <summary> /// Format a point to a string /// </summary> private string FormatPoint(double x, double y) { string xstr = DoubleUtilities.FormatString(x); string ystr = DoubleUtilities.FormatString(y); return($"{xstr} {ystr}"); }
protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint) { UIElement child = this.Child; if (child != null) { //Debug.WriteLine(String.Format("MO: constraint {0} prev {1}", constraint, _previousMeasureSize)); if (this.AllowLayout || (DoubleUtilities.AreClose(this._previousMeasureSize.Width, constraint.Width) && DoubleUtilities.AreClose(this._previousMeasureSize.Height, constraint.Height))) { child.Measure(constraint); _previousMeasureSize = constraint; //Debug.WriteLine(String.Format("M: prevDes {0} Des {1}", _previousDesiredSize, child.DesiredSize)); _previousDesiredSize = child.DesiredSize; } else { //Debug.WriteLine(String.Format("MX:{0} == {1}: {2}", constraint, _previousMeasureSize, (this._previousMeasureSize == constraint))); _dt.Stop(); _dt.Start(); } } return(_previousDesiredSize); }
/// <summary> /// Format a color to a string /// </summary> /// <param name="color"></param> private string FormatColor(Color color) { var rStr = DoubleUtilities.FormatString(color.R / 255.0); var gStr = DoubleUtilities.FormatString(color.G / 255.0); var bStr = DoubleUtilities.FormatString(color.B / 255.0); return($"{rStr} {gStr} {bStr}"); }
private static IntPtr _CreateRoundRectRgn(Rect region, double radius) { if (DoubleUtilities.AreClose(0.0, radius)) { return(NativeMethods.CreateRectRgn((int)Math.Floor(region.Left), (int)Math.Floor(region.Top), (int)Math.Ceiling(region.Right), (int)Math.Ceiling(region.Bottom))); } return(NativeMethods.CreateRoundRectRgn((int)Math.Floor(region.Left), (int)Math.Floor(region.Top), (int)Math.Ceiling(region.Right) + 1, (int)Math.Ceiling(region.Bottom) + 1, (int)Math.Ceiling(radius), (int)Math.Ceiling(radius))); }
public override bool Equals(object?obj) { return(obj is HSLColor color && DoubleUtilities.AreClose(A, color.A) && DoubleUtilities.AreClose(H, color.H) && DoubleUtilities.AreClose(S, color.S) && DoubleUtilities.AreClose(L, color.L)); }
/// <summary> /// Generate the XAML Path source code for a visual /// </summary> private static void GeneratePathGroup(GraphicVisual visual, StringBuilder result, int level, GeometryGeneratorType geometryGeneratorType) { switch (visual) { case GraphicGroup group: { var tag = "Grid"; var indentTag = SourceFormatterHelper.GetTagIndent(level); result.Append($"{indentTag}<{tag}"); bool tagIndent = false; if (!DoubleUtilities.IsEqual(group.Opacity, 1.0)) { tagIndent = true; string opac = string.Format(CultureInfo.InvariantCulture, " Opacity=\"{0}\"", DoubleUtilities.FormatString(group.Opacity)); result.Append(opac); } if (group.Clip != null) { if (tagIndent) { var indentProperty = SourceFormatterHelper.GetPropertyIndent(level, tag); result.AppendLine(); result.Append(indentProperty); } else { result.Append(" "); } result.Append(string.Format("Clip=\"")); var stream = StreamSourceGenerator.GenerateStreamGeometry(group.Clip); result.Append(stream); result.Append("\""); } result.AppendLine(">"); foreach (var childVisual in group.Children) { GeneratePathGroup(childVisual, result, level + 1, geometryGeneratorType); } result.AppendLine($"{indentTag}</{tag}>"); break; } case GraphicPath graphicPath: { result.AppendLine(GeneratePath(graphicPath, false, level, geometryGeneratorType)); break; } } }
public HSLColor(Color color) { // Init Parameters A = 0; H = 0; L = 0; S = 0; var r = color.R; var g = color.G; var b = color.B; var a = color.A; var min = Math.Min(r, Math.Min(g, b)); var max = Math.Max(r, Math.Max(g, b)); var delta = max - min; // Calculate H if (delta == 0) { H = 0; } else if (r == max) { H = 60 * (((double)(g - b) / delta) % 6); } else if (g == max) { H = 60 * (((double)(b - r) / delta) + 2); } else if (b == max) { H = 60 * (((double)(r - g) / delta) + 4); } if (H < 0) { H += 360; } // Calculate L L = (1d / 2d * (max + min)) / 255d; // Calculate S if (DoubleUtilities.AreClose(L, 0) || DoubleUtilities.AreClose(L, 1)) { S = 0; } else { S = delta / (255d * (1 - Math.Abs((2 * L) - 1))); } // Calculate Alpha A = a / 255d; }
public static List <Curve> SplitCurve(Curve c, XYZ p, double shortCurveTolerance, bool preserveDirection = true) { //only lines are splited, arcs must implemented if (c != null && p != null //&& c is Line && IsPointOnCurve(c, p)) { XYZ cS = GetEndPoint(c, 0); XYZ cE = GetEndPoint(c, 1); if (!p.IsAlmostEqualTo(cS) && !p.IsAlmostEqualTo(cE) && (p.DistanceTo(cS) > shortCurveTolerance || DoubleUtilities.IsDoublesEqual(p.DistanceTo(cS), shortCurveTolerance)) && (p.DistanceTo(cE) > shortCurveTolerance || DoubleUtilities.IsDoublesEqual(p.DistanceTo(cE), shortCurveTolerance))) { Curve c1 = null; Curve c2 = null; if (c is Arc) { Arc arc = c as Arc; //XYZ center = arc.Evaluate(0.5, true); XYZ center1 = PushOnCurveByCurve(c, GetEndPoint(c, 0), VectorUtils.GetVectorOfCurve(c), cS.DistanceTo(p) / 2.0); XYZ center2 = PushOnCurveByCurve(c, GetEndPoint(c, 1), VectorUtils.GetVectorOfCurve(c).Negate(), cE.DistanceTo(p) / 2.0); c1 = Arc.Create(cS, p, center1); c2 = Arc.Create(p, cE, center2); } else { if (preserveDirection) { c1 = LineUtils.NewLineBound(cS, p) as Curve; c2 = LineUtils.NewLineBound(p, cE) as Curve; } else { c1 = LineUtils.NewLineBound(p, cS) as Curve; c2 = LineUtils.NewLineBound(p, cE) as Curve; } } if (c1 != null && c2 != null) { return(new List <Curve>() { c1, c2 }); } } } return(null); }
/// <summary> /// append a point to the stream /// </summary> public static void AppendPoint(StringBuilder output, double x, double y) { string xstr = DoubleUtilities.FormatString(x); string ystr = DoubleUtilities.FormatString(y); output.Append(xstr); output.Append(','); output.Append(ystr); output.Append(' '); }
/// <summary> /// Set the colors /// </summary> private static void SetColors(GraphicPath graphicPath, XElement pathElement, XNamespace ns, XElement definitions, ref int definitionsCount) { if (graphicPath.FillBrush != null) { GenerateBrush(graphicPath.FillBrush, pathElement, ns, "fill", definitions, ref definitionsCount); } else { pathElement.Add(new XAttribute("fill", "none")); } if (graphicPath.StrokeBrush != null) { GenerateBrush(graphicPath.StrokeBrush, pathElement, ns, "stroke", definitions, ref definitionsCount); pathElement.Add(new XAttribute("stroke-width", DoubleUtilities.FormatString(graphicPath.StrokeThickness))); if (graphicPath.StrokeLineCap != GraphicLineCap.Flat) { pathElement.Add(new XAttribute("stroke-linecap", ConvertToSvg(graphicPath.StrokeLineCap))); } if (graphicPath.StrokeLineJoin != GraphicLineJoin.Miter) { pathElement.Add(new XAttribute("stroke-linejoin", ConvertToSvg(graphicPath.StrokeLineJoin))); } if (!DoubleUtilities.IsEqual(graphicPath.StrokeMiterLimit, 4)) { pathElement.Add(new XAttribute("stroke-miterlimit", DoubleUtilities.FormatString(graphicPath.StrokeMiterLimit))); } if (graphicPath.StrokeDashes != null) { var result = new StringBuilder(); for (int i = 0; i < graphicPath.StrokeDashes.Count; i++) { if (i != 0) { result.Append(" "); } result.Append(DoubleUtilities.FormatString(graphicPath.StrokeDashes[i] * graphicPath.StrokeThickness)); } pathElement.Add(new XAttribute("stroke-dasharray", result.ToString())); if (!DoubleUtilities.IsZero(graphicPath.StrokeDashOffset)) { pathElement.Add(new XAttribute("stroke-dashoffset", DoubleUtilities.FormatString(graphicPath.StrokeDashOffset * graphicPath.StrokeThickness))); } } } }
/// <summary> /// Calculate result values based on the input values /// </summary> public List <double> Calculate(List <double> values) { var results = new List <double>(); for (int i = 0; i < c0.Count; i++) { var y2 = DoubleUtilities.Interpolate(values[i], domain0, domain1, c0[i], c1[i]); results.Add(y2); } return(results); }
/// <summary> /// Generate gradient stops /// </summary> private static void GenerateGradientStops(StringBuilder result, string indent, List <GraphicGradientStop> gradientStops) { foreach (var stop in gradientStops) { Color color = stop.Color; var offset = stop.Position; result.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}<GradientStop Color=\"{1}\" Offset=\"{2}\"/>", indent, FormatColorParamter(color), DoubleUtilities.FormatString(offset))); } }
/// <summary> /// Write a radial shading definition /// </summary> private void WriteRadialShading(GraphicRadialGradientBrush gradientBrush, Rect boundingBox) { string center0Str = FormatPoint(GetAbsolutePosition(boundingBox, gradientBrush.StartPoint)); string center1Str = FormatPoint(GetAbsolutePosition(boundingBox, gradientBrush.EndPoint)); string radius0Str = DoubleUtilities.FormatString(GetAbsoluteLength(boundingBox, 0)); string radius1Str = DoubleUtilities.FormatString(GetAbsoluteLength(boundingBox, gradientBrush.RadiusX)); string coordsStr = $"/Coords [{center0Str} {radius0Str} {center1Str} {radius1Str}]"; WriteShadingPattern("3", gradientBrush, boundingBox, coordsStr); }
/// <summary> /// Get the viewport definition /// </summary> private Rect GetViewPort(XElement element, bool isTopLevel) { double x; double y; if (isTopLevel) { x = 0.0; y = 0.0; } else { x = doubleParser.GetLengthPercent(element, "x", 0.0, PercentBaseSelector.ViewBoxWidth); y = doubleParser.GetLengthPercent(element, "y", 0.0, PercentBaseSelector.ViewBoxHeight); } var widthLPA = doubleParser.GetLengthPercentAuto(element, "width", PercentBaseSelector.ViewBoxWidth); var heightLPA = doubleParser.GetLengthPercentAuto(element, "height", PercentBaseSelector.ViewBoxHeight); if (DoubleUtilities.IsZero(x) && DoubleUtilities.IsZero(y) && widthLPA.IsAuto && heightLPA.IsAuto) { return(Rect.Empty); } double width; double height; var svgViewBox = cssStyleCascade.GetCurrentViewBox().ViewBox; if (widthLPA.IsAuto) { width = svgViewBox.Width; } else { width = widthLPA.Value; } if (heightLPA.IsAuto) { height = svgViewBox.Height; } else { height = heightLPA.Value; } return(new Rect(new Point(x, y), new Size(width, height))); }
/// <summary> /// Generate a visual recursively to xml /// </summary> private static XElement Generate(GraphicVisual visual, XNamespace ns, XElement definitions, ref int definitionsCount) { XElement element = null; switch (visual) { case GraphicGroup group: { element = new XElement(ns + "g"); if (!DoubleUtilities.IsEqual(group.Opacity, 1)) { element.Add(new XAttribute("opacity", DoubleUtilities.FormatString(group.Opacity))); } if (group.Clip != null) { var clipElement = new XElement(ns + "clipPath"); definitions.Add(clipElement); definitionsCount++; string defId = $"clip{definitionsCount}"; element.Add(new XAttribute("clip-path", $"url(#{defId})")); clipElement.Add(new XAttribute("id", defId)); var pathElement = new XElement(ns + "path"); clipElement.Add(pathElement); var pathStr = StreamSourceGenerator.GenerateStreamGeometry(group.Clip, false); pathElement.Add(new XAttribute("d", pathStr)); } foreach (var childVisual in group.Childreen) { var path = Generate(childVisual, ns, definitions, ref definitionsCount); element.Add(path); } break; } case GraphicPath graphicPath: { element = GeneratePath(graphicPath, ns, definitions, ref definitionsCount); break; } } return(element); }
/// <summary> /// Extract a sample from the data array /// </summary> /// <param name="data">the data array</param> /// <param name="offset">the offset where the requested sample starts</param> /// <param name="valuesPerSample">number of values per sample</param> /// <returns>list of values that descibe a single sample</returns> private List <double> GetSample(List <double> data, int offset, int valuesPerSample, List <double> decodes) { var list = new List <double>(); for (int i = 0; i < valuesPerSample; i++) { var value = data[offset + i]; var decoded = DoubleUtilities.Interpolate(value, 0, 1, decodes[i * 2], decodes[i * 2 + 1]); list.Add(decoded); } return(list); }
private void ExecuteIncreaseBoost(TermModel model) { if (!model.Boost.HasValue) { model.Boost = 1.0; } model.Ban = false; model.Require = false; if (DoubleUtilities.LessThan(model.Boost.GetValueOrDefault(), 5.0)) { model.Boost += 0.5; } }
/// <summary> /// Format one double value for scaling /// </summary> protected string FormatScaledValue(double normalizedValue, string scaleVariableName) { if (IsEqual(normalizedValue, 0.0)) { return "0"; } else if (IsEqual(normalizedValue, 1.0)) { return scaleVariableName; } string dblStr = DoubleUtilities.FormatString(normalizedValue); return $"{dblStr} * {scaleVariableName}"; }
/// <summary> /// Format one double value for scaling /// </summary> private string FormatScaledValue(double normalizedValue, string scaleVariableName, string offset) { if (IsEqual(normalizedValue, 0.0)) { return offset; } else if (IsEqual(normalizedValue, 1.0)) { return $"{scaleVariableName} + {offset}"; } string dblStr = DoubleUtilities.FormatString(normalizedValue); return $"{dblStr} * {scaleVariableName} + {offset}"; }
private void OnWindow_MouseWheel(object sender, MouseWheelEventArgs e) { if (!e.Handled) { if (DoubleUtilities.IsStrictlyLessThan(e.Delta, 0)) { MediaCommands.NextTrack.Execute(null, this); } else if (DoubleUtilities.IsStrictlyGreaterThan(e.Delta, 0)) { MediaCommands.PreviousTrack.Execute(null, this); } e.Handled = true; } }
private static bool _IsUniform(CornerRadius cornerRadius) { if (!DoubleUtilities.AreClose(cornerRadius.BottomLeft, cornerRadius.BottomRight)) { return(false); } if (!DoubleUtilities.AreClose(cornerRadius.TopLeft, cornerRadius.TopRight)) { return(false); } if (!DoubleUtilities.AreClose(cornerRadius.BottomLeft, cornerRadius.TopRight)) { return(false); } return(true); }
/// <summary> /// Write start of the EPS file /// </summary> private void InitEpsFile(double width, double height) { var widthStr = DoubleUtilities.FormatString(Math.Ceiling(width)); var heightStr = DoubleUtilities.FormatString(Math.Ceiling(height)); outputStream.WriteLine("%!PS-Adobe-3.1 EPSF-3.0"); outputStream.WriteLine($"%%BoundingBox: 0 0 {widthStr} {heightStr}"); outputStream.WriteLine("%%Pages: 1"); outputStream.WriteLine("%%EndComments"); outputStream.WriteLine("%%BeginProlog"); outputStream.WriteLine("%%EndProlog"); outputStream.WriteLine("%%BeginSetup"); outputStream.WriteLine("%%EndSetup"); outputStream.WriteLine("%%Page: 1 1"); outputStream.WriteLine("%%BeginPageSetup"); outputStream.WriteLine("%%EndPageSetup"); outputStream.WriteLine($"1 -1 scale 0 -{heightStr} translate"); }
/// <summary> /// Generates the source code for a given visual. /// </summary> private void Generate(GraphicVisual visual) { switch (visual) { case GraphicGroup group: { bool graphicStateSaved = false; if (!DoubleUtilities.IsEqual(group.Opacity, 1.0)) { // EPS doesn't support opacity nonSupportedOpacityFound = true; } if (group.Clip != null) { graphicStateSaved = true; outputStream.WriteLine("gsave"); GenerateShape(group.Clip); outputStream.WriteLine("clippath"); } foreach (var childVisual in group.Children) { Generate(childVisual); } if (graphicStateSaved) { outputStream.WriteLine("grestore"); } break; } case GraphicPath graphicPath: { GeneratePath(graphicPath); break; } } }
/// <summary> /// Write a stitching function definition describing the gradient stops /// </summary> private void WriteStitchingFunction(List <GraphicGradientStop> gradientStops) { outputStream.WriteLine("<<"); outputStream.WriteLine("/FunctionType 3"); string boundFromStr = DoubleUtilities.FormatString(gradientStops[0].Position); string boundToStr = DoubleUtilities.FormatString(gradientStops[gradientStops.Count - 1].Position); outputStream.WriteLine($"/Domain[{boundFromStr} {boundToStr}]"); outputStream.WriteLine("/Range [0 1 0 1 0 1]"); outputStream.WriteLine("/Encode [0 1 0 1 0 1]"); outputStream.Write("/Bounds ["); for (int i = 1; i < gradientStops.Count - 1; i++) { if (i > 1) { outputStream.Write(" "); } string boundStr = DoubleUtilities.FormatString(gradientStops[i].Position); outputStream.Write(boundStr); } outputStream.WriteLine("]"); outputStream.WriteLine("/Functions ["); for (int i = 0; i < gradientStops.Count - 1; i++) { var stopFrom = gradientStops[i]; var stopTo = gradientStops[i + 1]; WriteExponentialFunction(stopFrom.Color, stopTo.Color); } outputStream.WriteLine("]"); outputStream.WriteLine(">>"); }
/// <summary> /// Generate the source code for the given path /// </summary> private void GeneratePath(GraphicPath graphicPath) { GenerateShape(graphicPath.Geometry); if (graphicPath.FillBrush != null) { bool graphicStateSaved = false; if (graphicPath.StrokeBrush != null) { graphicStateSaved = true; outputStream.WriteLine("gsave"); } WriteBrush(graphicPath.FillBrush, graphicPath.Geometry.Bounds); outputStream.WriteLine("fill"); if (graphicStateSaved) { outputStream.WriteLine("grestore"); } } if (graphicPath.StrokeBrush != null) { WriteBrush(graphicPath.StrokeBrush, graphicPath.Geometry.Bounds); var widthStr = DoubleUtilities.FormatString(graphicPath.StrokeThickness); outputStream.WriteLine($"{widthStr} setlinewidth"); WriteLineCap(graphicPath.StrokeLineCap); WriteLineJoin(graphicPath.StrokeLineJoin); WriteDash(graphicPath); var miterStr = DoubleUtilities.FormatString(graphicPath.StrokeMiterLimit); outputStream.WriteLine($"{miterStr} setmiterlimit"); outputStream.WriteLine("stroke"); } }
private static bool _Animate( double currentValue, double currentVelocity, double targetValue, double attractionFator, double dampening, double terminalVelocity, double minValueDelta, double minVelocityDelta, out double newValue, out double newVelocity) { Assert.IsTrue(DoubleUtilities.IsFinite(currentValue)); Assert.IsTrue(DoubleUtilities.IsFinite(currentVelocity)); Assert.IsTrue(DoubleUtilities.IsFinite(targetValue)); Assert.IsTrue(DoubleUtilities.IsFinite(dampening)); Assert.IsTrue(dampening > 0 && dampening < 1); Assert.IsTrue(DoubleUtilities.IsFinite(attractionFator)); Assert.IsTrue(attractionFator > 0); Assert.IsTrue(terminalVelocity > 0); Assert.IsTrue(minValueDelta > 0); Assert.IsTrue(minVelocityDelta > 0); double diff = targetValue - currentValue; if (Math.Abs(diff) > minValueDelta || Math.Abs(currentVelocity) > minVelocityDelta) { newVelocity = currentVelocity * (1 - dampening); newVelocity += diff * attractionFator; newVelocity *= (Math.Abs(currentVelocity) > terminalVelocity) ? terminalVelocity / Math.Abs(currentVelocity) : 1; newValue = currentValue + newVelocity; return(true); } else { newValue = targetValue; newVelocity = 0; return(false); } }