// ========================================================== // FreeImage 3 .NET wrapper // Original FreeImage 3 functions and .NET compatible derived functions // // Design and implementation by // - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net) // - Carsten Klein (cklein05@users.sourceforge.net) // // Contributors: // - David Boland (davidboland@vodafone.ie) // // Main reference : MSDN Knowlede Base // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== // ========================================================== // CVS // $Revision: 1.5 $ // $Date: 2009/02/27 16:36:23 $ // $Id: FIURational.cs,v 1.5 2009/02/27 16:36:23 cklein05 Exp $ // ========================================================== using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; namespace FreeImageAPI { /// /// The FIURational structure represents a fraction via two /// instances which are interpreted as numerator and denominator. /// /// /// The structure tries to approximate the value of /// when creating a new instance by using a better algorithm than FreeImage does. /// /// The structure implements the following operators: /// +, ++, --, ==, != , >, >==, <, <== and ~ (which switches nominator and denomiator). /// /// The structure can be converted into all .NET standard types either implicit or /// explicit. /// [Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)] public struct FIURational : IConvertible, IComparable, IFormattable, IComparable, IEquatable { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private uint numerator; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private uint denominator; /// /// Represents the largest possible value of . This field is constant. /// public static readonly FIURational MaxValue = new FIURational(UInt32.MaxValue, 1u); /// /// Represents the smallest possible value of . This field is constant. /// public static readonly FIURational MinValue = new FIURational(0u, 1u); /// /// Represents the smallest positive value greater than zero. This field is constant. /// public static readonly FIURational Epsilon = new FIURational(1u, UInt32.MaxValue); /// /// Initializes a new instance based on the specified parameters. /// /// The numerator. /// The denominator. public FIURational(uint n, uint d) { numerator = n; denominator = d; Normalize(); } /// /// Initializes a new instance based on the specified parameters. /// /// The tag to read the data from. public unsafe FIURational(FITAG tag) { switch (FreeImage.GetTagType(tag)) { case FREE_IMAGE_MDTYPE.FIDT_RATIONAL: uint* pvalue = (uint*)FreeImage.GetTagValue(tag); numerator = pvalue[0]; denominator = pvalue[1]; Normalize(); return; default: throw new ArgumentException("tag"); } } /// ///Initializes a new instance based on the specified parameters. /// /// The value to convert into a fraction. /// /// cannot be converted into a fraction /// represented by two unsigned integer values. public FIURational(decimal value) { try { if (value < 0) { throw new OverflowException("value"); } try { int[] contFract = CreateContinuedFraction(value); CreateFraction(contFract, out numerator, out denominator); Normalize(); } catch { numerator = 0; denominator = 1; } if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m) { int maxDen = (Int32.MaxValue / (int)value) - 2; maxDen = maxDen < 10000 ? maxDen : 10000; ApproximateFraction(value, maxDen, out numerator, out denominator); Normalize(); if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m) { throw new OverflowException("Unable to convert value into a fraction"); } } Normalize(); } catch (Exception ex) { throw new OverflowException("Unable to calculate fraction.", ex); } } /// /// The numerator of the fraction. /// public uint Numerator { get { return numerator; } } /// /// The denominator of the fraction. /// public uint Denominator { get { return denominator; } } /// /// Returns the truncated value of the fraction. /// /// public int Truncate() { return denominator > 0 ? (int)(numerator / denominator) : 0; } /// /// Returns whether the fraction is representing an integer value. /// public bool IsInteger { get { return (denominator == 1 || (denominator != 0 && (numerator % denominator == 0)) || (denominator == 0 && numerator == 0)); } } /// /// Calculated the greatest common divisor of 'a' and 'b'. /// private static ulong Gcd(ulong a, ulong b) { ulong r; while (b > 0) { r = a % b; a = b; b = r; } return a; } /// /// Calculated the smallest common multiple of 'a' and 'b'. /// private static ulong Scm(uint n, uint m) { return (ulong)n * (ulong)m / Gcd(n, m); } /// /// Normalizes the fraction. /// private void Normalize() { if (denominator == 0) { numerator = 0; denominator = 1; return; } if (numerator != 1 && denominator != 1) { uint common = (uint)Gcd(numerator, denominator); if (common != 1 && common != 0) { numerator /= common; denominator /= common; } } } /// /// Normalizes a fraction. /// private static void Normalize(ref ulong numerator, ref ulong denominator) { if (denominator == 0) { numerator = 0; denominator = 1; } else if (numerator != 1 && denominator != 1) { ulong common = Gcd(numerator, denominator); if (common != 1) { numerator /= common; denominator /= common; } } } /// /// Returns the digits after the point. /// private static int GetDigits(decimal value) { int result = 0; value -= decimal.Truncate(value); while (value != 0) { value *= 10; value -= decimal.Truncate(value); result++; } return result; } /// /// Creates a continued fraction of a decimal value. /// private static int[] CreateContinuedFraction(decimal value) { int precision = GetDigits(value); decimal epsilon = 0.0000001m; List list = new List(); value = Math.Abs(value); byte b = 0; list.Add((int)value); value -= ((int)value); while (value != 0m) { if (++b == byte.MaxValue || value < epsilon) { break; } value = 1m / value; if (Math.Abs((Math.Round(value, precision - 1) - value)) < epsilon) { value = Math.Round(value, precision - 1); } list.Add((int)value); value -= ((int)value); } return list.ToArray(); } /// /// Creates a fraction from a continued fraction. /// private static void CreateFraction(int[] continuedFraction, out uint numerator, out uint denominator) { numerator = 1; denominator = 0; uint temp; for (int i = continuedFraction.Length - 1; i > -1; i--) { temp = numerator; numerator = (uint)(continuedFraction[i] * numerator + denominator); denominator = temp; } } /// /// Tries 'brute force' to approximate with a fraction. /// private static void ApproximateFraction(decimal value, int maxDen, out uint num, out uint den) { num = 0; den = 0; decimal bestDifference = 1m; decimal currentDifference = -1m; int digits = GetDigits(value); if (digits <= 9) { uint mul = 1; for (int i = 1; i <= digits; i++) { mul *= 10; } if (mul <= maxDen) { num = (uint)(value * mul); den = mul; return; } } for (uint u = 1; u <= maxDen; u++) { uint numerator = (uint)Math.Floor(value * (decimal)u + 0.5m); currentDifference = Math.Abs(value - (decimal)numerator / (decimal)u); if (currentDifference < bestDifference) { num = numerator; den = u; bestDifference = currentDifference; } } } /// /// Converts the numeric value of the object /// to its equivalent string representation. /// /// The string representation of the value of this instance. public override string ToString() { return ((IConvertible)this).ToDouble(null).ToString(); } /// /// Tests whether the specified object is a structure /// and is equivalent to this structure. /// /// The object to test. /// true if is a structure /// equivalent to this structure; otherwise, false. public override bool Equals(object obj) { return ((obj is FIURational) && (this == ((FIURational)obj))); } /// /// Returns a hash code for this structure. /// /// An integer value that specifies the hash code for this . public override int GetHashCode() { return base.GetHashCode(); } #region Operators /// /// Standard implementation of the operator. /// public static FIURational operator +(FIURational value) { return value; } /// /// Returns the reciprocal value of this instance. /// public static FIURational operator ~(FIURational value) { uint temp = value.denominator; value.denominator = value.numerator; value.numerator = temp; value.Normalize(); return value; } /// /// Standard implementation of the operator. /// public static FIURational operator ++(FIURational value) { checked { value.numerator += value.denominator; } return value; } /// /// Standard implementation of the operator. /// public static FIURational operator --(FIURational value) { checked { value.numerator -= value.denominator; } return value; } /// /// Standard implementation of the operator. /// public static FIURational operator +(FIURational left, FIURational right) { ulong numerator = 0; ulong denominator = Scm(left.denominator, right.denominator); numerator = (left.numerator * (denominator / left.denominator)) + (right.numerator * (denominator / right.denominator)); Normalize(ref numerator, ref denominator); checked { return new FIURational((uint)numerator, (uint)denominator); } } /// /// Standard implementation of the operator. /// public static FIURational operator -(FIURational left, FIURational right) { checked { if (left.denominator != right.denominator) { uint denom = left.denominator; left.numerator *= right.denominator; left.denominator *= right.denominator; right.numerator *= denom; right.denominator *= denom; } left.numerator -= right.numerator; left.Normalize(); return left; } } /// /// Standard implementation of the operator. /// public static FIURational operator *(FIURational left, FIURational r2) { ulong numerator = left.numerator * r2.numerator; ulong denominator = left.denominator * r2.denominator; Normalize(ref numerator, ref denominator); checked { return new FIURational((uint)numerator, (uint)denominator); } } /// /// Standard implementation of the operator. /// public static FIURational operator /(FIURational left, FIURational right) { uint temp = right.denominator; right.denominator = right.numerator; right.numerator = temp; return left * right; } /// /// Standard implementation of the operator. /// public static FIURational operator %(FIURational left, FIURational right) { right.Normalize(); if (Math.Abs(right.numerator) < right.denominator) return new FIURational(0, 0); int div = (int)(left / right); return left - (right * div); } /// /// Standard implementation of the operator. /// public static bool operator ==(FIURational left, FIURational right) { left.Normalize(); right.Normalize(); return (left.numerator == right.numerator) && (left.denominator == right.denominator); } /// /// Standard implementation of the operator. /// public static bool operator !=(FIURational left, FIURational right) { left.Normalize(); right.Normalize(); return (left.numerator != right.numerator) || (left.denominator != right.denominator); } /// /// Standard implementation of the operator. /// public static bool operator >(FIURational left, FIURational right) { ulong denominator = Scm(left.denominator, right.denominator); return (left.numerator * (denominator / left.denominator)) > (right.numerator * (denominator / right.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator <(FIURational left, FIURational right) { ulong denominator = Scm(left.denominator, right.denominator); return (left.numerator * (denominator / left.denominator)) < (right.numerator * (denominator / right.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator >=(FIURational left, FIURational right) { ulong denominator = Scm(left.denominator, right.denominator); return (left.numerator * (denominator / left.denominator)) >= (right.numerator * (denominator / right.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator <=(FIURational left, FIURational right) { ulong denominator = Scm(left.denominator, right.denominator); return (left.numerator * (denominator / left.denominator)) <= (right.numerator * (denominator / right.denominator)); } #endregion #region Conversions /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator bool(FIURational value) { return (value.numerator != 0); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator byte(FIURational value) { return (byte)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator char(FIURational value) { return (char)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator decimal(FIURational value) { return value.denominator == 0 ? 0m : (decimal)value.numerator / (decimal)value.denominator; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator double(FIURational value) { return value.denominator == 0 ? 0d : (double)value.numerator / (double)value.denominator; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator short(FIURational value) { return (short)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator int(FIURational value) { return (int)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator long(FIURational value) { return (byte)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator float(FIURational value) { return value.denominator == 0 ? 0f : (float)value.numerator / (float)value.denominator; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator sbyte(FIURational value) { return (sbyte)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator ushort(FIURational value) { return (ushort)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator uint(FIURational value) { return (uint)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator ulong(FIURational value) { return (ulong)(double)value; } // /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIURational(bool value) { return new FIURational(value ? 1u : 0u, 1u); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIURational(byte value) { return new FIURational(value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIURational(char value) { return new FIURational(value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIURational(decimal value) { return new FIURational(value); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIURational(double value) { return new FIURational((decimal)value); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIURational(short value) { return new FIURational((uint)value, 1u); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIURational(int value) { return new FIURational((uint)value, 1u); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIURational(long value) { return new FIURational((uint)value, 1u); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIURational(sbyte value) { return new FIURational((uint)value, 1u); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIURational(float value) { return new FIURational((decimal)value); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIURational(ushort value) { return new FIURational(value, 1); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIURational(uint value) { return new FIURational(value, 1u); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIURational(ulong value) { return new FIURational((uint)value, 1u); } #endregion #region IConvertible Member TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return (bool)this; } byte IConvertible.ToByte(IFormatProvider provider) { return (byte)this; } char IConvertible.ToChar(IFormatProvider provider) { return (char)this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(((IConvertible)this).ToDouble(provider)); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return this; } double IConvertible.ToDouble(IFormatProvider provider) { return this; } short IConvertible.ToInt16(IFormatProvider provider) { return (short)this; } int IConvertible.ToInt32(IFormatProvider provider) { return (int)this; } long IConvertible.ToInt64(IFormatProvider provider) { return (long)this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return (sbyte)this; } float IConvertible.ToSingle(IFormatProvider provider) { return this; } string IConvertible.ToString(IFormatProvider provider) { return ToString(((double)this).ToString(), provider); } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return Convert.ChangeType(((IConvertible)this).ToDouble(provider), conversionType, provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return (ushort)this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return (uint)this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return (ulong)this; } #endregion #region IComparable Member /// /// Compares this instance with a specified . /// /// An object to compare with this instance. /// A 32-bit signed integer indicating the lexical relationship between the two comparands. /// is not a . public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is FIURational)) { throw new ArgumentException(); } return CompareTo((FIURational)obj); } #endregion #region IFormattable Member /// /// Formats the value of the current instance using the specified format. /// /// The String specifying the format to use. /// The IFormatProvider to use to format the value. /// A String containing the value of the current instance in the specified format. public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { format = ""; } return String.Format(formatProvider, format, ((IConvertible)this).ToDouble(formatProvider)); } #endregion #region IEquatable Member /// /// Tests whether the specified structure is equivalent to this structure. /// /// A structure to compare to this instance. /// true if is a structure /// equivalent to this structure; otherwise, false. public bool Equals(FIURational other) { return (this == other); } #endregion #region IComparable Member /// /// Compares this instance with a specified object. /// /// A to compare. /// A signed number indicating the relative values of this instance /// and . public int CompareTo(FIURational other) { FIURational difference = this - other; difference.Normalize(); if (difference.numerator > 0) return 1; if (difference.numerator < 0) return -1; else return 0; } #endregion } }