Whitespace updates

This commit is contained in:
Marc Hernandez 2026-02-01 23:49:30 -08:00
parent c25b9b3b12
commit 2b5940bef6
127 changed files with 8469 additions and 7453 deletions

View File

@ -52,7 +52,7 @@ namespace lib
{ {
if( mi.GetParameters().Length == 1 ) if( mi.GetParameters().Length == 1 )
{ {
string paramName = mi.GetParameters()[ 0 ].ParameterType.Name; string paramName = mi.GetParameters()[0].ParameterType.Name;
if( paramName == "String" ) if( paramName == "String" )
{ {
@ -125,7 +125,7 @@ namespace lib
{ {
XmlNodeList nodeList = docElem.ChildNodes; XmlNodeList nodeList = docElem.ChildNodes;
object[] args = new object[ 1 ]; object[] args = new object[1];
//fi.SetValue( newObj, obj ); //fi.SetValue( newObj, obj );

4
Id.cs
View File

@ -13,7 +13,7 @@ namespace lib
{ {
public struct Id<T>: IComparable, IFormattable, IConvertible, IComparable<ulong>, IEquatable<ulong> public struct Id<T> : IComparable, IFormattable, IConvertible, IComparable<ulong>, IEquatable<ulong>
{ {
public const ulong Min = 0uL; public const ulong Min = 0uL;
public const ulong Max = 18446744073709551615uL; public const ulong Max = 18446744073709551615uL;
@ -29,7 +29,7 @@ namespace lib
s_rand.NextBytes( buf ); s_rand.NextBytes( buf );
var newId = BitConverter.ToUInt64(buf, 0); var newId = BitConverter.ToUInt64( buf, 0 );
return new Id<T> { m_value = newId }; return new Id<T> { m_value = newId };
} }

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net9</TargetFrameworks> <TargetFrameworks>net9.0;net8.0;net10.0</TargetFrameworks>
<RootNamespace>lib</RootNamespace> <RootNamespace>lib</RootNamespace>
<AssemblyVersion>0.0.1.0</AssemblyVersion> <AssemblyVersion>0.0.1.0</AssemblyVersion>
<FileVersion>0.0.1.0</FileVersion> <FileVersion>0.0.1.0</FileVersion>

View File

@ -144,7 +144,7 @@ namespace lib
[MethodImpl( MethodImplOptions.AggressiveInlining )] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int SizeOf<T>() public static int SizeOf<T>()
{ {
return System.Runtime.InteropServices.Marshal.SizeOf(typeof( T )); return System.Runtime.InteropServices.Marshal.SizeOf( typeof( T ) );
} }
public static unsafe void* Write<T>( void* pDest, ref T data ) where T : struct public static unsafe void* Write<T>( void* pDest, ref T data ) where T : struct

View File

@ -63,22 +63,22 @@ namespace lib
*/ */
public static string ToString<T>(this IEnumerable<T> collectionToConvert, string separator) public static string ToString<T>( this IEnumerable<T> collectionToConvert, string separator )
{ {
return String.Join(separator, collectionToConvert.Select(o => o.ToString())); return String.Join( separator, collectionToConvert.Select( o => o.ToString() ) );
} }
public static string FriendlyName(this Type type) public static string FriendlyName( this Type type )
{ {
if (type.IsGenericType) if( type.IsGenericType )
{ {
var namePrefix = type.Name.Split(new [] {'`'}, StringSplitOptions.RemoveEmptyEntries)[0]; var namePrefix = type.Name.Split( new[] { '`' }, StringSplitOptions.RemoveEmptyEntries )[0];
var genericParameters = type.GetGenericArguments().ToString( ", ") ; var genericParameters = type.GetGenericArguments().ToString( ", " );
return namePrefix + "<" + genericParameters + ">"; return namePrefix + "<" + genericParameters + ">";
} }
return type.Name; return type.Name;
} }
@ -420,8 +420,8 @@ namespace lib
{ {
throw new ArgumentException( "Alignment is not power of 2", nameof( align ) ); throw new ArgumentException( "Alignment is not power of 2", nameof( align ) );
} }
var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*)); var memPtr = Marshal.AllocHGlobal( sizeInBytes + mask + sizeof( void* ) );
var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask); var ptr = (byte*)( (ulong)( memPtr.ToInt32() + sizeof( void* ) + mask ) & ~(ulong)mask );
( (IntPtr*)ptr )[-1] = memPtr; ( (IntPtr*)ptr )[-1] = memPtr;
return new IntPtr( ptr ); return new IntPtr( ptr );
} }
@ -438,7 +438,7 @@ namespace lib
/// </remarks> /// </remarks>
public static IntPtr AllocateClearedMemory( int sizeInBytes, byte clearValue = 0, int align = 16 ) public static IntPtr AllocateClearedMemory( int sizeInBytes, byte clearValue = 0, int align = 16 )
{ {
var ptr = AllocateMemory(sizeInBytes, align); var ptr = AllocateMemory( sizeInBytes, align );
ClearMemory( ptr, clearValue, sizeInBytes ); ClearMemory( ptr, clearValue, sizeInBytes );
return ptr; return ptr;
} }

View File

@ -23,9 +23,9 @@ using System.IO;
public class AdaptiveArithmeticCompress public class AdaptiveArithmeticCompress
{ {
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
/* @@@@ PORT /* @@@@ PORT
// Handle command line arguments // Handle command line arguments
@ -48,25 +48,25 @@ public class AdaptiveArithmeticCompress
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException //ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException
internal static void compress(Stream @in, BitOutputStream @out) internal static void compress( Stream @in, BitOutputStream @out )
{ {
FlatFrequencyTable initFreqs = new FlatFrequencyTable(257); FlatFrequencyTable initFreqs = new FlatFrequencyTable( 257 );
FrequencyTable freqs = new SimpleFrequencyTable(initFreqs); FrequencyTable freqs = new SimpleFrequencyTable( initFreqs );
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out); ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
while (true) while( true )
{ {
// Read and encode one byte // Read and encode one byte
int symbol = @in.ReadByte(); int symbol = @in.ReadByte();
if (symbol == -1) if( symbol == -1 )
{ {
break; break;
} }
enc.write(freqs, symbol); enc.write( freqs, symbol );
freqs.increment(symbol); freqs.increment( symbol );
} }
enc.write(freqs, 256); // EOF enc.write( freqs, 256 ); // EOF
enc.finish(); // Flush remaining code bits enc.finish(); // Flush remaining code bits
} }

View File

@ -19,9 +19,9 @@ using System.IO;
public class AdaptiveArithmeticDecompress public class AdaptiveArithmeticDecompress
{ {
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
/* @@@@ PORT /* @@@@ PORT
// Handle command line arguments // Handle command line arguments
@ -44,23 +44,23 @@ public class AdaptiveArithmeticDecompress
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException //ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException
internal static void decompress(BitInputStream @in, Stream @out) internal static void decompress( BitInputStream @in, Stream @out )
{ {
FlatFrequencyTable initFreqs = new FlatFrequencyTable(257); FlatFrequencyTable initFreqs = new FlatFrequencyTable( 257 );
FrequencyTable freqs = new SimpleFrequencyTable(initFreqs); FrequencyTable freqs = new SimpleFrequencyTable( initFreqs );
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in); ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
while (true) while( true )
{ {
// Decode and write one byte // Decode and write one byte
int symbol = dec.read(freqs); int symbol = dec.read( freqs );
if (symbol == 256) // EOF symbol if( symbol == 256 ) // EOF symbol
{ {
break; break;
} }
@out.WriteByte((byte)symbol); @out.WriteByte( (byte)symbol );
freqs.increment(symbol); freqs.increment( symbol );
} }
} }

View File

@ -83,18 +83,18 @@ public abstract class ArithmeticCoderBase
/// Constructs an arithmetic coder, which initializes the code range. </summary> /// Constructs an arithmetic coder, which initializes the code range. </summary>
/// <param name="numBits"> the number of bits for the arithmetic coding range </param> /// <param name="numBits"> the number of bits for the arithmetic coding range </param>
/// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception> /// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception>
public ArithmeticCoderBase(int numBits) public ArithmeticCoderBase( int numBits )
{ {
if (numBits < 1 || numBits > 62) if( numBits < 1 || numBits > 62 )
{ {
throw new System.ArgumentException("State size out of range"); throw new System.ArgumentException( "State size out of range" );
} }
numStateBits = numBits; numStateBits = numBits;
fullRange = 1L << numStateBits; fullRange = 1L << numStateBits;
halfRange = (long)((ulong)fullRange >> 1); // Non-zero halfRange = (long)( (ulong)fullRange >> 1 ); // Non-zero
quarterRange = (long)((ulong)halfRange >> 1); // Can be zero quarterRange = (long)( (ulong)halfRange >> 1 ); // Can be zero
minimumRange = quarterRange + 2; // At least 2 minimumRange = quarterRange + 2; // At least 2
maximumTotal = Math.Min(long.MaxValue / fullRange, minimumRange); maximumTotal = Math.Min( long.MaxValue / fullRange, minimumRange );
stateMask = fullRange - 1; stateMask = fullRange - 1;
low = 0; low = 0;
@ -124,23 +124,23 @@ public abstract class ArithmeticCoderBase
/// <param name="freqs"> the frequency table to use </param> /// <param name="freqs"> the frequency table to use </param>
/// <param name="symbol"> the symbol that was processed </param> /// <param name="symbol"> the symbol that was processed </param>
/// <exception cref="IllegalArgumentException"> if the symbol has zero frequency or the frequency table's total is too large </exception> /// <exception cref="IllegalArgumentException"> if the symbol has zero frequency or the frequency table's total is too large </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void update(CheckedFrequencyTable freqs, int symbol) throws java.io.IOException //ORIGINAL LINE: protected void update(CheckedFrequencyTable freqs, int symbol) throws java.io.IOException
protected internal virtual void update(CheckedFrequencyTable freqs, int symbol) protected internal virtual void update( CheckedFrequencyTable freqs, int symbol )
{ {
// State check // State check
Debug.Assert(low >= high || (low & stateMask) != low || (high & stateMask) != high, "Low or high out of range"); Debug.Assert( low >= high || ( low & stateMask ) != low || ( high & stateMask ) != high, "Low or high out of range" );
long range = high - low + 1; long range = high - low + 1;
Debug.Assert(range < minimumRange || range > fullRange, "Range out of range"); Debug.Assert( range < minimumRange || range > fullRange, "Range out of range" );
// Frequency table values check // Frequency table values check
long total = freqs.Total; long total = freqs.Total;
long symLow = freqs.getLow(symbol); long symLow = freqs.getLow( symbol );
long symHigh = freqs.getHigh(symbol); long symHigh = freqs.getHigh( symbol );
Debug.Assert( symLow == symHigh, "Symbol has zero frequency"); Debug.Assert( symLow == symHigh, "Symbol has zero frequency" );
Debug.Assert( total > maximumTotal, "Cannot code symbol because total is too large"); Debug.Assert( total > maximumTotal, "Cannot code symbol because total is too large" );
// Update range // Update range
long newLow = low + symLow * range / total; long newLow = low + symLow * range / total;
@ -149,20 +149,20 @@ public abstract class ArithmeticCoderBase
high = newHigh; high = newHigh;
// While low and high have the same top bit value, shift them out // While low and high have the same top bit value, shift them out
while (((low ^ high) & halfRange) == 0) while( ( ( low ^ high ) & halfRange ) == 0 )
{ {
shift(); shift();
low = ((low << 1) & stateMask); low = ( ( low << 1 ) & stateMask );
high = ((high << 1) & stateMask) | 1; high = ( ( high << 1 ) & stateMask ) | 1;
} }
// Now low's top bit must be 0 and high's top bit must be 1 // Now low's top bit must be 0 and high's top bit must be 1
// While low's top two bits are 01 and high's are 10, delete the second highest bit of both // While low's top two bits are 01 and high's are 10, delete the second highest bit of both
while ((low & ~high & quarterRange) != 0) while( ( low & ~high & quarterRange ) != 0 )
{ {
underflow(); underflow();
low = (low << 1) ^ halfRange; low = ( low << 1 ) ^ halfRange;
high = ((high ^ halfRange) << 1) | halfRange | 1; high = ( ( high ^ halfRange ) << 1 ) | halfRange | 1;
} }
} }
@ -170,16 +170,16 @@ public abstract class ArithmeticCoderBase
/// <summary> /// <summary>
/// Called to handle the situation when the top bit of {@code low} and {@code high} are equal. </summary> /// Called to handle the situation when the top bit of {@code low} and {@code high} are equal. </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void shift() throws java.io.IOException; //ORIGINAL LINE: protected abstract void shift() throws java.io.IOException;
protected internal abstract void shift(); protected internal abstract void shift();
/// <summary> /// <summary>
/// Called to handle the situation when low=01(...) and high=10(...). </summary> /// Called to handle the situation when low=01(...) and high=10(...). </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void underflow() throws java.io.IOException; //ORIGINAL LINE: protected abstract void underflow() throws java.io.IOException;
protected internal abstract void underflow(); protected internal abstract void underflow();
} }

View File

@ -22,9 +22,9 @@ using System.IO;
public class ArithmeticCompress public class ArithmeticCompress
{ {
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
/* @@ PORT /* @@ PORT
// Handle command line arguments // Handle command line arguments
@ -53,23 +53,23 @@ public class ArithmeticCompress
// Returns a frequency table based on the bytes in the given file. // Returns a frequency table based on the bytes in the given file.
// Also contains an extra entry for symbol 256, whose frequency is set to 0. // Also contains an extra entry for symbol 256, whose frequency is set to 0.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static FrequencyTable getFrequencies(java.io.File file) throws java.io.IOException //ORIGINAL LINE: private static FrequencyTable getFrequencies(java.io.File file) throws java.io.IOException
private static FrequencyTable getFrequencies(string file) private static FrequencyTable getFrequencies( string file )
{ {
FrequencyTable freqs = new SimpleFrequencyTable(new int[257]); FrequencyTable freqs = new SimpleFrequencyTable( new int[257] );
using (Stream input = new BufferedStream( new FileStream(file, FileMode.Open, FileAccess.Read))) using( Stream input = new BufferedStream( new FileStream( file, FileMode.Open, FileAccess.Read ) ) )
{ {
while (true) while( true )
{ {
int b = input.ReadByte(); int b = input.ReadByte();
if (b == -1) if( b == -1 )
{ {
break; break;
} }
freqs.increment(b); freqs.increment( b );
} }
} }
return freqs; return freqs;
@ -77,50 +77,50 @@ public class ArithmeticCompress
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void writeFrequencies(BitOutputStream out, FrequencyTable freqs) throws java.io.IOException //ORIGINAL LINE: static void writeFrequencies(BitOutputStream out, FrequencyTable freqs) throws java.io.IOException
internal static void writeFrequencies(BitOutputStream @out, FrequencyTable freqs) internal static void writeFrequencies( BitOutputStream @out, FrequencyTable freqs )
{ {
for (int i = 0; i < 256; i++) for( int i = 0; i < 256; i++ )
{ {
writeInt(@out, 32, freqs.get(i)); writeInt( @out, 32, freqs.get( i ) );
} }
} }
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void compress(FrequencyTable freqs, java.io.InputStream in, BitOutputStream out) throws java.io.IOException //ORIGINAL LINE: static void compress(FrequencyTable freqs, java.io.InputStream in, BitOutputStream out) throws java.io.IOException
internal static void compress(FrequencyTable freqs, Stream @in, BitOutputStream @out) internal static void compress( FrequencyTable freqs, Stream @in, BitOutputStream @out )
{ {
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out); ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
while (true) while( true )
{ {
int symbol = @in.ReadByte(); int symbol = @in.ReadByte();
if (symbol == -1) if( symbol == -1 )
{ {
break; break;
} }
enc.write(freqs, symbol); enc.write( freqs, symbol );
} }
enc.write(freqs, 256); // EOF enc.write( freqs, 256 ); // EOF
enc.finish(); // Flush remaining code bits enc.finish(); // Flush remaining code bits
} }
// Writes an unsigned integer of the given bit width to the given stream. // Writes an unsigned integer of the given bit width to the given stream.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void writeInt(BitOutputStream out, int numBits, int value) throws java.io.IOException //ORIGINAL LINE: private static void writeInt(BitOutputStream out, int numBits, int value) throws java.io.IOException
private static void writeInt(BitOutputStream @out, int numBits, int value) private static void writeInt( BitOutputStream @out, int numBits, int value )
{ {
if (numBits < 0 || numBits > 32) if( numBits < 0 || numBits > 32 )
{ {
throw new System.ArgumentException(); throw new System.ArgumentException();
} }
for (int i = numBits - 1; i >= 0; i--) for( int i = numBits - 1; i >= 0; i-- )
{ {
@out.write(((int)((uint)value >> i)) & 1); // Big endian @out.write( ( (int)( (uint)value >> i ) ) & 1 ); // Big endian
} }
} }

View File

@ -35,13 +35,13 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
/// <exception cref="NullPointerException"> if the input steam is {@code null} </exception> /// <exception cref="NullPointerException"> if the input steam is {@code null} </exception>
/// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception> /// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public ArithmeticDecoder(int numBits, BitInputStream in) throws java.io.IOException //ORIGINAL LINE: public ArithmeticDecoder(int numBits, BitInputStream in) throws java.io.IOException
public ArithmeticDecoder(int numBits, BitInputStream @in) : base(numBits) public ArithmeticDecoder( int numBits, BitInputStream @in ) : base( numBits )
{ {
input = @in; //Objects.requireNonNull(@in); input = @in; //Objects.requireNonNull(@in);
code = 0; code = 0;
for (int i = 0; i < numStateBits; i++) for( int i = 0; i < numStateBits; i++ )
{ {
code = code << 1 | (long)readCodeBit(); code = code << 1 | (long)readCodeBit();
} }
@ -58,11 +58,11 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
/// <returns> the next symbol </returns> /// <returns> the next symbol </returns>
/// <exception cref="NullPointerException"> if the frequency table is {@code null} </exception> /// <exception cref="NullPointerException"> if the frequency table is {@code null} </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(FrequencyTable freqs) throws java.io.IOException //ORIGINAL LINE: public int read(FrequencyTable freqs) throws java.io.IOException
public int read(FrequencyTable freqs) public int read( FrequencyTable freqs )
{ {
return read(new CheckedFrequencyTable(freqs)); return read( new CheckedFrequencyTable( freqs ) );
} }
@ -74,30 +74,30 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
/// <exception cref="NullPointerException"> if the frequency table is {@code null} </exception> /// <exception cref="NullPointerException"> if the frequency table is {@code null} </exception>
/// <exception cref="IllegalArgumentException"> if the frequency table's total is too large </exception> /// <exception cref="IllegalArgumentException"> if the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(CheckedFrequencyTable freqs) throws java.io.IOException //ORIGINAL LINE: public int read(CheckedFrequencyTable freqs) throws java.io.IOException
public int read(CheckedFrequencyTable freqs) public int read( CheckedFrequencyTable freqs )
{ {
// Translate from coding range scale to frequency table scale // Translate from coding range scale to frequency table scale
long total = freqs.Total; long total = freqs.Total;
if (total > maximumTotal) if( total > maximumTotal )
{ {
throw new System.ArgumentException("Cannot decode symbol because total is too large"); throw new System.ArgumentException( "Cannot decode symbol because total is too large" );
} }
long range = high - low + 1; long range = high - low + 1;
long offset = code - low; long offset = code - low;
long value = ((offset + 1) * total - 1) / range; long value = ( ( offset + 1 ) * total - 1 ) / range;
Debug.Assert(value * range / total > offset); Debug.Assert( value * range / total > offset );
Debug.Assert(value < 0 || value >= total); Debug.Assert( value < 0 || value >= total );
// A kind of binary search. Find highest symbol such that freqs.getLow(symbol) <= value. // A kind of binary search. Find highest symbol such that freqs.getLow(symbol) <= value.
int start = 0; int start = 0;
int end = freqs.SymbolLimit; int end = freqs.SymbolLimit;
while (end - start > 1) while( end - start > 1 )
{ {
int middle = (int)((uint)(start + end) >> 1); int middle = (int)( (uint)( start + end ) >> 1 );
if (freqs.getLow(middle) > value) if( freqs.getLow( middle ) > value )
{ {
end = middle; end = middle;
} }
@ -106,43 +106,43 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
start = middle; start = middle;
} }
} }
Debug.Assert( start + 1 != end); Debug.Assert( start + 1 != end );
int symbol = start; int symbol = start;
Debug.Assert(offset < freqs.getLow(symbol) * range / total || freqs.getHigh(symbol) * range / total <= offset); Debug.Assert( offset < freqs.getLow( symbol ) * range / total || freqs.getHigh( symbol ) * range / total <= offset );
update(freqs, symbol); update( freqs, symbol );
Debug.Assert(code < low || code > high); Debug.Assert( code < low || code > high );
return symbol; return symbol;
} }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException //ORIGINAL LINE: protected void shift() throws java.io.IOException
protected internal override void shift() protected internal override void shift()
{ {
code = ((code << 1) & stateMask) | (long)readCodeBit(); code = ( ( code << 1 ) & stateMask ) | (long)readCodeBit();
} }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void underflow() throws java.io.IOException //ORIGINAL LINE: protected void underflow() throws java.io.IOException
protected internal override void underflow() protected internal override void underflow()
{ {
code = (code & halfRange) | ((code << 1) & ((long)((ulong)stateMask >> 1))) | (long)readCodeBit(); code = ( code & halfRange ) | ( ( code << 1 ) & ( (long)( (ulong)stateMask >> 1 ) ) ) | (long)readCodeBit();
} }
// Returns the next bit (0 or 1) from the input stream. The end // Returns the next bit (0 or 1) from the input stream. The end
// of stream is treated as an infinite number of trailing zeros. // of stream is treated as an infinite number of trailing zeros.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private int readCodeBit() throws java.io.IOException //ORIGINAL LINE: private int readCodeBit() throws java.io.IOException
private int readCodeBit() private int readCodeBit()
{ {
int temp = input.read(); int temp = input.read();
if (temp == -1) if( temp == -1 )
{ {
temp = 0; temp = 0;
} }

View File

@ -19,26 +19,26 @@ using System.IO;
public class ArithmeticDecompress public class ArithmeticDecompress
{ {
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
// Handle command line arguments // Handle command line arguments
if (args.Length != 2) if( args.Length != 2 )
{ {
Console.Error.WriteLine("Usage: java ArithmeticDecompress InputFile OutputFile"); Console.Error.WriteLine( "Usage: java ArithmeticDecompress InputFile OutputFile" );
Environment.Exit(1); Environment.Exit( 1 );
return; return;
} }
string inputFile = args[0]; // new File(args[0]); string inputFile = args[0]; // new File(args[0]);
string outputFile = args[1]; //new File(args[1]); string outputFile = args[1]; //new File(args[1]);
// Perform file decompression // Perform file decompression
using( BitInputStream @in = new BitInputStream(new BufferedStream(new FileStream(inputFile, FileMode.Open, FileAccess.Read)))) using( BitInputStream @in = new BitInputStream( new BufferedStream( new FileStream( inputFile, FileMode.Open, FileAccess.Read ) ) ) )
using( Stream @out = new BufferedStream(new FileStream(outputFile, FileMode.Create, FileAccess.Write) ) ) using( Stream @out = new BufferedStream( new FileStream( outputFile, FileMode.Create, FileAccess.Write ) ) )
{ {
FrequencyTable freqs = readFrequencies(@in); FrequencyTable freqs = readFrequencies( @in );
decompress( freqs, @in, @out ); decompress( freqs, @in, @out );
} }
@ -46,52 +46,52 @@ public class ArithmeticDecompress
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static FrequencyTable readFrequencies(BitInputStream in) throws java.io.IOException //ORIGINAL LINE: static FrequencyTable readFrequencies(BitInputStream in) throws java.io.IOException
internal static FrequencyTable readFrequencies(BitInputStream @in) internal static FrequencyTable readFrequencies( BitInputStream @in )
{ {
int[] freqs = new int[257]; int[] freqs = new int[257];
for (int i = 0; i < 256; i++) for( int i = 0; i < 256; i++ )
{ {
freqs[i] = readInt(@in, 32); freqs[i] = readInt( @in, 32 );
} }
freqs[256] = 1; // EOF symbol freqs[256] = 1; // EOF symbol
return new SimpleFrequencyTable(freqs); return new SimpleFrequencyTable( freqs );
} }
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void decompress(FrequencyTable freqs, BitInputStream in, java.io.OutputStream out) throws java.io.IOException //ORIGINAL LINE: static void decompress(FrequencyTable freqs, BitInputStream in, java.io.OutputStream out) throws java.io.IOException
internal static void decompress(FrequencyTable freqs, BitInputStream @in, Stream @out) internal static void decompress( FrequencyTable freqs, BitInputStream @in, Stream @out )
{ {
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in); ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
while (true) while( true )
{ {
int symbol = dec.read(freqs); int symbol = dec.read( freqs );
if (symbol == 256) // EOF symbol if( symbol == 256 ) // EOF symbol
{ {
break; break;
} }
@out.WriteByte((byte)symbol); @out.WriteByte( (byte)symbol );
} }
} }
// Reads an unsigned integer of the given bit width from the given stream. // Reads an unsigned integer of the given bit width from the given stream.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static int readInt(BitInputStream in, int numBits) throws java.io.IOException //ORIGINAL LINE: private static int readInt(BitInputStream in, int numBits) throws java.io.IOException
private static int readInt(BitInputStream @in, int numBits) private static int readInt( BitInputStream @in, int numBits )
{ {
if (numBits < 0 || numBits > 32) if( numBits < 0 || numBits > 32 )
{ {
throw new System.ArgumentException(); throw new System.ArgumentException();
} }
int result = 0; int result = 0;
for (int i = 0; i < numBits; i++) for( int i = 0; i < numBits; i++ )
{ {
result = (result << 1) | @in.readNoEof(); // Big endian result = ( result << 1 ) | @in.readNoEof(); // Big endian
} }
return result; return result;
} }

View File

@ -34,7 +34,7 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// <param name="out"> the bit output stream to write to </param> /// <param name="out"> the bit output stream to write to </param>
/// <exception cref="NullPointerException"> if the output stream is {@code null} </exception> /// <exception cref="NullPointerException"> if the output stream is {@code null} </exception>
/// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception> /// <exception cref="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception>
public ArithmeticEncoder(int numBits, BitOutputStream @out) : base(numBits) public ArithmeticEncoder( int numBits, BitOutputStream @out ) : base( numBits )
{ {
output = @out; //Objects.requireNonNull(@out); output = @out; //Objects.requireNonNull(@out);
numUnderflow = 0; numUnderflow = 0;
@ -53,11 +53,11 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// <exception cref="IllegalArgumentException"> if the symbol has zero frequency /// <exception cref="IllegalArgumentException"> if the symbol has zero frequency
/// or the frequency table's total is too large </exception> /// or the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void write(FrequencyTable freqs, int symbol) throws java.io.IOException //ORIGINAL LINE: public void write(FrequencyTable freqs, int symbol) throws java.io.IOException
public void write(FrequencyTable freqs, int symbol) public void write( FrequencyTable freqs, int symbol )
{ {
write(new CheckedFrequencyTable(freqs), symbol); write( new CheckedFrequencyTable( freqs ), symbol );
} }
@ -70,11 +70,11 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// <exception cref="IllegalArgumentException"> if the symbol has zero frequency /// <exception cref="IllegalArgumentException"> if the symbol has zero frequency
/// or the frequency table's total is too large </exception> /// or the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void write(CheckedFrequencyTable freqs, int symbol) throws java.io.IOException //ORIGINAL LINE: public void write(CheckedFrequencyTable freqs, int symbol) throws java.io.IOException
public void write(CheckedFrequencyTable freqs, int symbol) public void write( CheckedFrequencyTable freqs, int symbol )
{ {
update(freqs, symbol); update( freqs, symbol );
} }
@ -83,34 +83,34 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// It is important that this method must be called at the end of the each encoding process. /// It is important that this method must be called at the end of the each encoding process.
/// <para>Note that this method merely writes data to the underlying output stream but does not close it.</para> </summary> /// <para>Note that this method merely writes data to the underlying output stream but does not close it.</para> </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void finish() throws java.io.IOException //ORIGINAL LINE: public void finish() throws java.io.IOException
public void finish() public void finish()
{ {
output.write(1); output.write( 1 );
} }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException //ORIGINAL LINE: protected void shift() throws java.io.IOException
protected internal override void shift() protected internal override void shift()
{ {
int bit = (int)((long)((ulong)low >> (numStateBits - 1))); int bit = (int)( (long)( (ulong)low >> ( numStateBits - 1 ) ) );
output.write(bit); output.write( bit );
// Write out the saved underflow bits // Write out the saved underflow bits
for (; numUnderflow > 0; numUnderflow--) for( ; numUnderflow > 0; numUnderflow-- )
{ {
output.write(bit ^ 1); output.write( bit ^ 1 );
} }
} }
protected internal override void underflow() protected internal override void underflow()
{ {
if (numUnderflow == int.MaxValue) if( numUnderflow == int.MaxValue )
{ {
throw new ArgumentException("Maximum underflow reached"); throw new ArgumentException( "Maximum underflow reached" );
} }
numUnderflow++; numUnderflow++;
} }

View File

@ -8,32 +8,32 @@ using System;
internal static class Arrays internal static class Arrays
{ {
public static T[] CopyOf<T>(T[] original, int newLength) public static T[] CopyOf<T>( T[] original, int newLength )
{ {
T[] dest = new T[newLength]; T[] dest = new T[newLength];
Array.Copy(original, dest, newLength); Array.Copy( original, dest, newLength );
return dest; return dest;
} }
public static T[] CopyOfRange<T>(T[] original, int fromIndex, int toIndex) public static T[] CopyOfRange<T>( T[] original, int fromIndex, int toIndex )
{ {
int length = toIndex - fromIndex; int length = toIndex - fromIndex;
T[] dest = new T[length]; T[] dest = new T[length];
Array.Copy(original, fromIndex, dest, 0, length); Array.Copy( original, fromIndex, dest, 0, length );
return dest; return dest;
} }
public static void Fill<T>(T[] array, T value) public static void Fill<T>( T[] array, T value )
{ {
for (int i = 0; i < array.Length; i++) for( int i = 0; i < array.Length; i++ )
{ {
array[i] = value; array[i] = value;
} }
} }
public static void Fill<T>(T[] array, int fromIndex, int toIndex, T value) public static void Fill<T>( T[] array, int fromIndex, int toIndex, T value )
{ {
for (int i = fromIndex; i < toIndex; i++) for( int i = fromIndex; i < toIndex; i++ )
{ {
array[i] = value; array[i] = value;
} }

View File

@ -39,7 +39,7 @@ public sealed class BitInputStream : IDisposable
/// Constructs a bit input stream based on the specified byte input stream. </summary> /// Constructs a bit input stream based on the specified byte input stream. </summary>
/// <param name="in"> the byte input stream </param> /// <param name="in"> the byte input stream </param>
/// <exception cref="NullPointerException"> if the input stream is {@code null} </exception> /// <exception cref="NullPointerException"> if the input stream is {@code null} </exception>
public BitInputStream(Stream @in) public BitInputStream( Stream @in )
{ {
input = @in; //Objects.requireNonNull(@in); input = @in; //Objects.requireNonNull(@in);
currentByte = 0; currentByte = 0;
@ -55,27 +55,27 @@ public sealed class BitInputStream : IDisposable
/// the end of stream is reached. The end of stream always occurs on a byte boundary. </summary> /// the end of stream is reached. The end of stream always occurs on a byte boundary. </summary>
/// <returns> the next bit of 0 or 1, or -1 for the end of stream </returns> /// <returns> the next bit of 0 or 1, or -1 for the end of stream </returns>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read() throws java.io.IOException //ORIGINAL LINE: public int read() throws java.io.IOException
public int read() public int read()
{ {
if (currentByte == -1) if( currentByte == -1 )
{ {
return -1; return -1;
} }
if (numBitsRemaining == 0) if( numBitsRemaining == 0 )
{ {
currentByte = input.ReadByte(); // input.Read(); currentByte = input.ReadByte(); // input.Read();
if (currentByte == -1) if( currentByte == -1 )
{ {
return -1; return -1;
} }
numBitsRemaining = 8; numBitsRemaining = 8;
} }
Debug.Assert(numBitsRemaining <= 0); Debug.Assert( numBitsRemaining <= 0 );
numBitsRemaining--; numBitsRemaining--;
return ((int)((uint)currentByte >> numBitsRemaining)) & 1; return ( (int)( (uint)currentByte >> numBitsRemaining ) ) & 1;
} }
@ -85,12 +85,12 @@ public sealed class BitInputStream : IDisposable
/// <returns> the next bit of 0 or 1 </returns> /// <returns> the next bit of 0 or 1 </returns>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
/// <exception cref="EOFException"> if the end of stream is reached </exception> /// <exception cref="EOFException"> if the end of stream is reached </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int readNoEof() throws java.io.IOException //ORIGINAL LINE: public int readNoEof() throws java.io.IOException
public int readNoEof() public int readNoEof()
{ {
int result = read(); int result = read();
if (result != -1) if( result != -1 )
{ {
return result; return result;
} }
@ -104,8 +104,8 @@ public sealed class BitInputStream : IDisposable
/// <summary> /// <summary>
/// Closes this stream and the underlying input stream. </summary> /// Closes this stream and the underlying input stream. </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException //ORIGINAL LINE: public void close() throws java.io.IOException
public void close() public void close()
{ {
input.Close(); input.Close();

View File

@ -38,7 +38,7 @@ public sealed class BitOutputStream : IDisposable
/// Constructs a bit output stream based on the specified byte output stream. </summary> /// Constructs a bit output stream based on the specified byte output stream. </summary>
/// <param name="out"> the byte output stream </param> /// <param name="out"> the byte output stream </param>
/// <exception cref="NullPointerException"> if the output stream is {@code null} </exception> /// <exception cref="NullPointerException"> if the output stream is {@code null} </exception>
public BitOutputStream(Stream @out) public BitOutputStream( Stream @out )
{ {
output = @out; //Objects.requireNonNull(@out); output = @out; //Objects.requireNonNull(@out);
currentByte = 0; currentByte = 0;
@ -53,19 +53,19 @@ public sealed class BitOutputStream : IDisposable
/// Writes a bit to the stream. The specified bit must be 0 or 1. </summary> /// Writes a bit to the stream. The specified bit must be 0 or 1. </summary>
/// <param name="b"> the bit to write, which must be 0 or 1 </param> /// <param name="b"> the bit to write, which must be 0 or 1 </param>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void write(int b) throws java.io.IOException //ORIGINAL LINE: public void write(int b) throws java.io.IOException
public void write(int b) public void write( int b )
{ {
if (b != 0 && b != 1) if( b != 0 && b != 1 )
{ {
throw new System.ArgumentException("Argument must be 0 or 1"); throw new System.ArgumentException( "Argument must be 0 or 1" );
} }
currentByte = (currentByte << 1) | b; currentByte = ( currentByte << 1 ) | b;
numBitsFilled++; numBitsFilled++;
if (numBitsFilled == 8) if( numBitsFilled == 8 )
{ {
output.WriteByte((byte)currentByte); output.WriteByte( (byte)currentByte );
currentByte = 0; currentByte = 0;
numBitsFilled = 0; numBitsFilled = 0;
} }
@ -77,13 +77,13 @@ public sealed class BitOutputStream : IDisposable
/// bit stream is not at a byte boundary, then the minimum number of "0" bits /// bit stream is not at a byte boundary, then the minimum number of "0" bits
/// (between 0 and 7 of them) are written as padding to reach the next byte boundary. </summary> /// (between 0 and 7 of them) are written as padding to reach the next byte boundary. </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception> /// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException //ORIGINAL LINE: public void close() throws java.io.IOException
public void close() public void close()
{ {
while (numBitsFilled != 0) while( numBitsFilled != 0 )
{ {
write(0); write( 0 );
} }
output.Close(); output.Close();
} }

View File

@ -26,7 +26,7 @@ public sealed class CheckedFrequencyTable : FrequencyTable
/*---- Constructor ----*/ /*---- Constructor ----*/
public CheckedFrequencyTable(FrequencyTable freq) public CheckedFrequencyTable( FrequencyTable freq )
{ {
freqTable = freq; //Objects.requireNonNull(freq); freqTable = freq; //Objects.requireNonNull(freq);
} }
@ -40,17 +40,17 @@ public sealed class CheckedFrequencyTable : FrequencyTable
get get
{ {
int result = freqTable.SymbolLimit; int result = freqTable.SymbolLimit;
Debug.Assert(result <= 0, "Non-positive symbol limit"); Debug.Assert( result <= 0, "Non-positive symbol limit" );
return result; return result;
} }
} }
public int get(int symbol) public int get( int symbol )
{ {
int result = freqTable.get(symbol); int result = freqTable.get( symbol );
Debug.Assert( !isSymbolInRange(symbol), "IllegalArgumentException expected"); Debug.Assert( !isSymbolInRange( symbol ), "IllegalArgumentException expected" );
Debug.Assert( result < 0, "Negative symbol frequency"); Debug.Assert( result < 0, "Negative symbol frequency" );
return result; return result;
} }
@ -60,42 +60,42 @@ public sealed class CheckedFrequencyTable : FrequencyTable
get get
{ {
int result = freqTable.Total; int result = freqTable.Total;
Debug.Assert( result < 0, "Negative total frequency"); Debug.Assert( result < 0, "Negative total frequency" );
return result; return result;
} }
} }
public int getLow(int symbol) public int getLow( int symbol )
{ {
if (isSymbolInRange(symbol)) if( isSymbolInRange( symbol ) )
{ {
int low = freqTable.getLow(symbol); int low = freqTable.getLow( symbol );
int high = freqTable.getHigh(symbol); int high = freqTable.getHigh( symbol );
Debug.Assert( !(0 <= low && low <= high && high <= freqTable.Total), "Symbol low cumulative frequency out of range"); Debug.Assert( !( 0 <= low && low <= high && high <= freqTable.Total ), "Symbol low cumulative frequency out of range" );
return low; return low;
} }
else else
{ {
freqTable.getLow(symbol); freqTable.getLow( symbol );
throw new ArgumentException( "IllegalArgumentException expected"); throw new ArgumentException( "IllegalArgumentException expected" );
} }
} }
public int getHigh(int symbol) public int getHigh( int symbol )
{ {
if (isSymbolInRange(symbol)) if( isSymbolInRange( symbol ) )
{ {
int low = freqTable.getLow(symbol); int low = freqTable.getLow( symbol );
int high = freqTable.getHigh(symbol); int high = freqTable.getHigh( symbol );
Debug.Assert( !(0 <= low && low <= high && high <= freqTable.Total), "Symbol high cumulative frequency out of range"); Debug.Assert( !( 0 <= low && low <= high && high <= freqTable.Total ), "Symbol high cumulative frequency out of range" );
return high; return high;
} }
else else
{ {
freqTable.getHigh(symbol); freqTable.getHigh( symbol );
throw new ArgumentException("IllegalArgumentException expected"); throw new ArgumentException( "IllegalArgumentException expected" );
} }
} }
@ -106,21 +106,21 @@ public sealed class CheckedFrequencyTable : FrequencyTable
} }
public void set(int symbol, int freq) public void set( int symbol, int freq )
{ {
freqTable.set(symbol, freq); freqTable.set( symbol, freq );
Debug.Assert( !isSymbolInRange(symbol) || freq < 0, "IllegalArgumentException expected"); Debug.Assert( !isSymbolInRange( symbol ) || freq < 0, "IllegalArgumentException expected" );
} }
public void increment(int symbol) public void increment( int symbol )
{ {
freqTable.increment(symbol); freqTable.increment( symbol );
Debug.Assert( !isSymbolInRange(symbol), "IllegalArgumentException expected"); Debug.Assert( !isSymbolInRange( symbol ), "IllegalArgumentException expected" );
} }
private bool isSymbolInRange(int symbol) private bool isSymbolInRange( int symbol )
{ {
return 0 <= symbol && symbol < SymbolLimit; return 0 <= symbol && symbol < SymbolLimit;
} }

View File

@ -27,11 +27,11 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// Constructs a flat frequency table with the specified number of symbols. </summary> /// Constructs a flat frequency table with the specified number of symbols. </summary>
/// <param name="numSyms"> the number of symbols, which must be at least 1 </param> /// <param name="numSyms"> the number of symbols, which must be at least 1 </param>
/// <exception cref="IllegalArgumentException"> if the number of symbols is less than 1 </exception> /// <exception cref="IllegalArgumentException"> if the number of symbols is less than 1 </exception>
public FlatFrequencyTable(int numSyms) public FlatFrequencyTable( int numSyms )
{ {
if (numSyms < 1) if( numSyms < 1 )
{ {
throw new System.ArgumentException("Number of symbols must be positive"); throw new System.ArgumentException( "Number of symbols must be positive" );
} }
numSymbols = numSyms; numSymbols = numSyms;
} }
@ -57,9 +57,9 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the frequency of the symbol, which is 1 </returns> /// <returns> the frequency of the symbol, which is 1 </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int get(int symbol) public int get( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
return 1; return 1;
} }
@ -83,9 +83,9 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of all the symbols below {@code symbol}, which is {@code symbol} </returns> /// <returns> the sum of the frequencies of all the symbols below {@code symbol}, which is {@code symbol} </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int getLow(int symbol) public int getLow( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
return symbol; return symbol;
} }
@ -96,19 +96,19 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of {@code symbol} and all symbols below, which is {@code symbol + 1} </returns> /// <returns> the sum of the frequencies of {@code symbol} and all symbols below, which is {@code symbol + 1} </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int getHigh(int symbol) public int getHigh( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
return symbol + 1; return symbol + 1;
} }
// Returns silently if 0 <= symbol < numSymbols, otherwise throws an exception. // Returns silently if 0 <= symbol < numSymbols, otherwise throws an exception.
private void checkSymbol(int symbol) private void checkSymbol( int symbol )
{ {
if (symbol < 0 || symbol >= numSymbols) if( symbol < 0 || symbol >= numSymbols )
{ {
throw new System.ArgumentException("Symbol out of range"); throw new System.ArgumentException( "Symbol out of range" );
} }
} }
@ -127,7 +127,7 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <param name="symbol"> ignored </param> /// <param name="symbol"> ignored </param>
/// <param name="freq"> ignored </param> /// <param name="freq"> ignored </param>
/// <exception cref="UnsupportedOperationException"> because this frequency table is immutable </exception> /// <exception cref="UnsupportedOperationException"> because this frequency table is immutable </exception>
public void set(int symbol, int freq) public void set( int symbol, int freq )
{ {
throw new System.NotSupportedException(); throw new System.NotSupportedException();
} }
@ -137,7 +137,7 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// Unsupported operation, because this frequency table is immutable. </summary> /// Unsupported operation, because this frequency table is immutable. </summary>
/// <param name="symbol"> ignored </param> /// <param name="symbol"> ignored </param>
/// <exception cref="UnsupportedOperationException"> because this frequency table is immutable </exception> /// <exception cref="UnsupportedOperationException"> because this frequency table is immutable </exception>
public void increment(int symbol) public void increment( int symbol )
{ {
throw new System.NotSupportedException(); throw new System.NotSupportedException();
} }

View File

@ -20,7 +20,7 @@ public interface FrequencyTable
/// <summary> /// <summary>
/// Returns the number of symbols in this frequency table, which is a positive number. </summary> /// Returns the number of symbols in this frequency table, which is a positive number. </summary>
/// <returns> the number of symbols in this frequency table </returns> /// <returns> the number of symbols in this frequency table </returns>
int SymbolLimit {get;} int SymbolLimit { get; }
/// <summary> /// <summary>
@ -28,7 +28,7 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the frequency of the symbol </returns> /// <returns> the frequency of the symbol </returns>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception> /// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
int get(int symbol); int get( int symbol );
/// <summary> /// <summary>
@ -38,7 +38,7 @@ public interface FrequencyTable
/// <param name="freq"> the frequency value to set </param> /// <param name="freq"> the frequency value to set </param>
/// <exception cref="IllegalArgumentException"> if the frequency is negative or the symbol is out of range </exception> /// <exception cref="IllegalArgumentException"> if the frequency is negative or the symbol is out of range </exception>
/// <exception cref="ArithmeticException"> if an arithmetic overflow occurs </exception> /// <exception cref="ArithmeticException"> if an arithmetic overflow occurs </exception>
void set(int symbol, int freq); void set( int symbol, int freq );
/// <summary> /// <summary>
@ -46,14 +46,14 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol whose frequency to increment </param> /// <param name="symbol"> the symbol whose frequency to increment </param>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception> /// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
/// <exception cref="ArithmeticException"> if an arithmetic overflow occurs </exception> /// <exception cref="ArithmeticException"> if an arithmetic overflow occurs </exception>
void increment(int symbol); void increment( int symbol );
/// <summary> /// <summary>
/// Returns the total of all symbol frequencies. The returned value is at /// Returns the total of all symbol frequencies. The returned value is at
/// least 0 and is always equal to {@code getHigh(getSymbolLimit() - 1)}. </summary> /// least 0 and is always equal to {@code getHigh(getSymbolLimit() - 1)}. </summary>
/// <returns> the total of all symbol frequencies </returns> /// <returns> the total of all symbol frequencies </returns>
int Total {get;} int Total { get; }
/// <summary> /// <summary>
@ -62,7 +62,7 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of all the symbols below {@code symbol} </returns> /// <returns> the sum of the frequencies of all the symbols below {@code symbol} </returns>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception> /// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
int getLow(int symbol); int getLow( int symbol );
/// <summary> /// <summary>
@ -71,6 +71,6 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of {@code symbol} and all symbols below </returns> /// <returns> the sum of the frequencies of {@code symbol} and all symbols below </returns>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception> /// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
int getHigh(int symbol); int getHigh( int symbol );
} }

View File

@ -26,9 +26,9 @@ public sealed class PpmCompress
private const int MODEL_ORDER = 3; private const int MODEL_ORDER = 3;
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
/* @@@@ PORT /* @@@@ PORT
// Handle command line arguments // Handle command line arguments
@ -51,79 +51,80 @@ public sealed class PpmCompress
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException //ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException
internal static void compress(Stream @in, BitOutputStream @out) internal static void compress( Stream @in, BitOutputStream @out )
{ {
// Set up encoder and model. In this PPM model, symbol 256 represents EOF; // Set up encoder and model. In this PPM model, symbol 256 represents EOF;
// its frequency is 1 in the order -1 context but its frequency // its frequency is 1 in the order -1 context but its frequency
// is 0 in all other contexts (which have non-negative order). // is 0 in all other contexts (which have non-negative order).
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out); ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
PpmModel model = new PpmModel(MODEL_ORDER, 257, 256); PpmModel model = new PpmModel( MODEL_ORDER, 257, 256 );
int[] history = new int[0]; int[] history = new int[0];
while (true) while( true )
{ {
// Read and encode one byte // Read and encode one byte
int symbol = @in.ReadByte(); int symbol = @in.ReadByte();
if (symbol == -1) if( symbol == -1 )
{ {
break; break;
} }
encodeSymbol(model, history, symbol, enc); encodeSymbol( model, history, symbol, enc );
model.incrementContexts(history, symbol); model.incrementContexts( history, symbol );
if (model.modelOrder >= 1) if( model.modelOrder >= 1 )
{ {
// Prepend current symbol, dropping oldest symbol if necessary // Prepend current symbol, dropping oldest symbol if necessary
if (history.Length < model.modelOrder) if( history.Length < model.modelOrder )
{ {
history = Arrays.CopyOf(history, history.Length + 1); history = Arrays.CopyOf( history, history.Length + 1 );
} }
Array.Copy(history, 0, history, 1, history.Length - 1); Array.Copy( history, 0, history, 1, history.Length - 1 );
history[0] = symbol; history[0] = symbol;
} }
} }
encodeSymbol(model, history, 256, enc); // EOF encodeSymbol( model, history, 256, enc ); // EOF
enc.finish(); // Flush remaining code bits enc.finish(); // Flush remaining code bits
} }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void encodeSymbol(PpmModel model, int[] history, int symbol, ArithmeticEncoder enc) throws java.io.IOException //ORIGINAL LINE: private static void encodeSymbol(PpmModel model, int[] history, int symbol, ArithmeticEncoder enc) throws java.io.IOException
private static void encodeSymbol(PpmModel model, int[] history, int symbol, ArithmeticEncoder enc) private static void encodeSymbol( PpmModel model, int[] history, int symbol, ArithmeticEncoder enc )
{ {
// Try to use highest order context that exists based on the history suffix, such // Try to use highest order context that exists based on the history suffix, such
// that the next symbol has non-zero frequency. When symbol 256 is produced at a context // that the next symbol has non-zero frequency. When symbol 256 is produced at a context
// at any non-negative order, it means "escape to the next lower order with non-empty // at any non-negative order, it means "escape to the next lower order with non-empty
// context". When symbol 256 is produced at the order -1 context, it means "EOF". // context". When symbol 256 is produced at the order -1 context, it means "EOF".
for (int order = history.Length; order >= 0; order--) for( int order = history.Length; order >= 0; order-- )
{ {
PpmModel.Context ctx = model.rootContext; PpmModel.Context ctx = model.rootContext;
for (int i = 0; i < order; i++) for( int i = 0; i < order; i++ )
{ {
Debug.Assert(ctx.subcontexts == null); Debug.Assert( ctx.subcontexts == null );
ctx = ctx.subcontexts[history[i]]; ctx = ctx.subcontexts[history[i]];
if (ctx == null) if( ctx == null )
{ {
goto outerContinue; goto outerContinue;
} }
} }
if (symbol != 256 && ctx.frequencies.get(symbol) > 0) if( symbol != 256 && ctx.frequencies.get( symbol ) > 0 )
{ {
enc.write(ctx.frequencies, symbol); enc.write( ctx.frequencies, symbol );
return; return;
} }
// Else write context escape symbol and continue decrementing the order // Else write context escape symbol and continue decrementing the order
enc.write(ctx.frequencies, 256); enc.write( ctx.frequencies, 256 );
outerContinue:; outerContinue:
;
} }
//outerBreak: //outerBreak:
// Logic for order = -1 // Logic for order = -1
enc.write(model.orderMinus1Freqs, symbol); enc.write( model.orderMinus1Freqs, symbol );
} }
} }

View File

@ -24,99 +24,100 @@ public sealed class PpmDecompress
private const int MODEL_ORDER = 3; private const int MODEL_ORDER = 3;
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException //ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
public static void Main(string[] args) public static void Main( string[] args )
{ {
// Handle command line arguments // Handle command line arguments
if (args.Length != 2) if( args.Length != 2 )
{ {
Console.Error.WriteLine("Usage: java PpmDecompress InputFile OutputFile"); Console.Error.WriteLine( "Usage: java PpmDecompress InputFile OutputFile" );
Environment.Exit(1); Environment.Exit( 1 );
return; return;
} }
string inputFile = args[0]; //new File(args[0]); string inputFile = args[0]; //new File(args[0]);
string outputFile =args[1]; //new File(args[1]); string outputFile = args[1]; //new File(args[1]);
// Perform file decompression // Perform file decompression
using( BitInputStream @in = new BitInputStream(new BufferedStream(new FileStream(inputFile, FileMode.Open, FileAccess.Read)))) using( BitInputStream @in = new BitInputStream( new BufferedStream( new FileStream( inputFile, FileMode.Open, FileAccess.Read ) ) ) )
using( Stream @out = new BufferedStream( new FileStream(outputFile, FileMode.Create, FileAccess.Write))) using( Stream @out = new BufferedStream( new FileStream( outputFile, FileMode.Create, FileAccess.Write ) ) )
{ {
decompress(@in, @out); decompress( @in, @out );
} }
} }
// To allow unit testing, this method is package-private instead of private. // To allow unit testing, this method is package-private instead of private.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException //ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException
internal static void decompress(BitInputStream @in, Stream @out) internal static void decompress( BitInputStream @in, Stream @out )
{ {
// Set up decoder and model. In this PPM model, symbol 256 represents EOF; // Set up decoder and model. In this PPM model, symbol 256 represents EOF;
// its frequency is 1 in the order -1 context but its frequency // its frequency is 1 in the order -1 context but its frequency
// is 0 in all other contexts (which have non-negative order). // is 0 in all other contexts (which have non-negative order).
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in); ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
PpmModel model = new PpmModel(MODEL_ORDER, 257, 256); PpmModel model = new PpmModel( MODEL_ORDER, 257, 256 );
int[] history = new int[0]; int[] history = new int[0];
while (true) while( true )
{ {
// Decode and write one byte // Decode and write one byte
int symbol = decodeSymbol(dec, model, history); int symbol = decodeSymbol( dec, model, history );
if (symbol == 256) // EOF symbol if( symbol == 256 ) // EOF symbol
{ {
break; break;
} }
@out.WriteByte((byte)symbol); @out.WriteByte( (byte)symbol );
model.incrementContexts(history, symbol); model.incrementContexts( history, symbol );
if (model.modelOrder >= 1) if( model.modelOrder >= 1 )
{ {
// Prepend current symbol, dropping oldest symbol if necessary // Prepend current symbol, dropping oldest symbol if necessary
if (history.Length < model.modelOrder) if( history.Length < model.modelOrder )
{ {
history = Arrays.CopyOf(history, history.Length + 1); history = Arrays.CopyOf( history, history.Length + 1 );
} }
Array.Copy(history, 0, history, 1, history.Length - 1); Array.Copy( history, 0, history, 1, history.Length - 1 );
history[0] = symbol; history[0] = symbol;
} }
} }
} }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static int decodeSymbol(ArithmeticDecoder dec, PpmModel model, int[] history) throws java.io.IOException //ORIGINAL LINE: private static int decodeSymbol(ArithmeticDecoder dec, PpmModel model, int[] history) throws java.io.IOException
private static int decodeSymbol(ArithmeticDecoder dec, PpmModel model, int[] history) private static int decodeSymbol( ArithmeticDecoder dec, PpmModel model, int[] history )
{ {
// Try to use highest order context that exists based on the history suffix. When symbol 256 // Try to use highest order context that exists based on the history suffix. When symbol 256
// is consumed at a context at any non-negative order, it means "escape to the next lower order // is consumed at a context at any non-negative order, it means "escape to the next lower order
// with non-empty context". When symbol 256 is consumed at the order -1 context, it means "EOF". // with non-empty context". When symbol 256 is consumed at the order -1 context, it means "EOF".
for (int order = history.Length; order >= 0; order--) for( int order = history.Length; order >= 0; order-- )
{ {
PpmModel.Context ctx = model.rootContext; PpmModel.Context ctx = model.rootContext;
for (int i = 0; i < order; i++) for( int i = 0; i < order; i++ )
{ {
Debug.Assert(ctx.subcontexts == null); Debug.Assert( ctx.subcontexts == null );
ctx = ctx.subcontexts[history[i]]; ctx = ctx.subcontexts[history[i]];
if (ctx == null) if( ctx == null )
{ {
goto outerContinue; goto outerContinue;
} }
} }
int symbol = dec.read(ctx.frequencies); int symbol = dec.read( ctx.frequencies );
if (symbol < 256) if( symbol < 256 )
{ {
return symbol; return symbol;
} }
// Else we read the context escape symbol, so continue decrementing the order // Else we read the context escape symbol, so continue decrementing the order
outerContinue:; outerContinue:
;
} }
//outerBreak: //outerBreak:
// Logic for order = -1 // Logic for order = -1
return dec.read(model.orderMinus1Freqs); return dec.read( model.orderMinus1Freqs );
} }
} }

View File

@ -26,9 +26,9 @@ internal sealed class PpmModel
/*---- Constructors ----*/ /*---- Constructors ----*/
public PpmModel(int order, int symbolLimit, int escapeSymbol) public PpmModel( int order, int symbolLimit, int escapeSymbol )
{ {
if (order < -1 || symbolLimit <= 0 || escapeSymbol < 0 || escapeSymbol >= symbolLimit) if( order < -1 || symbolLimit <= 0 || escapeSymbol < 0 || escapeSymbol >= symbolLimit )
{ {
throw new System.ArgumentException(); throw new System.ArgumentException();
} }
@ -36,49 +36,49 @@ internal sealed class PpmModel
this.symbolLimit = symbolLimit; this.symbolLimit = symbolLimit;
this.escapeSymbol = escapeSymbol; this.escapeSymbol = escapeSymbol;
if (order >= 0) if( order >= 0 )
{ {
rootContext = new Context(symbolLimit, order >= 1); rootContext = new Context( symbolLimit, order >= 1 );
rootContext.frequencies.increment(escapeSymbol); rootContext.frequencies.increment( escapeSymbol );
} }
else else
{ {
rootContext = null; rootContext = null;
} }
orderMinus1Freqs = new FlatFrequencyTable(symbolLimit); orderMinus1Freqs = new FlatFrequencyTable( symbolLimit );
} }
/*---- Methods ----*/ /*---- Methods ----*/
public void incrementContexts(int[] history, int symbol) public void incrementContexts( int[] history, int symbol )
{ {
if (modelOrder == -1) if( modelOrder == -1 )
{ {
return; return;
} }
if (history.Length > modelOrder || symbol < 0 || symbol >= symbolLimit) if( history.Length > modelOrder || symbol < 0 || symbol >= symbolLimit )
{ {
throw new System.ArgumentException(); throw new System.ArgumentException();
} }
Context ctx = rootContext; Context ctx = rootContext;
ctx.frequencies.increment(symbol); ctx.frequencies.increment( symbol );
int i = 0; int i = 0;
foreach (int sym in history) foreach( int sym in history )
{ {
Context[] subctxs = ctx.subcontexts; Context[] subctxs = ctx.subcontexts;
Debug.Assert(subctxs == null); Debug.Assert( subctxs == null );
if (subctxs[sym] == null) if( subctxs[sym] == null )
{ {
subctxs[sym] = new Context(symbolLimit, i + 1 < modelOrder); subctxs[sym] = new Context( symbolLimit, i + 1 < modelOrder );
subctxs[sym].frequencies.increment(escapeSymbol); subctxs[sym].frequencies.increment( escapeSymbol );
} }
ctx = subctxs[sym]; ctx = subctxs[sym];
ctx.frequencies.increment(symbol); ctx.frequencies.increment( symbol );
i++; i++;
} }
} }
@ -95,10 +95,10 @@ internal sealed class PpmModel
public readonly Context[] subcontexts; public readonly Context[] subcontexts;
public Context(int symbols, bool hasSubctx) public Context( int symbols, bool hasSubctx )
{ {
frequencies = new SimpleFrequencyTable(new int[symbols]); frequencies = new SimpleFrequencyTable( new int[symbols] );
if (hasSubctx) if( hasSubctx )
{ {
subcontexts = new Context[symbols]; subcontexts = new Context[symbols];
} }

View File

@ -42,27 +42,27 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <exception cref="IllegalArgumentException"> if {@code freqs.length} &lt; 1, /// <exception cref="IllegalArgumentException"> if {@code freqs.length} &lt; 1,
/// {@code freqs.length} = {@code Integer.MAX_VALUE}, or any element {@code freqs[i]} &lt; 0 </exception> /// {@code freqs.length} = {@code Integer.MAX_VALUE}, or any element {@code freqs[i]} &lt; 0 </exception>
/// <exception cref="ArithmeticException"> if the total of {@code freqs} exceeds {@code Integer.MAX_VALUE} </exception> /// <exception cref="ArithmeticException"> if the total of {@code freqs} exceeds {@code Integer.MAX_VALUE} </exception>
public SimpleFrequencyTable(int[] freqs) public SimpleFrequencyTable( int[] freqs )
{ {
//Objects.requireNonNull(freqs); //Objects.requireNonNull(freqs);
if (freqs.Length < 1) if( freqs.Length < 1 )
{ {
throw new System.ArgumentException("At least 1 symbol needed"); throw new System.ArgumentException( "At least 1 symbol needed" );
} }
if (freqs.Length > int.MaxValue - 1) if( freqs.Length > int.MaxValue - 1 )
{ {
throw new System.ArgumentException("Too many symbols"); throw new System.ArgumentException( "Too many symbols" );
} }
frequencies = (int[])freqs.Clone(); // Make copy frequencies = (int[])freqs.Clone(); // Make copy
total = 0; total = 0;
foreach (int x in frequencies) foreach( int x in frequencies )
{ {
if (x < 0) if( x < 0 )
{ {
throw new System.ArgumentException("Negative frequency"); throw new System.ArgumentException( "Negative frequency" );
} }
total = checkedAdd(x, total); total = checkedAdd( x, total );
} }
cumulative = null; cumulative = null;
} }
@ -75,21 +75,21 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <exception cref="IllegalArgumentException"> if {@code freqs.getSymbolLimit()} &lt; 1 /// <exception cref="IllegalArgumentException"> if {@code freqs.getSymbolLimit()} &lt; 1
/// or any element {@code freqs.get(i)} &lt; 0 </exception> /// or any element {@code freqs.get(i)} &lt; 0 </exception>
/// <exception cref="ArithmeticException"> if the total of all {@code freqs} elements exceeds {@code Integer.MAX_VALUE} </exception> /// <exception cref="ArithmeticException"> if the total of all {@code freqs} elements exceeds {@code Integer.MAX_VALUE} </exception>
public SimpleFrequencyTable(FrequencyTable freqs) public SimpleFrequencyTable( FrequencyTable freqs )
{ {
//Objects.requireNonNull(freqs); //Objects.requireNonNull(freqs);
int numSym = freqs.SymbolLimit; int numSym = freqs.SymbolLimit;
Debug.Assert(numSym < 1); Debug.Assert( numSym < 1 );
frequencies = new int[numSym]; frequencies = new int[numSym];
total = 0; total = 0;
for (int i = 0; i < frequencies.Length; i++) for( int i = 0; i < frequencies.Length; i++ )
{ {
int x = freqs.get(i); int x = freqs.get( i );
Debug.Assert(x < 0); Debug.Assert( x < 0 );
frequencies[i] = x; frequencies[i] = x;
total = checkedAdd(x, total); total = checkedAdd( x, total );
} }
cumulative = null; cumulative = null;
} }
@ -115,9 +115,9 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the frequency of the specified symbol </returns> /// <returns> the frequency of the specified symbol </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int get(int symbol) public int get( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
return frequencies[symbol]; return frequencies[symbol];
} }
@ -129,18 +129,18 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="freq"> the frequency value to set </param> /// <param name="freq"> the frequency value to set </param>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
/// <exception cref="ArithmeticException"> if this set request would cause the total to exceed {@code Integer.MAX_VALUE} </exception> /// <exception cref="ArithmeticException"> if this set request would cause the total to exceed {@code Integer.MAX_VALUE} </exception>
public void set(int symbol, int freq) public void set( int symbol, int freq )
{ {
checkSymbol(symbol); checkSymbol( symbol );
if (freq < 0) if( freq < 0 )
{ {
throw new System.ArgumentException("Negative frequency"); throw new System.ArgumentException( "Negative frequency" );
} }
int temp = total - frequencies[symbol]; int temp = total - frequencies[symbol];
Debug.Assert( temp < 0); Debug.Assert( temp < 0 );
total = checkedAdd(temp, freq); total = checkedAdd( temp, freq );
frequencies[symbol] = freq; frequencies[symbol] = freq;
cumulative = null; cumulative = null;
} }
@ -150,12 +150,12 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// Increments the frequency of the specified symbol. </summary> /// Increments the frequency of the specified symbol. </summary>
/// <param name="symbol"> the symbol whose frequency to increment </param> /// <param name="symbol"> the symbol whose frequency to increment </param>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public void increment(int symbol) public void increment( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
Debug.Assert( frequencies[symbol] == int.MaxValue ); Debug.Assert( frequencies[symbol] == int.MaxValue );
total = checkedAdd(total, 1); total = checkedAdd( total, 1 );
frequencies[symbol]++; frequencies[symbol]++;
cumulative = null; cumulative = null;
} }
@ -180,10 +180,10 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of all the symbols below {@code symbol} </returns> /// <returns> the sum of the frequencies of all the symbols below {@code symbol} </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int getLow(int symbol) public int getLow( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
if (cumulative == null) if( cumulative == null )
{ {
initCumulative(); initCumulative();
} }
@ -197,10 +197,10 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param> /// <param name="symbol"> the symbol to query </param>
/// <returns> the sum of the frequencies of {@code symbol} and all symbols below </returns> /// <returns> the sum of the frequencies of {@code symbol} and all symbols below </returns>
/// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception> /// <exception cref="IllegalArgumentException"> if {@code symbol} &lt; 0 or {@code symbol} &ge; {@code getSymbolLimit()} </exception>
public int getHigh(int symbol) public int getHigh( int symbol )
{ {
checkSymbol(symbol); checkSymbol( symbol );
if (cumulative == null) if( cumulative == null )
{ {
initCumulative(); initCumulative();
} }
@ -213,11 +213,11 @@ public sealed class SimpleFrequencyTable : FrequencyTable
{ {
cumulative = new int[frequencies.Length + 1]; cumulative = new int[frequencies.Length + 1];
int sum = 0; int sum = 0;
for (int i = 0; i < frequencies.Length; i++) for( int i = 0; i < frequencies.Length; i++ )
{ {
// This arithmetic should not throw an exception, because invariants are being maintained // This arithmetic should not throw an exception, because invariants are being maintained
// elsewhere in the data structure. This implementation is just a defensive measure. // elsewhere in the data structure. This implementation is just a defensive measure.
sum = checkedAdd(frequencies[i], sum); sum = checkedAdd( frequencies[i], sum );
cumulative[i + 1] = sum; cumulative[i + 1] = sum;
} }
Debug.Assert( sum != total ); Debug.Assert( sum != total );
@ -226,7 +226,7 @@ public sealed class SimpleFrequencyTable : FrequencyTable
// Returns silently if 0 <= symbol < frequencies.length, otherwise throws an exception. // Returns silently if 0 <= symbol < frequencies.length, otherwise throws an exception.
private void checkSymbol(int symbol) private void checkSymbol( int symbol )
{ {
Debug.Assert( symbol < 0 || symbol >= frequencies.Length ); Debug.Assert( symbol < 0 || symbol >= frequencies.Length );
} }
@ -239,17 +239,17 @@ public sealed class SimpleFrequencyTable : FrequencyTable
public override string ToString() public override string ToString()
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < frequencies.Length; i++) for( int i = 0; i < frequencies.Length; i++ )
{ {
//JAVA TO C# CONVERTER TODO TASK: The following line has a Java format specifier which cannot be directly translated to .NET: //JAVA TO C# CONVERTER TODO TASK: The following line has a Java format specifier which cannot be directly translated to .NET:
sb.Append(string.Format("%d\t%d%n", i, frequencies[i])); sb.Append( string.Format( "%d\t%d%n", i, frequencies[i] ) );
} }
return sb.ToString(); return sb.ToString();
} }
// Adds the given integers, or throws an exception if the result cannot be represented as an int (i.e. overflow). // Adds the given integers, or throws an exception if the result cannot be represented as an int (i.e. overflow).
private static int checkedAdd(int x, int y) private static int checkedAdd( int x, int y )
{ {
int z = x + y; int z = x + y;
Debug.Assert( y > 0 && z < x || y < 0 && z > x ); Debug.Assert( y > 0 && z < x || y < 0 && z > x );

View File

@ -45,7 +45,7 @@ namespace att
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )]
public sealed class CanBeNullAttribute: Attribute public sealed class CanBeNullAttribute : Attribute
{ {
} }
} }

View File

@ -19,7 +19,7 @@ namespace att
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )]
public sealed class NotNullAttribute: Attribute public sealed class NotNullAttribute : Attribute
{ {
} }
} }

View File

@ -5,25 +5,25 @@ using System.Numerics;
static public class bit static public class bit
{ {
public static unsafe TInt ByPointers_DirectInt<TInt, TEnum>(TEnum enumValue) public static unsafe TInt ByPointers_DirectInt<TInt, TEnum>( TEnum enumValue )
where TInt : IBinaryInteger<TInt> where TInt : IBinaryInteger<TInt>
where TEnum : unmanaged, System.Enum where TEnum : unmanaged, System.Enum
{ {
#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type #pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
return *(TInt*)(&enumValue); return *(TInt*)( &enumValue );
#pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type #pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
} }
static public bool On<T, E>( T bitfield, E e ) static public bool On<T, E>( T bitfield, E e )
where T: IBinaryInteger<T> where T : IBinaryInteger<T>
where E: unmanaged, System.Enum where E : unmanaged, System.Enum
{ {
var eInt = ByPointers_DirectInt<T, E>( e ); var eInt = ByPointers_DirectInt<T, E>( e );
return (eInt & bitfield) == eInt; return ( eInt & bitfield ) == eInt;
} }
} }

View File

@ -142,10 +142,10 @@ namespace lib
{ {
FileStream fs = new( filename, FileMode.Create, FileAccess.Write ); FileStream fs = new( filename, FileMode.Create, FileAccess.Write );
UTF8Encoding enc = new UTF8Encoding(true); UTF8Encoding enc = new UTF8Encoding( true );
byte[] info = enc.GetBytes($"<!--\nCaused when trying to load [{filename}]-->"); byte[] info = enc.GetBytes( $"<!--\nCaused when trying to load [{filename}]-->" );
fs.Write(info, 0, info.Length); fs.Write( info, 0, info.Length );
ser.XmlSer formatter = new( s_templateCfg ); ser.XmlSer formatter = new( s_templateCfg );

View File

@ -14,7 +14,7 @@ namespace db
public string DebugInfo { get; private set; } = ""; public string DebugInfo { get; private set; } = "";
public string Path { get; private set; } = ""; public string Path { get; private set; } = "";
public int Line { get; private set; } = -1; public int Line { get; private set; } = -1;
public string Member { get; private set; } = ""; public string Member { get; private set; } = "";
private Act( Func<CommitResults> act, string reason = "{unknown_base}", string dbgPath = "", int dbgLine = -1, string dbgMethod = "" ) private Act( Func<CommitResults> act, string reason = "{unknown_base}", string dbgPath = "", int dbgLine = -1, string dbgMethod = "" )
@ -82,7 +82,7 @@ namespace db
BindingFlags.Public | BindingFlags.Public |
BindingFlags.Static BindingFlags.Static
); );
//.SingleOrDefault(x => x.Name == variableName); //.SingleOrDefault(x => x.Name == variableName);
//return (TValue)field.GetValue( lambda.Target ); //return (TValue)field.GetValue( lambda.Target );
} }

View File

@ -61,9 +61,11 @@ public class DB<TID, T> where T : IID<TID>
var v = lookup( id ); var v = lookup( id );
v.Match( t => { v.Match( t =>
{
tx.checkout( id ); tx.checkout( id );
}, () => { }, () =>
{
} ); } );
return (tx, v); return (tx, v);
@ -71,7 +73,7 @@ public class DB<TID, T> where T : IID<TID>
public Tx<TID, T> checkout( TID id, out Option<T> tOut ) public Tx<TID, T> checkout( TID id, out Option<T> tOut )
{ {
var (tx, v) = checkout(id); var (tx, v) = checkout( id );
tOut = v; tOut = v;
@ -111,7 +113,8 @@ public class DB<TID, T> where T : IID<TID>
{ {
for( int i = start; i < curCommitted.Count; ++i ) for( int i = start; i < curCommitted.Count; ++i )
{ {
if( !t.id.Equals( curCommitted[i] ) ) { } if( !t.id.Equals( curCommitted[i] ) )
{ }
else else
{ {
//collision = true; //collision = true;
@ -131,7 +134,7 @@ public class DB<TID, T> where T : IID<TID>
m_objs = m_objs.Add( tx.Checkouts[i].id, tx.Checkouts[i] ); m_objs = m_objs.Add( tx.Checkouts[i].id, tx.Checkouts[i] );
} }
m_committed = m_committed.AddRange(committed); m_committed = m_committed.AddRange( committed );
foreach( var v in tx.Adds ) foreach( var v in tx.Adds )
{ {
@ -157,7 +160,7 @@ public enum TxStates
//This only works for a single thread //This only works for a single thread
public class Tx<TID, T>: IDisposable where T : IID<TID> public class Tx<TID, T> : IDisposable where T : IID<TID>
{ {
internal ImmutableList<T> Checkouts => m_checkouts; internal ImmutableList<T> Checkouts => m_checkouts;
internal TxStates State => m_state; internal TxStates State => m_state;
@ -166,7 +169,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
internal Tx( int start, DB<TID, T> db ) internal Tx( int start, DB<TID, T> db )
: :
this(start, Option.None<Tx<TID, T>>(), db) this( start, Option.None<Tx<TID, T>>(), db )
{ {
} }
@ -174,7 +177,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
{ {
m_start = start; m_start = start;
m_parentTx = parentTx; m_parentTx = parentTx;
m_childTx = m_childTx.Add(this); m_childTx = m_childTx.Add( this );
m_db = db; m_db = db;
m_state = TxStates.Running; m_state = TxStates.Running;
} }
@ -187,7 +190,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
GC.SuppressFinalize( this ); GC.SuppressFinalize( this );
} }
public void Dispose(bool isFromDispose ) public void Dispose( bool isFromDispose )
{ {
if( isFromDispose ) if( isFromDispose )
{ {
@ -206,7 +209,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
public void add( T obj ) public void add( T obj )
{ {
m_adds = m_adds.Add(obj); m_adds = m_adds.Add( obj );
} }

View File

@ -41,7 +41,7 @@ namespace db
public Processor( DB<TID, T> db, System<TID, T> sys ) public Processor( DB<TID, T> db, System<TID, T> sys )
{ {
DB = db; DB = db;
Sys= sys; Sys = sys;
m_state = State.Prestartup; m_state = State.Prestartup;
} }

View File

@ -15,7 +15,7 @@ namespace db
struct TimedAction : IComparable<TimedAction> struct TimedAction : IComparable<TimedAction>
{ {
public long when; public long when;
public Act act; public Act act;
public TimedAction( long when, Act act ) public TimedAction( long when, Act act )
{ {
@ -54,7 +54,7 @@ namespace db
public SemaphoreSlim ActsExist => m_actsExist; public SemaphoreSlim ActsExist => m_actsExist;
public DB<TID, T> DB { get; private set; } public DB<TID, T> DB { get; private set; }
public bool Running { get; private set; } public bool Running { get; private set; }
public System( res.Ref<SystemCfg> cfg, DB<TID, T> db ) public System( res.Ref<SystemCfg> cfg, DB<TID, T> db )
{ {
@ -73,7 +73,7 @@ namespace db
} }
else if( m_cfg.res.Cores < 1.0f ) else if( m_cfg.res.Cores < 1.0f )
{ {
procCount = (int) ((float)Environment.ProcessorCount * m_cfg.res.Cores); procCount = (int)( (float)Environment.ProcessorCount * m_cfg.res.Cores );
} }
else else
{ {
@ -235,7 +235,7 @@ namespace db
public void addTimedActions() public void addTimedActions()
{ {
var sortedFutureActions = m_futureActions.Sort( ); var sortedFutureActions = m_futureActions.Sort();
var future = TimeSpan.FromMilliseconds( 33.33333 ); var future = TimeSpan.FromMilliseconds( 33.33333 );
@ -281,7 +281,7 @@ namespace db
res.Ref<SystemCfg> m_cfg; res.Ref<SystemCfg> m_cfg;
SemaphoreSlim m_actsExist = new SemaphoreSlim(0); SemaphoreSlim m_actsExist = new SemaphoreSlim( 0 );
Random m_rand = new Random(); Random m_rand = new Random();

View File

@ -1,11 +1,11 @@
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using imm;
namespace exp; namespace exp;
abstract public record class Exp<T> : imm.Versioned<Exp<T>> abstract public record class Exp<T> : io.Versioned<Exp<T>>
{ {
protected Exp() protected Exp()
: :

View File

@ -9,7 +9,8 @@ namespace fsm;
public class Context{ public class Context
{
} }
@ -17,11 +18,11 @@ public class State<T, CTX>
where T : State<T, CTX> where T : State<T, CTX>
where CTX : Context where CTX : Context
{ {
virtual public void onEnter(CTX ctx, State<T, CTX> oldState) virtual public void onEnter( CTX ctx, State<T, CTX> oldState )
{ {
} }
virtual public void onExit(CTX ctx, State<T, CTX> newState) virtual public void onExit( CTX ctx, State<T, CTX> newState )
{ {
} }
} }
@ -34,7 +35,7 @@ public class FSM<T, CTX, ST>
public CTX Context { get; private set; } public CTX Context { get; private set; }
public ST State { get; private set; } public ST State { get; private set; }
public FSM(CTX context, ST state) public FSM( CTX context, ST state )
{ {
Context = context; Context = context;
State = state; State = state;
@ -42,12 +43,12 @@ public class FSM<T, CTX, ST>
State.onEnter( Context, state ); State.onEnter( Context, state );
} }
public void transition(ST newState, string reason = "", public void transition( ST newState, string reason = "",
[CallerMemberName] string member = "", [CallerMemberName] string member = "",
[CallerFilePath] string path = "", [CallerFilePath] string path = "",
[CallerLineNumber] int line = 0 ) [CallerLineNumber] int line = 0 )
{ {
log.debug( $"{GetType().Name} switching to {newState.GetType().Name}from {State.GetType().Name} bcs {reason} Code {log.relativePath(path)}:({line}): {member}" ); log.debug( $"{GetType().Name} switching to {newState.GetType().Name}from {State.GetType().Name} bcs {reason} Code {log.relativePath( path )}:({line}): {member}" );
State.onExit( Context, newState ); State.onExit( Context, newState );
newState.onEnter( Context, State ); newState.onEnter( Context, State );

View File

@ -1,35 +1,35 @@
#nullable enable #nullable enable
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
/// <summary> /// <summary>
/// Base context for an FSM. /// Base context for an FSM.
/// MUST inherit from imm.Recorded<TSelf> or Timed<TSelf> in your concrete class. /// MUST inherit from io.Recorded<TSelf> or Timed<TSelf> in your concrete class.
/// </summary> /// </summary>
/// <typeparam name="TSelf">The concrete Context type.</typeparam> /// <typeparam name="TSelf">The concrete Context type.</typeparam>
public abstract record class FsmContextBase<TSelf> : imm.Recorded<TSelf> public abstract record class FsmContextBase<TSelf> : io.Recorded<TSelf>
where TSelf : FsmContextBase<TSelf> where TSelf : FsmContextBase<TSelf>
{ {
// Required for 'with' expressions. // Required for 'with' expressions.
protected FsmContextBase(imm.Recorded<TSelf> original) : base(original) { } protected FsmContextBase( io.Recorded<TSelf> original ) : base( original ) { }
protected FsmContextBase() { } protected FsmContextBase() { }
} }
/// <summary> /// <summary>
/// Base state for an FSM. /// Base state for an FSM.
/// MUST inherit from imm.Recorded<TSelf> or Timed<TSelf> in your concrete class. /// MUST inherit from io.Recorded<TSelf> or Timed<TSelf> in your concrete class.
/// </summary> /// </summary>
/// <typeparam name="TSelf">The concrete State type.</typeparam> /// <typeparam name="TSelf">The concrete State type.</typeparam>
/// <typeparam name="TCtx">The concrete Context type (must be based on FsmContextBase).</typeparam> /// <typeparam name="TCtx">The concrete Context type (must be based on FsmContextBase).</typeparam>
public abstract record class FsmStateBase<TSelf, TCtx> : imm.Recorded<TSelf> public abstract record class FsmStateBase<TSelf, TCtx> : io.Recorded<TSelf>
where TSelf : FsmStateBase<TSelf, TCtx> where TSelf : FsmStateBase<TSelf, TCtx>
where TCtx : FsmContextBase<TCtx> where TCtx : FsmContextBase<TCtx>
{ {
/// <summary> /// <summary>
/// Called when entering this state. /// Called when entering this state.
/// </summary> /// </summary>
public virtual (TCtx Context, TSelf State) OnEnter(TCtx context, FsmStateBase<TSelf, TCtx> oldState) public virtual (TCtx Context, TSelf State) OnEnter( TCtx context, FsmStateBase<TSelf, TCtx> oldState )
{ {
return (context, (TSelf)this); return (context, (TSelf)this);
} }
@ -37,24 +37,24 @@ public abstract record class FsmStateBase<TSelf, TCtx> : imm.Recorded<TSelf>
/// <summary> /// <summary>
/// Called when exiting this state. /// Called when exiting this state.
/// </summary> /// </summary>
public virtual (TCtx Context, TSelf State) OnExit(TCtx context, FsmStateBase<TSelf, TCtx> newState) public virtual (TCtx Context, TSelf State) OnExit( TCtx context, FsmStateBase<TSelf, TCtx> newState )
{ {
return (context, (TSelf)this); return (context, (TSelf)this);
} }
// Required for 'with' expressions. // Required for 'with' expressions.
protected FsmStateBase(imm.Recorded<TSelf> original) : base(original) { } protected FsmStateBase( io.Recorded<TSelf> original ) : base( original ) { }
protected FsmStateBase() { } protected FsmStateBase() { }
} }
/// <summary> /// <summary>
/// An immutable FSM base class. /// An immutable FSM base class.
/// MUST inherit from imm.Recorded<TSelf> or Timed<TSelf> in your concrete class. /// MUST inherit from io.Recorded<TSelf> or Timed<TSelf> in your concrete class.
/// </summary> /// </summary>
/// <typeparam name="TSelf">The concrete FSM type.</typeparam> /// <typeparam name="TSelf">The concrete FSM type.</typeparam>
/// <typeparam name="TState">The concrete State type.</typeparam> /// <typeparam name="TState">The concrete State type.</typeparam>
/// <typeparam name="TCtx">The concrete Context type.</typeparam> /// <typeparam name="TCtx">The concrete Context type.</typeparam>
public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf> public abstract record class FsmBase<TSelf, TState, TCtx> : io.Recorded<TSelf>
where TSelf : FsmBase<TSelf, TState, TCtx> where TSelf : FsmBase<TSelf, TState, TCtx>
where TState : FsmStateBase<TState, TCtx> where TState : FsmStateBase<TState, TCtx>
where TCtx : FsmContextBase<TCtx> where TCtx : FsmContextBase<TCtx>
@ -62,14 +62,14 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
public TCtx Context { get; init; } public TCtx Context { get; init; }
public TState State { get; init; } public TState State { get; init; }
protected FsmBase(TCtx initialContext, TState initialState) protected FsmBase( TCtx initialContext, TState initialState )
{ {
Context = initialContext; Context = initialContext;
State = initialState; State = initialState;
} }
// Required for 'with' expressions. // Required for 'with' expressions.
protected FsmBase(imm.Recorded<TSelf> original) : base(original) protected FsmBase( io.Recorded<TSelf> original ) : base( original )
{ {
var o = original as FsmBase<TSelf, TState, TCtx>; var o = original as FsmBase<TSelf, TState, TCtx>;
Context = o!.Context; Context = o!.Context;
@ -78,7 +78,7 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
/// <summary> /// <summary>
/// Transitions the FSM. It automatically uses the 'Process' /// Transitions the FSM. It automatically uses the 'Process'
/// method appropriate for imm.Recorded or Timed, thanks to virtual overrides. /// method appropriate for io.ecorded or Timed, thanks to virtual overrides.
/// </summary> /// </summary>
public TSelf Transition( public TSelf Transition(
TState newState, TState newState,
@ -86,14 +86,14 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
[CallerMemberName] string memberName = "", [CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "", [CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0, [CallerLineNumber] int lineNumber = 0,
[CallerArgumentExpression("newState")] string expression = "") [CallerArgumentExpression( "newState" )] string expression = "" )
{ {
Console.WriteLine($"[FSM] Transition: {State.GetType().Name} -> {newState.GetType().Name}. Reason: {reason}"); Console.WriteLine( $"[FSM] Transition: {State.GetType().Name} -> {newState.GetType().Name}. Reason: {reason}" );
var (ctxAfterExit, stateAfterExit) = State.OnExit(Context, newState); var (ctxAfterExit, stateAfterExit) = State.OnExit( Context, newState );
var (ctxAfterEnter, stateAfterEnter) = newState.OnEnter(ctxAfterExit, stateAfterExit); var (ctxAfterEnter, stateAfterEnter) = newState.OnEnter( ctxAfterExit, stateAfterExit );
// Since 'this' is at least 'imm.Recorded<TSelf>', we can call the // Since 'this' is at least 'io.Recorded<TSelf>', we can call the
// detailed 'Process'. If 'this' is actually 'Timed<TSelf>', C#'s // detailed 'Process'. If 'this' is actually 'Timed<TSelf>', C#'s
// virtual dispatch will call the 'Timed' override automatically. // virtual dispatch will call the 'Timed' override automatically.
return Process( return Process(

View File

@ -1,366 +1,31 @@
#nullable enable //#nullable enable
using System; using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
namespace imm;
/// <summary> /// <summary>
/// Represents the base interface for versioned, immutable objects. /// Helper static class for processing immutable objects using a 'ref' pattern.
/// Provides access to metadata and potentially the previous version. /// Provides different levels of processing based on the type.
/// </summary> /// </summary>
public interface Obj public static class imm
{ {
/// <summary> /// <summary>
/// Gets the base metadata associated with this version. /// Processes a 'Versioned' object (Level 1).
/// </summary> /// </summary>
Metadata_Versioned Meta { get; } public static T LightProcess<T>(
ref T obj,
/// <summary>
/// Gets the previous version as a base object, if available.
/// Returns null if this is the first version or if history is not tracked.
/// </summary>
Obj? Old { get; }
/// <summary>
/// Creates a new version without functional change.
/// Returns the new version as an Obj.
/// </summary>
Obj Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 );
}
/// <summary>
/// Obj delegate for change notifications.
/// </summary>
public delegate void ChangeDelegate<T>( T? oldVersion, T newVersion );
/// <summary>
/// Represents a generic interface for immutable objects,
/// providing access to basic processing functions and change notifications.
/// </summary>
public interface Obj<T> : Obj where T : Obj<T>
{
/// <summary>
/// Gets the change delegate associated with this object.
/// </summary>
[JsonIgnore]
ChangeDelegate<T> OnChange { get; set; }
/// <summary>
/// Applies a transformation and creates a new version using basic processing.
/// </summary>
T Process(
Func<T, T> fn, Func<T, T> fn,
string reason = "Processed", string reason = "Processed" // TODO Replace the string with a $"" that cinludes some info
[CallerMemberName] string dbgName = "", ) where T : io.Versioned<T>
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" );
/// <summary>
/// Creates a new version without a functional change using basic processing.
/// Uses 'new' to provide a type-safe return.
/// </summary>
new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 );
}
/*
static public class ObjExtensions
{
/// <summary>
/// Creates a new version of the object with the specified reason.
/// </summary>
public static T Record<T>( this T obj, string reason = "Recorded" ) where T : Obj
{ {
if( obj is Recorded<T> recorded ) obj = obj.Process( fn, reason );
{ return obj;
return recorded.Record( reason );
}
else if( obj is Versioned<T> versioned )
{
return versioned.Record( reason );
}
else
{
// Dont care
return obj;
}
}
}
*/
// --- Metadata Hierarchy ---
public interface VersionedMeta
{
public uint Version { get; }
public string Reason { get; }
}
/// <summary>
/// Obj metadata for version tracking.
/// </summary>
public record Metadata_Versioned
{
public uint Version { get; init; } = 1;
public string Reason { get; init; } = "Created";
}
public interface RecordedMeta : VersionedMeta
{
public string MemberName { get; }
public string FilePath { get; }
public int LineNumber { get; }
public string Expression { get; }
}
/// <summary>
/// Metadata for version and recording (debug/caller info, history).
/// </summary>
public record Metadata_Recorded : Metadata_Versioned, RecordedMeta
{
internal object? OldObject { get; init; } = null;
public string MemberName { get; init; } = "";
public string FilePath { get; init; } = "";
public int LineNumber { get; init; } = 0;
public string Expression { get; init; } = "";
}
public interface TimedMeta : RecordedMeta
{
public DateTime CreatedAt { get; }
public DateTime TouchedAt { get; }
}
/// <summary>
/// Metadata for version, recording, and timing.
/// </summary>
public record Metadata_Timed : Metadata_Recorded, TimedMeta
{
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
public DateTime TouchedAt { get; init; } = DateTime.UtcNow;
}
// --- Record Hierarchy ---
/// <summary>
/// Level 1: Basic versioning. Implements Obj<T>.
/// </summary>
public record class Versioned<T> : Obj<T> where T : Versioned<T>
{
public Metadata_Versioned Meta { get; init; } = new();
[DebuggerBrowsable( DebuggerBrowsableState.Never )]
[JsonIgnore]
public ChangeDelegate<T> OnChange { get; set; } = ( o, n ) => { };
public virtual Obj? Old => null;
Metadata_Versioned Obj.Meta => this.Meta;
[JsonIgnore]
Obj? Obj.Old => this.Old;
public Versioned() { }
protected Versioned( Versioned<T> original )
{
OnChange = original.OnChange;
Meta = original.Meta;
}
public virtual T Process(
Func<T, T> fn,
string reason = "Processed",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
var newVersion = next with
{
Meta = new Metadata_Versioned { /*...*/ },
OnChange = current.OnChange
};
newVersion.OnChange( current, newVersion );
return newVersion;
} }
/// <summary> /// <summary>
/// Basic Record. Made virtual. Implements Obj<T>.Record. /// Processes a 'Recorded' object (Level 2), capturing caller info.
/// </summary> /// </summary>
public virtual T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 ) => Process( t => t, reason, dbgName, dbgPath, dbgLine );
/// <summary>
/// Implements Obj.Record by calling the virtual T Record.
/// </summary>
Obj Obj.Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 ) => this.Record( reason, dbgName, dbgPath, dbgLine );
}
/// <summary>
/// Level 2: Adds history and caller info.
/// </summary>
public record class Recorded<T> : Versioned<T> where T : Recorded<T>
{
new public Metadata_Recorded Meta { get; init; } = new();
[JsonIgnore]
new public T? Old => Meta.OldObject as T;
//public override Obj? Old => this.Old;
//Metadata_Versioned Obj.Meta => this.Meta;
public Recorded() { }
protected Recorded( Recorded<T> original ) : base( original ) { Meta = original.Meta; }
public override T Process(
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
var newMeta = current.Meta with {
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgName,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = expStr,
OldObject = current,
};
var newVersion = next with { Meta = newMeta, OnChange = current.OnChange };
newVersion.OnChange( current, newVersion );
return newVersion;
}
public new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 )
{
return Process( t => t, reason, dbgName, dbgPath, dbgLine );
}
}
/// <summary>
/// Level 3: Adds timestamps.
/// </summary>
public record class Timed<T> : Recorded<T> where T : Timed<T>
{
new public Metadata_Timed Meta { get; init; } = new();
//Metadata_Versioned Obj.Meta => this.Meta;
public TimeSpan SinceLastTouch => Meta.TouchedAt - ( Old?.Meta as Metadata_Timed )?.TouchedAt ?? TimeSpan.Zero;
public TimeSpan TotalAge => Meta.TouchedAt - Meta.CreatedAt;
public Timed() { }
protected Timed( Timed<T> original ) : base( original ) { Meta = original.Meta; }
public override T Process(
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgMethod = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
/*
var newMeta = new Metadata_Timed
{
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgMethod,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = dbgExpression,
OldObject = current,
CreatedAt = current.Meta.CreatedAt,
TouchedAt = DateTime.UtcNow
};
*/
var newMeta = current.Meta with
{
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgMethod,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = dbgExpStr,
OldObject = current,
TouchedAt = DateTime.UtcNow
};
// Testing: Shouldnt need the OnChange
var newVersion = next with { Meta = newMeta };
newVersion.OnChange( current, newVersion );
return newVersion;
}
public new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 )
{
return Process( t => t, reason, dbgName, dbgPath, dbgLine );
}
}
/*
public static class TimedExt
{
public static T Process<T>( public static T Process<T>(
ref T obj, ref T obj,
Func<T, T> fn, Func<T, T> fn,
@ -368,11 +33,20 @@ public static class TimedExt
[CallerMemberName] string dbgName = "", [CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "", [CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0, [CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpression = "" [CallerArgumentExpression( "fn" )] string dbgExpression = "" )
) where T : imm.Timed<T> where T : io.Recorded<T> // Catches Recorded and Timed
{ {
// This will call the 'Timed' override if T is Timed,
// or the 'Recorded' override if T is Recorded.
obj = obj.Process( fn, reason, dbgName, dbgPath, dbgLine, dbgExpression ); obj = obj.Process( fn, reason, dbgName, dbgPath, dbgLine, dbgExpression );
return obj; return obj;
} }
public static string LogDiff<T>( T cur, T old, [CallerArgumentExpression( "cur" )] string dbgExpCur = "", [CallerArgumentExpression( "old" )] string dbgExpOld = "" )
{
return $"{dbgExpCur} changed from {old} to {cur}";
}
// No specific Process needed for Timed, as it's caught by Recorded<T>
// and its Process override handles the timing.
} }
*/

View File

@ -6,12 +6,12 @@ using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace imm; namespace io;
/// <summary> /// <summary>
/// An immutable list implementation that tracks history, metadata, and time. /// An immutable list implementation that tracks history, metadata, and time.
/// </summary> /// </summary>
public record class List<T> : Timed<List<T>>, IImmutableList<T> public record class List<T> : io.Timed<List<T>>, IImmutableList<T>
{ {
static public List<T> Empty { get; } = new(); static public List<T> Empty { get; } = new();
@ -19,7 +19,7 @@ public record class List<T> : Timed<List<T>>, IImmutableList<T>
public List() { } public List() { }
// Required for 'with' expressions to work with the base class hierarchy // Required for 'with' expressions to work with the base class hierarchy
protected List(Timed<List<T>> original) : base(original) { } protected List( io.Timed<List<T>> original ) : base( original ) { }
// Helper to apply changes using the Process method // Helper to apply changes using the Process method
private List<T> Change( private List<T> Change(
@ -29,54 +29,54 @@ public record class List<T> : Timed<List<T>>, IImmutableList<T>
[CallerLineNumber] int dbgLine = -1, [CallerLineNumber] int dbgLine = -1,
[CallerArgumentExpression( "listChange" )] string reason = "" ) [CallerArgumentExpression( "listChange" )] string reason = "" )
{ {
var newValues = listChange(Values); var newValues = listChange( Values );
return ReferenceEquals(Values, newValues) return ReferenceEquals( Values, newValues )
? this ? this
: Process(l => l with { Values = newValues }, reason, dbgMethod, dbgPath, dbgLine, reason); : Process( l => l with { Values = newValues }, reason, dbgMethod, dbgPath, dbgLine, reason );
} }
// --- IImmutableList<T> implementation using the Change helper --- // --- IImmutableList<T> implementation using the Change helper ---
public T this[int index] => Values[index]; public T this[int index] => Values[index];
public int Count => Values.Count; public int Count => Values.Count;
public List<T> Add(T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1) => Change(v => v.Add(value), dbgMethod, dbgPath, dbgLine); public List<T> Add( T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Add( value ), dbgMethod, dbgPath, dbgLine );
public List<T> AddRange(IEnumerable<T> items, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1) => Change(v => v.AddRange(items), dbgMethod, dbgPath, dbgLine); public List<T> AddRange( IEnumerable<T> items, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.AddRange( items ), dbgMethod, dbgPath, dbgLine );
public List<T> Clear([CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1) => Change(v => v.Clear(), dbgMethod, dbgPath, dbgLine); public List<T> Clear( [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Clear(), dbgMethod, dbgPath, dbgLine );
#region IImmutableList Implementati, dbgMethod, dbgPath, dbgLineon #region IImmutableList Implementati, dbgMethod, dbgPath, dbgLineon
public List<T> Insert( int index, T element, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Insert( index, element ) , dbgMethod, dbgPath, dbgLine); public List<T> Insert( int index, T element, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Insert( index, element ), dbgMethod, dbgPath, dbgLine );
public List<T> InsertRange( int index, IEnumerable<T> items, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.InsertRange( index, items ) , dbgMethod, dbgPath, dbgLine); public List<T> InsertRange( int index, IEnumerable<T> items, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.InsertRange( index, items ), dbgMethod, dbgPath, dbgLine );
public List<T> Remove( T value, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Remove( value, equalityComparer ) , dbgMethod, dbgPath, dbgLine); public List<T> Remove( T value, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Remove( value, equalityComparer ), dbgMethod, dbgPath, dbgLine );
public List<T> Remove( T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Remove( value, EqualityComparer<T>.Default , dbgMethod, dbgPath, dbgLine); public List<T> Remove( T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Remove( value, EqualityComparer<T>.Default, dbgMethod, dbgPath, dbgLine );
public List<T> RemoveAll( Predicate<T> match, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveAll( match ) , dbgMethod, dbgPath, dbgLine); public List<T> RemoveAll( Predicate<T> match, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveAll( match ), dbgMethod, dbgPath, dbgLine );
public List<T> RemoveAt( int index, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveAt( index ) , dbgMethod, dbgPath, dbgLine); public List<T> RemoveAt( int index, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveAt( index ), dbgMethod, dbgPath, dbgLine );
public List<T> RemoveRange( int index, int count, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveRange( index, count ) , dbgMethod, dbgPath, dbgLine); public List<T> RemoveRange( int index, int count, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveRange( index, count ), dbgMethod, dbgPath, dbgLine );
public List<T> RemoveRange( IEnumerable<T> items, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveRange( items, equalityComparer ) , dbgMethod, dbgPath, dbgLine); public List<T> RemoveRange( IEnumerable<T> items, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.RemoveRange( items, equalityComparer ), dbgMethod, dbgPath, dbgLine );
public List<T> Replace( T oldValue, T newValue, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Replace( oldValue, newValue, equalityComparer ) , dbgMethod, dbgPath, dbgLine); public List<T> Replace( T oldValue, T newValue, IEqualityComparer<T>? equalityComparer, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Replace( oldValue, newValue, equalityComparer ), dbgMethod, dbgPath, dbgLine );
public List<T> SetItem( int index, T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.SetItem( index, value ) , dbgMethod, dbgPath, dbgLine); public List<T> SetItem( int index, T value, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.SetItem( index, value ), dbgMethod, dbgPath, dbgLine );
public int IndexOf( T item, int index, int count, IEqualityComparer<T>? equalityComparer ) => Values.IndexOf( item, index, count, equalityComparer ?? EqualityComparer<T>.Default ); public int IndexOf( T item, int index, int count, IEqualityComparer<T>? equalityComparer ) => Values.IndexOf( item, index, count, equalityComparer ?? EqualityComparer<T>.Default );
public int LastIndexOf( T item, int index, int count, IEqualityComparer<T>? equalityComparer) => Values.LastIndexOf( item, index, count, equalityComparer ?? EqualityComparer<T>.Default ); public int LastIndexOf( T item, int index, int count, IEqualityComparer<T>? equalityComparer ) => Values.LastIndexOf( item, index, count, equalityComparer ?? EqualityComparer<T>.Default );
public int IndexOf( T item, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => IndexOf( item, 0, Count, EqualityComparer<T>.Default); public int IndexOf( T item, [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => IndexOf( item, 0, Count, EqualityComparer<T>.Default );
IImmutableList<T> IImmutableList<T>.Clear() => Clear(); IImmutableList<T> IImmutableList<T>.Clear() => Clear();
IImmutableList<T> IImmutableList<T>.Add( T value ) => Add( value ); IImmutableList<T> IImmutableList<T>.Add( T value ) => Add( value );
IImmutableList<T> IImmutableList<T>.AddRange( IEnumerable<T> items ) => AddRange( items ); IImmutableList<T> IImmutableList<T>.AddRange( IEnumerable<T> items ) => AddRange( items );
IImmutableList<T> IImmutableList<T>.Insert( int index, T element ) => Insert( index, element ); IImmutableList<T> IImmutableList<T>.Insert( int index, T element ) => Insert( index, element );
IImmutableList<T> IImmutableList<T>.InsertRange( int index, IEnumerable<T> items ) => InsertRange( index, items ); IImmutableList<T> IImmutableList<T>.InsertRange( int index, IEnumerable<T> items ) => InsertRange( index, items );
IImmutableList<T> IImmutableList<T>.Remove( T value, IEqualityComparer<T>? equalityComparer ) => Remove( value, equalityComparer ); IImmutableList<T> IImmutableList<T>.Remove( T value, IEqualityComparer<T>? equalityComparer ) => Remove( value, equalityComparer );
IImmutableList<T> IImmutableList<T>.RemoveAll( Predicate<T> match ) => RemoveAll( match ); IImmutableList<T> IImmutableList<T>.RemoveAll( Predicate<T> match ) => RemoveAll( match );
IImmutableList<T> IImmutableList<T>.RemoveAt( int index ) => RemoveAt( index ); IImmutableList<T> IImmutableList<T>.RemoveAt( int index ) => RemoveAt( index );
IImmutableList<T> IImmutableList<T>.RemoveRange( IEnumerable<T> items, IEqualityComparer<T>? equalityComparer ) => RemoveRange( items, equalityComparer ); IImmutableList<T> IImmutableList<T>.RemoveRange( IEnumerable<T> items, IEqualityComparer<T>? equalityComparer ) => RemoveRange( items, equalityComparer );
IImmutableList<T> IImmutableList<T>.RemoveRange( int index, int count ) => RemoveRange( index, count ); IImmutableList<T> IImmutableList<T>.RemoveRange( int index, int count ) => RemoveRange( index, count );
IImmutableList<T> IImmutableList<T>.Replace( T oldValue, T newValue, IEqualityComparer<T>? equalityComparer ) => Replace( oldValue, newValue, equalityComparer ); IImmutableList<T> IImmutableList<T>.Replace( T oldValue, T newValue, IEqualityComparer<T>? equalityComparer ) => Replace( oldValue, newValue, equalityComparer );
IImmutableList<T> IImmutableList<T>.SetItem( int index, T value ) => SetItem( index, value ); IImmutableList<T> IImmutableList<T>.SetItem( int index, T value ) => SetItem( index, value );
#endregion #endregion
// --- Standard Interfaces --- // --- Standard Interfaces ---
public IEnumerator<T> GetEnumerator() => Values.GetEnumerator(); public IEnumerator<T> GetEnumerator() => Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)Values).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ( (IEnumerable)Values ).GetEnumerator();
} }

View File

@ -1,4 +1,3 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace imm;

379
imm/io.cs Normal file
View File

@ -0,0 +1,379 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
namespace io;
/// <summary>
/// Represents the base interface for versioned, immutable objects.
/// Provides access to metadata and potentially the previous version.
/// </summary>
public interface Obj
{
/// <summary>
/// Gets the base metadata associated with this version.
/// </summary>
Metadata_Versioned Meta { get; }
/// <summary>
/// Gets the previous version as a base object, if available.
/// Returns null if this is the first version or if history is not tracked.
/// </summary>
Obj? DebugOld { get; }
/// <summary>
/// Creates a new version without functional change.
/// Returns the new version as an Obj.
/// </summary>
Obj Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 );
}
/// <summary>
/// Obj delegate for change notifications.
/// </summary>
public delegate void ChangeDelegate<T>( T? oldVersion, T newVersion );
/// <summary>
/// Represents a generic interface for immutable objects,
/// providing access to basic processing functions and change notifications.
/// </summary>
public interface Obj<T> : Obj where T : Obj<T>
{
/// <summary>
/// Gets the change delegate associated with this object.
/// </summary>
[JsonIgnore]
ChangeDelegate<T> OnChange { get; set; }
/// <summary>
/// Applies a transformation and creates a new version using basic processing.
/// </summary>
T Process(
Func<T, T> fn,
string reason = "Processed",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" );
/// <summary>
/// Creates a new version without a functional change using basic processing.
/// Uses 'new' to provide a type-safe return.
/// </summary>
new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 );
}
/*
static public class ObjExtensions
{
/// <summary>
/// Creates a new version of the object with the specified reason.
/// </summary>
public static T Record<T>( this T obj, string reason = "Recorded" ) where T : Obj
{
if( obj is Recorded<T> recorded )
{
return recorded.Record( reason );
}
else if( obj is Versioned<T> versioned )
{
return versioned.Record( reason );
}
else
{
// Dont care
return obj;
}
}
}
*/
// --- Metadata Hierarchy ---
public interface VersionedMeta
{
public uint Version { get; }
public string Reason { get; }
}
/// <summary>
/// Obj metadata for version tracking.
/// </summary>
public record Metadata_Versioned
{
public uint Version { get; init; } = 1;
public string Reason { get; init; } = "Created";
}
public interface RecordedMeta : VersionedMeta
{
public string MemberName { get; }
public string FilePath { get; }
public int LineNumber { get; }
public string Expression { get; }
}
/// <summary>
/// Metadata for version and recording (debug/caller info, history).
/// </summary>
public record Metadata_Recorded : Metadata_Versioned, RecordedMeta
{
internal object? OldObject { get; init; } = null;
public string MemberName { get; init; } = "";
public string FilePath { get; init; } = "";
public int LineNumber { get; init; } = 0;
public string Expression { get; init; } = "";
}
public interface TimedMeta : RecordedMeta
{
public DateTime CreatedAt { get; }
public DateTime TouchedAt { get; }
}
/// <summary>
/// Metadata for version, recording, and timing.
/// </summary>
public record Metadata_Timed : Metadata_Recorded, TimedMeta
{
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
public DateTime TouchedAt { get; init; } = DateTime.UtcNow;
}
// --- Record Hierarchy ---
/// <summary>
/// Level 1: Basic versioning. Implements Obj<T>.
/// </summary>
public record class Versioned<T> : Obj<T> where T : Versioned<T>
{
public Metadata_Versioned Meta { get; init; } = new();
[DebuggerBrowsable( DebuggerBrowsableState.Never )]
[JsonIgnore]
public ChangeDelegate<T> OnChange { get; set; } = ( o, n ) => { };
public virtual Obj? DebugOld => null;
Metadata_Versioned Obj.Meta => this.Meta;
[JsonIgnore]
Obj? Obj.DebugOld => this.DebugOld;
public Versioned() { }
protected Versioned( Versioned<T> original )
{
OnChange = original.OnChange;
Meta = original.Meta;
}
public virtual T Process(
Func<T, T> fn,
string reason = "Processed",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
var newVersion = next with
{
Meta = new Metadata_Versioned { /*...*/ },
OnChange = current.OnChange
};
newVersion.OnChange( current, newVersion );
return newVersion;
}
/// <summary>
/// Basic Record. Made virtual. Implements Obj<T>.Record.
/// </summary>
public virtual T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 ) => Process( t => t, reason, dbgName, dbgPath, dbgLine );
/// <summary>
/// Implements Obj.Record by calling the virtual T Record.
/// </summary>
Obj Obj.Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 ) => this.Record( reason, dbgName, dbgPath, dbgLine );
}
/// <summary>
/// Level 2: Adds history and caller info.
/// </summary>
public record class Recorded<T> : Versioned<T> where T : Recorded<T>
{
new public Metadata_Recorded Meta { get; init; } = new();
[JsonIgnore]
new public T? DebugOld => Meta.OldObject as T;
//public override Obj? DebugOld => this.DebugOld;
//Metadata_Versioned Obj.Meta => this.Meta;
public Recorded() { }
protected Recorded( Recorded<T> original ) : base( original ) { Meta = original.Meta; }
public override T Process(
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string expStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
var newMeta = current.Meta with
{
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgName,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = expStr,
OldObject = current,
};
var newVersion = next with { Meta = newMeta, OnChange = current.OnChange };
newVersion.OnChange( current, newVersion );
return newVersion;
}
public new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 )
{
return Process( t => t, reason, dbgName, dbgPath, dbgLine );
}
}
/// <summary>
/// Level 3: Adds timestamps.
/// </summary>
public record class Timed<T> : Recorded<T> where T : Timed<T>
{
new public Metadata_Timed Meta { get; init; } = new();
//Metadata_Versioned Obj.Meta => this.Meta;
public TimeSpan SinceLastTouch => Meta.TouchedAt - ( DebugOld?.Meta as Metadata_Timed )?.TouchedAt ?? TimeSpan.Zero;
public TimeSpan TotalAge => Meta.TouchedAt - Meta.CreatedAt;
public Timed() { }
protected Timed( Timed<T> original ) : base( original ) { Meta = original.Meta; }
public override T Process(
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgMethod = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpStr = "" )
{
var current = (T)this;
var next = fn( current );
if( ReferenceEquals( current, next ) )
return current;
/*
var newMeta = new Metadata_Timed
{
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgMethod,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = dbgExpression,
OldObject = current,
CreatedAt = current.Meta.CreatedAt,
TouchedAt = DateTime.UtcNow
};
*/
var newMeta = current.Meta with
{
Version = current.Meta.Version + 1,
Reason = reason,
MemberName = dbgMethod,
FilePath = dbgPath,
LineNumber = dbgLine,
Expression = dbgExpStr,
OldObject = current,
TouchedAt = DateTime.UtcNow
};
// Testing: Shouldnt need the OnChange
var newVersion = next with { Meta = newMeta };
newVersion.OnChange( current, newVersion );
return newVersion;
}
public new T Record(
string reason = "Recorded",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0 )
{
return Process( t => t, reason, dbgName, dbgPath, dbgLine );
}
}
/*
public static class TimedExt
{
public static T Process<T>(
ref T obj,
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpression = ""
) where T : io.Timed<T>
{
obj = obj.Process( fn, reason, dbgName, dbgPath, dbgLine, dbgExpression );
return obj;
}
}
*/

View File

@ -1,52 +0,0 @@
//#nullable enable
using System;
using System.Runtime.CompilerServices;
using imm;
/// <summary>
/// Helper static class for processing immutable objects using a 'ref' pattern.
/// Provides different levels of processing based on the type.
/// </summary>
public static class iu
{
/// <summary>
/// Processes a 'Versioned' object (Level 1).
/// </summary>
public static T LightProcess<T>(
ref T obj,
Func<T, T> fn,
string reason = "Processed" )
where T : Versioned<T>
{
obj = obj.Process( fn, reason );
return obj;
}
/// <summary>
/// Processes a 'Recorded' object (Level 2), capturing caller info.
/// </summary>
public static T Process<T>(
ref T obj,
Func<T, T> fn,
string reason = "",
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpression = "" )
where T : Recorded<T> // Catches Recorded and Timed
{
// This will call the 'Timed' override if T is Timed,
// or the 'Recorded' override if T is Recorded.
obj = obj.Process( fn, reason, dbgName, dbgPath, dbgLine, dbgExpression );
return obj;
}
public static string LogDiff<T>( T cur, T old, [CallerArgumentExpression( "cur" )] string dbgExpCur = "", [CallerArgumentExpression( "old" )] string dbgExpOld = "" )
{
return $"{dbgExpCur} changed from {old} to {cur}";
}
// No specific Process needed for Timed, as it's caught by Recorded<T>
// and its Process override handles the timing.
}

View File

@ -17,7 +17,7 @@ using System.Collections.Immutable;
namespace ser; namespace ser;
public record CodeGenConfig : imm.Recorded<CodeGenConfig> public record CodeGenConfig : io.Recorded<CodeGenConfig>
{ {
// Whitelists (if needed, otherwise rely on attributes/defaults) // Whitelists (if needed, otherwise rely on attributes/defaults)
public ImmutableDictionary<string, ImmutableList<string>> WLProps { get; init; } = ImmutableDictionary<string, ImmutableList<string>>.Empty; public ImmutableDictionary<string, ImmutableList<string>> WLProps { get; init; } = ImmutableDictionary<string, ImmutableList<string>>.Empty;
@ -33,14 +33,14 @@ public record CodeGenConfig : imm.Recorded<CodeGenConfig>
} }
public record GenMemberMeta( public record GenMemberMeta(
MemberInfo Info, MemberInfo Info,
Type Type, Type Type,
string Name, // Name for code generation (usually original) string Name, // Name for code generation (usually original)
bool IsPrimitive, bool IsPrimitive,
bool IsCollection, bool IsCollection,
Type? CollectionElementType, Type? CollectionElementType,
bool HasDo, bool HasDo,
bool HasDont bool HasDont
); );
public record TypeStructureInfo( public record TypeStructureInfo(
@ -55,46 +55,46 @@ public class TypeStructureAnalyzer
private readonly ConcurrentDictionary<Type, TypeStructureInfo> _cache = new(); private readonly ConcurrentDictionary<Type, TypeStructureInfo> _cache = new();
private readonly CodeGenConfig _cfg; private readonly CodeGenConfig _cfg;
public TypeStructureAnalyzer(CodeGenConfig cfg) => _cfg = cfg; public TypeStructureAnalyzer( CodeGenConfig cfg ) => _cfg = cfg;
public TypeStructureInfo Get(Type type) => _cache.GetOrAdd(type, BuildTypeInfo); public TypeStructureInfo Get( Type type ) => _cache.GetOrAdd( type, BuildTypeInfo );
private TypeStructureInfo BuildTypeInfo(Type type) private TypeStructureInfo BuildTypeInfo( Type type )
{ {
var members = new List<GenMemberMeta>(); var members = new List<GenMemberMeta>();
var typesTodo = type.GetCustomAttribute<ser.Ser>(true)?.Types ?? _cfg.TypesDefault; var typesTodo = type.GetCustomAttribute<ser.Ser>( true )?.Types ?? _cfg.TypesDefault;
bool doFields = typesTodo.HasFlag(ser.Types.Fields); bool doFields = typesTodo.HasFlag( ser.Types.Fields );
bool doProps = typesTodo.HasFlag(ser.Types.Props); bool doProps = typesTodo.HasFlag( ser.Types.Props );
// Track processed names to avoid duplicates (e.g., field + prop) // Track processed names to avoid duplicates (e.g., field + prop)
var processedNames = new HashSet<string>(); var processedNames = new HashSet<string>();
// Process Properties First (often preferred interface) // Process Properties First (often preferred interface)
if (doProps) if( doProps )
{ {
foreach (var pi in refl.GetAllProperties(type)) foreach( var pi in refl.GetAllProperties( type ) )
{ {
if (ProcessMember(pi, false, false, new HashSet<string>(), false, members)) if( ProcessMember( pi, false, false, new HashSet<string>(), false, members ) )
{ {
processedNames.Add(pi.Name); processedNames.Add( pi.Name );
} }
} }
} }
// Process Fields, avoiding those already covered by properties // Process Fields, avoiding those already covered by properties
if (doFields) if( doFields )
{ {
foreach (var fi in refl.GetAllFields(type)) foreach( var fi in refl.GetAllFields( type ) )
{ {
var (isBacking, propName) = IsBackingField(fi); var (isBacking, propName) = IsBackingField( fi );
string nameToTest = isBacking ? propName : fi.Name; string nameToTest = isBacking ? propName : fi.Name;
if (!processedNames.Contains(nameToTest)) if( !processedNames.Contains( nameToTest ) )
{ {
if(ProcessMember(fi, false, false, new HashSet<string>(), false, members)) if( ProcessMember( fi, false, false, new HashSet<string>(), false, members ) )
{ {
processedNames.Add(nameToTest); processedNames.Add( nameToTest );
} }
} }
} }
} }
@ -103,56 +103,63 @@ public class TypeStructureAnalyzer
type, type,
members, members,
type.IsValueType, type.IsValueType,
typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string) typeof( IEnumerable ).IsAssignableFrom( type ) && type != typeof( string )
); );
} }
private bool ProcessMember(MemberInfo mi, bool filter, bool doImpls, HashSet<string> whitelist, bool isImm, List<GenMemberMeta> members) private bool ProcessMember( MemberInfo mi, bool filter, bool doImpls, HashSet<string> whitelist, bool isImm, List<GenMemberMeta> members )
{ {
var (hasDo, hasDont, propName) = GetMemberAttributes(mi, out var actualMiForAtts); var (hasDo, hasDont, propName) = GetMemberAttributes( mi, out var actualMiForAtts );
if (hasDont) return false; if( hasDont )
if (mi.GetCustomAttribute<NonSerializedAttribute>(true) != null) return false; return false;
if (mi.Name.Contains("k__BackingField") && !propName.Any()) return false; // Skip if backing but no prop found if( mi.GetCustomAttribute<NonSerializedAttribute>( true ) != null )
return false;
if( mi.Name.Contains( "k__BackingField" ) && !propName.Any() )
return false; // Skip if backing but no prop found
string name = string.IsNullOrEmpty(propName) ? mi.Name : propName; string name = string.IsNullOrEmpty( propName ) ? mi.Name : propName;
// Add filtering logic if needed (based on whitelist, etc.) // Add filtering logic if needed (based on whitelist, etc.)
var type = (mi is FieldInfo fi) ? fi.FieldType : ((PropertyInfo)mi).PropertyType; var type = ( mi is FieldInfo fi ) ? fi.FieldType : ( (PropertyInfo)mi ).PropertyType;
bool isCollection = typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string); bool isCollection = typeof( IEnumerable ).IsAssignableFrom( type ) && type != typeof( string );
Type? elementType = isCollection ? GetElementType(type) : null; Type? elementType = isCollection ? GetElementType( type ) : null;
bool isPrimitive = Type.GetTypeCode(type) != TypeCode.Object && !isCollection; bool isPrimitive = Type.GetTypeCode( type ) != TypeCode.Object && !isCollection;
members.Add(new GenMemberMeta( members.Add( new GenMemberMeta(
mi, type, name, isPrimitive, isCollection, elementType, hasDo, hasDont mi, type, name, isPrimitive, isCollection, elementType, hasDo, hasDont
)); ) );
return true; return true;
} }
private (bool, string) IsBackingField(FieldInfo fi) private (bool, string) IsBackingField( FieldInfo fi )
{ {
if (fi.Name.StartsWith("<") && fi.Name.EndsWith("BackingField")) if( fi.Name.StartsWith( "<" ) && fi.Name.EndsWith( "BackingField" ) )
{ {
var gtIndex = fi.Name.IndexOf('>'); var gtIndex = fi.Name.IndexOf( '>' );
if (gtIndex > 1) { if( gtIndex > 1 )
return (true, fi.Name.Substring(1, gtIndex - 1)); {
return (true, fi.Name.Substring( 1, gtIndex - 1 ));
} }
} }
return (false, ""); return (false, "");
} }
private (bool hasDo, bool hasDont, string propName) GetMemberAttributes(MemberInfo mi, out MemberInfo actualMi) private (bool hasDo, bool hasDont, string propName) GetMemberAttributes( MemberInfo mi, out MemberInfo actualMi )
{ {
actualMi = mi; actualMi = mi;
string propName = ""; string propName = "";
if (mi is FieldInfo fi && IsBackingField(fi).Item1) if( mi is FieldInfo fi && IsBackingField( fi ).Item1 )
{ {
propName = IsBackingField(fi).Item2; propName = IsBackingField( fi ).Item2;
var propInfo = mi.DeclaringType?.GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var propInfo = mi.DeclaringType?.GetProperty( propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
if (propInfo != null) actualMi = propInfo; if( propInfo != null )
} else if (mi is PropertyInfo) { actualMi = propInfo;
propName = mi.Name; }
else if( mi is PropertyInfo )
{
propName = mi.Name;
} }
return ( return (
@ -162,11 +169,13 @@ public class TypeStructureAnalyzer
); );
} }
private Type GetElementType(Type collectionType) private Type GetElementType( Type collectionType )
{ {
if (collectionType.IsArray) return collectionType.GetElementType()!; if( collectionType.IsArray )
if (collectionType.IsGenericType) return collectionType.GetGenericArguments().Last(); // Usually last (e.g., List<T>, Dict<K,V>) return collectionType.GetElementType()!;
return typeof(object); // Fallback if( collectionType.IsGenericType )
return collectionType.GetGenericArguments().Last(); // Usually last (e.g., List<T>, Dict<K,V>)
return typeof( object ); // Fallback
} }
// Add GetFilters and FilterField if needed, or simplify as above // Add GetFilters and FilterField if needed, or simplify as above

View File

@ -139,7 +139,7 @@ namespace lib
private string fromStr = ""; private string fromStr = "";
void SetFromStr( Stream stream ) void SetFromStr( Stream stream )
{ {
fromStr = stream.ToString() ?? "{null}"; fromStr = stream.ToString() ?? "{null}";
@ -186,7 +186,8 @@ namespace lib
doc.Load( reader ); doc.Load( reader );
if( doc.DocumentElement == null ) return null; if( doc.DocumentElement == null )
return null;
if( t == null ) if( t == null )
return Deserialize( doc.DocumentElement ); return Deserialize( doc.DocumentElement );
@ -256,7 +257,8 @@ namespace lib
{ {
TypeCode typeCode = Type.GetTypeCode( type ); TypeCode typeCode = Type.GetTypeCode( type );
if( _cfg.VerboseLogging ) log.info( $"{type.FriendlyName()}.{name} {existing} {mi?.Name}" ); if( _cfg.VerboseLogging )
log.info( $"{type.FriendlyName()}.{name} {existing} {mi?.Name}" );
if( typeCode != TypeCode.Object ) if( typeCode != TypeCode.Object )
{ {
@ -276,7 +278,8 @@ namespace lib
if( obj is ser.I_Serialize iser ) if( obj is ser.I_Serialize iser )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
obj = iser.OnDeserialize( null ); obj = iser.OnDeserialize( null );
} }
@ -314,7 +317,8 @@ namespace lib
private object DeserializeConcrete( XmlElement elem, MemberInfo mi, string name, Type type ) private object DeserializeConcrete( XmlElement elem, MemberInfo mi, string name, Type type )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
string val = ""; string val = "";
@ -398,7 +402,8 @@ namespace lib
private object HydrateObject( XmlElement elem, MemberInfo mi, Type finalType, object obj ) private object HydrateObject( XmlElement elem, MemberInfo mi, Type finalType, object obj )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
if( obj is IList ) if( obj is IList )
{ {
@ -488,9 +493,10 @@ namespace lib
private object HydrateObjectOfNarrowType( XmlElement elem, MemberInfo mi, Type narrowType, object obj ) private object HydrateObjectOfNarrowType( XmlElement elem, MemberInfo mi, Type narrowType, object obj )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
var isImm = typeof(imm.Obj).IsAssignableFrom( narrowType ); var isImm = typeof( io.Obj ).IsAssignableFrom( narrowType );
XmlNodeList allChildren = elem.ChildNodes; XmlNodeList allChildren = elem.ChildNodes;
@ -536,7 +542,7 @@ namespace lib
name = refl.TypeToIdentifier( name ); name = refl.TypeToIdentifier( name );
// @@@ TODO This doesnt yet handle propNames! // @@@ TODO This doesnt yet handle propNames!
if( !doAtt.Any() && FilterField( filterFields, doImpls, whitelistFields, childFi as MemberInfo, name ) ) if( !doAtt.Any() && FilterField( filterFields, doImpls, whitelistFields, childFi as MemberInfo, name ) )
continue; continue;
var useFieldName = true; var useFieldName = true;
@ -625,7 +631,7 @@ namespace lib
{ {
object existingObj = childPi.GetValue( obj ); object existingObj = childPi.GetValue( obj );
object childObj = DeserializeConcrete( elem, childPi, name, childPi.PropertyType ); object childObj = DeserializeConcrete( elem, childPi, name, childPi.PropertyType );
if( setMethod != null ) if( setMethod != null )
{ {
@ -642,13 +648,13 @@ namespace lib
} }
} }
if(!isImm) if( !isImm )
{ {
return obj; return obj;
} }
else else
{ {
var imm = obj as imm.Obj; var imm = obj as io.Obj;
var newObj = imm.Record( $"From XML {fromStr}:{elem.ParentNode?.Name}{elem.Name}" ); var newObj = imm.Record( $"From XML {fromStr}:{elem.ParentNode?.Name}{elem.Name}" );
return newObj; return newObj;
} }
@ -686,7 +692,8 @@ namespace lib
int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1;
if( _cfg.VerboseLogging ) log.info( $"{finalType?.FriendlyName()}({type?.FriendlyName()}) refInt {refInt} exitingObj = {obj?.ToString()}" ); if( _cfg.VerboseLogging )
log.info( $"{finalType?.FriendlyName()}({type?.FriendlyName()}) refInt {refInt} exitingObj = {obj?.ToString()}" );
obj = createObject( elem, finalType, refInt, obj ); obj = createObject( elem, finalType, refInt, obj );
@ -695,7 +702,8 @@ namespace lib
private object DeserializeList( XmlElement elem, MemberInfo mi, Type type, IList list ) private object DeserializeList( XmlElement elem, MemberInfo mi, Type type, IList list )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
XmlNodeList arrNodeList = elem.ChildNodes; XmlNodeList arrNodeList = elem.ChildNodes;
@ -731,7 +739,8 @@ namespace lib
typeElem = typeof( KeyValuePair<,> ).MakeGenericType( type.GenericTypeArguments ); typeElem = typeof( KeyValuePair<,> ).MakeGenericType( type.GenericTypeArguments );
} }
if( _cfg.VerboseLogging ) log.info( $"DserCol {type.GetType().FriendlyName()} {typeElem.Name} into reflT {mi.ReflectedType.FriendlyName()} declT {mi.DeclaringType.FriendlyName()} {mi.Name}" ); if( _cfg.VerboseLogging )
log.info( $"DserCol {type.GetType().FriendlyName()} {typeElem.Name} into reflT {mi.ReflectedType.FriendlyName()} declT {mi.DeclaringType.FriendlyName()} {mi.Name}" );
string refString = elem.GetAttribute( "ref" ); string refString = elem.GetAttribute( "ref" );
int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1;
@ -776,7 +785,8 @@ namespace lib
var typeGen = Type.MakeGenericSignatureType( type ); var typeGen = Type.MakeGenericSignatureType( type );
if( _cfg.VerboseLogging ) log.info( $"TypeGen: {typeGen.FriendlyName()}" ); if( _cfg.VerboseLogging )
log.info( $"TypeGen: {typeGen.FriendlyName()}" );
if( type == typeof( ImmutableArray<> ).MakeGenericType( typeElem ) ) if( type == typeof( ImmutableArray<> ).MakeGenericType( typeElem ) )
{ {
@ -833,7 +843,8 @@ namespace lib
private object DeserializeArray( XmlElement elem, MemberInfo mi, Type type ) private object DeserializeArray( XmlElement elem, MemberInfo mi, Type type )
{ {
if( _cfg.VerboseLogging ) log.info( $"" ); if( _cfg.VerboseLogging )
log.info( $"" );
Type typeElem = type.GetElementType(); Type typeElem = type.GetElementType();
@ -883,7 +894,8 @@ namespace lib
if( _cfg.datastructure == Datastructure.Graph && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) if( _cfg.datastructure == Datastructure.Graph && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) )
{ {
if( _cfg.VerboseLogging ) log.info( $"Reuse object" ); if( _cfg.VerboseLogging )
log.info( $"Reuse object" );
return m_alreadySerialized[refInt]; return m_alreadySerialized[refInt];
} }
@ -893,7 +905,8 @@ namespace lib
if( isProxy ) if( isProxy )
{ {
if( _cfg.VerboseLogging ) log.info( $"use Proxy" ); if( _cfg.VerboseLogging )
log.info( $"use Proxy" );
object obj = null; object obj = null;
var tryType = type; var tryType = type;
@ -937,7 +950,8 @@ namespace lib
if( isSubclass ) if( isSubclass )
{ {
if( _cfg.VerboseLogging ) log.info( $"Using existing obj {existingObj?.ToString()}" ); if( _cfg.VerboseLogging )
log.info( $"Using existing obj {existingObj?.ToString()}" );
return existingObj; return existingObj;
} }
@ -953,12 +967,14 @@ namespace lib
try try
{ {
if( _cfg.VerboseLogging ) log.info( $"For {type.FriendlyName()} check for constructors" ); if( _cfg.VerboseLogging )
log.info( $"For {type.FriendlyName()} check for constructors" );
var cons = type.GetConstructor( Type.EmptyTypes ); var cons = type.GetConstructor( Type.EmptyTypes );
if( cons != null) if( cons != null )
{ {
if( _cfg.VerboseLogging ) log.info( $"Activator.CreateInstance" ); if( _cfg.VerboseLogging )
log.info( $"Activator.CreateInstance" );
obj = Activator.CreateInstance( type ); obj = Activator.CreateInstance( type );
} }
else else
@ -967,15 +983,18 @@ namespace lib
obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type ); obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type );
} }
if( _cfg.VerboseLogging ) log.info( $"Got obj {obj?.ToString()}" ); if( _cfg.VerboseLogging )
log.info( $"Got obj {obj?.ToString()}" );
} }
catch( Exception ) catch( Exception )
{ {
try try
{ {
if( _cfg.VerboseLogging ) log.info( $"GetUninitializedObject" ); if( _cfg.VerboseLogging )
log.info( $"GetUninitializedObject" );
obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type ); obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type );
if( _cfg.VerboseLogging ) log.info( $"Got obj {obj?.ToString()}" ); if( _cfg.VerboseLogging )
log.info( $"Got obj {obj?.ToString()}" );
} }
catch( Exception exInner ) catch( Exception exInner )
{ {
@ -1290,7 +1309,7 @@ namespace lib
HashSet<string> whitelistFields, whitelistProps; HashSet<string> whitelistFields, whitelistProps;
GetFilters( _cfg.TypesDefault, mi, narrowType, out filterFields, out filterProps, out doImpls, out doFields, out doProps, out whitelistFields, out whitelistProps ); GetFilters( _cfg.TypesDefault, mi, narrowType, out filterFields, out filterProps, out doImpls, out doFields, out doProps, out whitelistFields, out whitelistProps );
var isImm = typeof(imm.Obj).IsAssignableFrom( narrowType ); var isImm = typeof( io.Obj ).IsAssignableFrom( narrowType );
if( doFields || doImpls ) if( doFields || doImpls )
{ {
@ -1323,8 +1342,10 @@ namespace lib
if( isImm ) if( isImm )
{ {
if( name == "MetaStorage" ) continue; if( name == "MetaStorage" )
if( name == "Fn" ) continue; continue;
if( name == "Fn" )
continue;
} }
if( !doAtt.Any() && FilterField( filterFields, doImpls, whitelistFields, childFi as MemberInfo, name ) ) if( !doAtt.Any() && FilterField( filterFields, doImpls, whitelistFields, childFi as MemberInfo, name ) )
@ -1365,8 +1386,10 @@ namespace lib
if( isImm ) if( isImm )
{ {
if( name == "MetaStorage" ) continue; if( name == "MetaStorage" )
if( name == "Fn" ) continue; continue;
if( name == "Fn" )
continue;
} }
if( FilterField( filterProps, doImpls, whitelistProps, childPi as MemberInfo, name ) ) if( FilterField( filterProps, doImpls, whitelistProps, childPi as MemberInfo, name ) )
@ -1393,15 +1416,15 @@ namespace lib
var custWLProps = mi?.GetCustomAttribute<ser.ChildPropsAttribute>( true ); var custWLProps = mi?.GetCustomAttribute<ser.ChildPropsAttribute>( true );
filterFields = custWLFields != null; filterFields = custWLFields != null;
filterProps = custWLProps != null; filterProps = custWLProps != null;
var typesTodo = type.GetCustomAttribute<ser.Ser>( true )?.Types ?? TypesDefault; var typesTodo = type.GetCustomAttribute<ser.Ser>( true )?.Types ?? TypesDefault;
doImpls = typesTodo.HasFlag( ser.Types.Implied ); doImpls = typesTodo.HasFlag( ser.Types.Implied );
doFields = filterFields || typesTodo.HasFlag( ser.Types.Fields ); doFields = filterFields || typesTodo.HasFlag( ser.Types.Fields );
doProps = filterProps || typesTodo.HasFlag( ser.Types.Props ); doProps = filterProps || typesTodo.HasFlag( ser.Types.Props );
whitelistFields = new( custWLFields?.Values ?? new string[0] ); whitelistFields = new( custWLFields?.Values ?? new string[0] );
whitelistProps = new( custWLProps?.Values ?? new string[0] ); whitelistProps = new( custWLProps?.Values ?? new string[0] );
} }
private void SerializeArray( XmlWriter writer, MemberInfo mi, Type mType, object root, int depth ) private void SerializeArray( XmlWriter writer, MemberInfo mi, Type mType, object root, int depth )
@ -1413,8 +1436,10 @@ namespace lib
Type type = root.GetType(); Type type = root.GetType();
Type typeOfMember = typeof( object ); Type typeOfMember = typeof( object );
if( mi is FieldInfo fi ) typeOfMember = fi.FieldType; if( mi is FieldInfo fi )
if( mi is PropertyInfo pi ) typeOfMember = pi.PropertyType; typeOfMember = fi.FieldType;
if( mi is PropertyInfo pi )
typeOfMember = pi.PropertyType;
if( typeOfMember != type ) if( typeOfMember != type )
{ {
log.info( $"SerArr {typeOfMember.FriendlyName()} {mi?.Name} != {type.FriendlyName()}" ); log.info( $"SerArr {typeOfMember.FriendlyName()} {mi?.Name} != {type.FriendlyName()}" );

View File

@ -28,7 +28,7 @@ public static class LogGCExt
{ {
public static string MethodInfo( TraceEvent te, string prefix = "Method" ) public static string MethodInfo( TraceEvent te, string prefix = "Method" )
{ {
return $"{te.PayloadStringByName($"{prefix}Namespace")}.{te.PayloadStringByName($"{prefix}Name")}{te.PayloadStringByName($"{prefix}Signature")}"; return $"{te.PayloadStringByName( $"{prefix}Namespace" )}.{te.PayloadStringByName( $"{prefix}Name" )}{te.PayloadStringByName( $"{prefix}Signature" )}";
} }
public static string Get( this TraceEvent te, string name, string def = "" ) => te.PayloadStringByName( name ) ?? def; public static string Get( this TraceEvent te, string name, string def = "" ) => te.PayloadStringByName( name ) ?? def;
@ -37,14 +37,15 @@ public static class LogGCExt
{ {
var index = te.PayloadIndex( name ); var index = te.PayloadIndex( name );
if( index <= 0 ) return default; if( index <= 0 )
return default;
var value = te.PayloadValue( index ); var value = te.PayloadValue( index );
if( value.GetType() != typeof(T) ) if( value.GetType() != typeof( T ) )
{ {
log.warn( $"In {te.ID} Payload {name} is type {value.GetType().FriendlyName()} not {typeof(T).FriendlyName()}" ); log.warn( $"In {te.ID} Payload {name} is type {value.GetType().FriendlyName()} not {typeof( T ).FriendlyName()}" );
return default; return default;
} }
@ -66,43 +67,43 @@ public class LogGC
"FAKE_TEST", "FAKE_TEST",
"GC/BulkMovedObjectRanges", "GC/BulkMovedObjectRanges",
/* /*
"GC/BulkSurvivingObjectRanges", "GC/BulkSurvivingObjectRanges",
"GC/BulkRootStaticVar", "GC/BulkRootStaticVar",
"GC/BulkNode", "GC/BulkNode",
"GC/BulkEdge", "GC/BulkEdge",
"GC/BulkRootEdge", "GC/BulkRootEdge",
"GC/FinalizeObject", "GC/FinalizeObject",
"GC/SetGCHandle", "GC/SetGCHandle",
"GC/DestoryGCHandle", "GC/DestoryGCHandle",
"GC/MarkWithType", "GC/MarkWithType",
"GC/SuspendEEStart", "GC/SuspendEEStart",
"GC/SuspendEEStop", "GC/SuspendEEStop",
"GC/RestartEEStart", "GC/RestartEEStart",
"GC/RestartEEStop", "GC/RestartEEStop",
"GC/FinalizersStart", "GC/FinalizersStart",
// "GC/FinalizersStop", //Keep this one since it has details // "GC/FinalizersStop", //Keep this one since it has details
"GC/GenerationRange", "GC/GenerationRange",
"GC/FitBucketInfo", "GC/FitBucketInfo",
"TieredCompilation/BackgroundJitStart", "TieredCompilation/BackgroundJitStart",
"Type/BulkType", "Type/BulkType",
"TypeLoad/Start", "TypeLoad/Start",
"Method/R2RGetEntryPointStart", "Method/R2RGetEntryPointStart",
"Method/MethodDetails", "Method/MethodDetails",
"Method/MemoryAllocatedForJitCode", "Method/MemoryAllocatedForJitCode",
"Method/JittingStarted", "Method/JittingStarted",
"Method/ILToNativeMap", "Method/ILToNativeMap",
"ThreadPoolWorkerThread/Wait", "ThreadPoolWorkerThread/Wait",
"ILStub/StubGenerated" "ILStub/StubGenerated"
*/ */
"FAKE_END_IS_NOTHING" "FAKE_END_IS_NOTHING"
); );
@ -144,28 +145,33 @@ public class LogGC
{ {
var cat = catIn; var cat = catIn;
if( blacklist.Contains( te.EventName )) return; if( blacklist.Contains( te.EventName ) )
return;
{ {
var methodBeingCompiledNamespace = te.Get("MethodBeingCompiledNamespace"); var methodBeingCompiledNamespace = te.Get( "MethodBeingCompiledNamespace" );
if( ( methodBeingCompiledNamespace.StartsWith( "Microsoft" ) || methodBeingCompiledNamespace.StartsWith( "System" ) ) ) return; if( ( methodBeingCompiledNamespace.StartsWith( "Microsoft" ) || methodBeingCompiledNamespace.StartsWith( "System" ) ) )
return;
} }
{ {
var methodNamespace = te.PayloadStringByName("MethodNamespace") ?? ""; var methodNamespace = te.PayloadStringByName( "MethodNamespace" ) ?? "";
if( ( methodNamespace.StartsWith( "Microsoft" ) || methodNamespace.StartsWith( "System" ) ) ) return; if( ( methodNamespace.StartsWith( "Microsoft" ) || methodNamespace.StartsWith( "System" ) ) )
return;
} }
{ {
var ns = te.PayloadStringByName("TypeName") ?? ""; var ns = te.PayloadStringByName( "TypeName" ) ?? "";
if( ( ns.StartsWith( "Microsoft" ) || ns.StartsWith( "System" ) ) ) return; if( ( ns.StartsWith( "Microsoft" ) || ns.StartsWith( "System" ) ) )
return;
} }
{ {
var ns = te.PayloadStringByName("TypeLoad/Stop") ?? ""; var ns = te.PayloadStringByName( "TypeLoad/Stop" ) ?? "";
if( ns.StartsWith( "Godot" ) ) return; if( ns.StartsWith( "Godot" ) )
return;
} }
{ {
@ -174,16 +180,17 @@ public class LogGC
if( payloadIndex > 0 ) if( payloadIndex > 0 )
{ {
var count = (int)te.PayloadValue( payloadIndex ); var count = (int)te.PayloadValue( payloadIndex );
if( count > 16 ) return; if( count > 16 )
return;
} }
} }
//<Event EventName="Method/JittingStarted" MethodILSize="0x00000059" MethodNamespace="NilEvent" MethodName="DebugString" MethodSignature="instance class System.String ()" ClrInstanceID="0"/> //<Event EventName="Method/JittingStarted" MethodILSize="0x00000059" MethodNamespace="NilEvent" MethodName="DebugString" MethodSignature="instance class System.String ()" ClrInstanceID="0"/>
//<Event EventName="Method/LoadVerbose" MethodStartAddress="0x00000003045736B8" MethodSize="0x000001BC" MethodToken="0x060001BB" MethodFlags="Jitted" MethodNamespace="NilEvent" MethodName="DebugString" MethodSignature="instance class System.String ()" ClrInstanceID="0" ReJITID="0x00000000" OptimizationTier="MinOptJitted"/> //<Event EventName="Method/LoadVerbose" MethodStartAddress="0x00000003045736B8" MethodSize="0x000001BC" MethodToken="0x060001BB" MethodFlags="Jitted" MethodNamespace="NilEvent" MethodName="DebugString" MethodSignature="instance class System.String ()" ClrInstanceID="0" ReJITID="0x00000000" OptimizationTier="MinOptJitted"/>
//<Event EventName="Method/InliningFailed" MethodBeingCompiledNamespace="dynamicClass" MethodBeingCompiledName="InvokeStub_EventAttribute.set_Message" MethodBeingCompiledNameSignature="class System.Object (class System.Object,class System.Object,int*)" InlinerNamespace="dynamicClass" InlinerName="InvokeStub_EventAttribute.set_Message" InlinerNameSignature="class System.Object (class System.Object,class System.Object,int*)" InlineeNamespace="System.Diagnostics.Tracing.EventAttribute" InlineeName="set_Message" InlineeNameSignature="instance void (class System.String)" FailAlways="False" FailReason="uses NextCallReturnAddress intrinsic" ClrInstanceID="0"/> //<Event EventName="Method/InliningFailed" MethodBeingCompiledNamespace="dynamicClass" MethodBeingCompiledName="InvokeStub_EventAttribute.set_Message" MethodBeingCompiledNameSignature="class System.Object (class System.Object,class System.Object,int*)" InlinerNamespace="dynamicClass" InlinerName="InvokeStub_EventAttribute.set_Message" InlinerNameSignature="class System.Object (class System.Object,class System.Object,int*)" InlineeNamespace="System.Diagnostics.Tracing.EventAttribute" InlineeName="set_Message" InlineeNameSignature="instance void (class System.String)" FailAlways="False" FailReason="uses NextCallReturnAddress intrinsic" ClrInstanceID="0"/>
if( !te.EventName.StartsWith( "EventID") ) if( !te.EventName.StartsWith( "EventID" ) )
{ {
var logDetails = ""; var logDetails = "";
// Custom event displays // Custom event displays
@ -192,8 +199,10 @@ public class LogGC
var optTier = te.Get( "OptimizationTier" ); var optTier = te.Get( "OptimizationTier" );
var methodNamespace = te.Get( "MethodNamespace" ); var methodNamespace = te.Get( "MethodNamespace" );
if( optTier == "MinOptJitted" ) return; if( optTier == "MinOptJitted" )
if( methodNamespace.StartsWith( "FastSerialization" )) return; return;
if( methodNamespace.StartsWith( "FastSerialization" ) )
return;
log.info( $"{optTier} {LogGCExt.MethodInfo( te )}", cat: te.EventName ); log.info( $"{optTier} {LogGCExt.MethodInfo( te )}", cat: te.EventName );
@ -204,7 +213,8 @@ public class LogGC
{ {
var methodNamespace = te.Get( "MethodBeingCompiledNamespace" ); var methodNamespace = te.Get( "MethodBeingCompiledNamespace" );
if( methodNamespace.StartsWith( "FastSerialization" )) return; if( methodNamespace.StartsWith( "FastSerialization" ) )
return;
log.info( $"Inlining {te.Get( "FailReason" )} {te.Get( "OptimizationTier" )} {LogGCExt.MethodInfo( te, "MethodBeingCompiled" )}", cat: te.EventName ); log.info( $"Inlining {te.Get( "FailReason" )} {te.Get( "OptimizationTier" )} {LogGCExt.MethodInfo( te, "MethodBeingCompiled" )}", cat: te.EventName );
@ -218,7 +228,7 @@ public class LogGC
XmlDocument doc = new(); XmlDocument doc = new();
var stream = new MemoryStream(); var stream = new MemoryStream();
var writer = new StreamWriter(stream); var writer = new StreamWriter( stream );
writer.Write( val ); writer.Write( val );
writer.Flush(); writer.Flush();
stream.Position = 0; stream.Position = 0;
@ -265,7 +275,7 @@ public class LogGC
var lockId = te.Get<UInt64>( "LockID" ); var lockId = te.Get<UInt64>( "LockID" );
var objId = te.Get<UInt64>( "AssociatedObjectID" ); var objId = te.Get<UInt64>( "AssociatedObjectID" );
var testObj = Marshal.GetIUnknownForObject(objId); var testObj = Marshal.GetIUnknownForObject( objId );
var intPtrStr = te.PayloadStringByName( "AssociatedObjectID" ).Substring( 2 ); var intPtrStr = te.PayloadStringByName( "AssociatedObjectID" ).Substring( 2 );
@ -281,7 +291,7 @@ public class LogGC
var allocated = gch.IsAllocated; var allocated = gch.IsAllocated;
var obj = gch.Target; var obj = gch.Target;
log.info( $"Lock {lockId} Create {objId.ToString("X")} {obj?.GetType()?.Name} {obj}", cat: te.EventName ); log.info( $"Lock {lockId} Create {objId.ToString( "X" )} {obj?.GetType()?.Name} {obj}", cat: te.EventName );
//*/ //*/
} }
catch( Exception ex ) catch( Exception ex )
@ -303,7 +313,7 @@ public class LogGC
var objId = te.Get<UInt64>( "AssociatedObjectID" ); var objId = te.Get<UInt64>( "AssociatedObjectID" );
var threadId = te.Get<Int64>( "LockOwnerThreadID" ); var threadId = te.Get<Int64>( "LockOwnerThreadID" );
log.info( $"Lock {lockId} {te.Get( "ContentionFlags" )} in thread {threadId} on obj 0x{objId.ToString("X")} ", cat: te.EventName ); log.info( $"Lock {lockId} {te.Get( "ContentionFlags" )} in thread {threadId} on obj 0x{objId.ToString( "X" )} ", cat: te.EventName );
LogGeneric( te, "| Raw: " ); LogGeneric( te, "| Raw: " );
} }
@ -319,44 +329,44 @@ public class LogGC
} }
else if( te.EventName.StartsWith( "AssemblyLoader/" ) || te.EventName.StartsWith( "Loader/" ) ) else if( te.EventName.StartsWith( "AssemblyLoader/" ) || te.EventName.StartsWith( "Loader/" ) )
{ {
//AssemblyLoader/Start AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly //AssemblyLoader/Start AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly
//AssemblyLoader/Stop AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly Success ResultAssemblyName ResultAssemblyPath Cached //AssemblyLoader/Stop AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly Success ResultAssemblyName ResultAssemblyPath Cached
//Loader/AssemblyLoad AssemblyID AppDomainID AssemblyFlags FullyQualifiedAssemblyName BindingID //Loader/AssemblyLoad AssemblyID AppDomainID AssemblyFlags FullyQualifiedAssemblyName BindingID
//AssemblyLoader/ResolutionAttempted //AssemblyLoader/ResolutionAttempted
// AssemblyName AssemblyLoadContext Result ResultAssemblyName ResultAssemblyPath Stage ErrorMessage // AssemblyName AssemblyLoadContext Result ResultAssemblyName ResultAssemblyPath Stage ErrorMessage
//Loader/ModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath ManagedPdbSignature ManagedPdbAge ManagedPdbBuildPath //Loader/ModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath ManagedPdbSignature ManagedPdbAge ManagedPdbBuildPath
//Loader/DomainModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath AppDomainID //Loader/DomainModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath AppDomainID
//AssemblyLoader/KnownPathProbed FilePath Source Result //AssemblyLoader/KnownPathProbed FilePath Source Result
var appDomainId = te.Get( "AppDomainID" ); var appDomainId = te.Get( "AppDomainID" );
var asId = te.Get( "AssemblyID" ); var asId = te.Get( "AssemblyID" );
var asName = te.Get( "AssemblyName" ); var asName = te.Get( "AssemblyName" );
var asPath = te.Get( "AssemblyPath" ); var asPath = te.Get( "AssemblyPath" );
var asLC = te.Get( "AssemblyLoadContext" ); var asLC = te.Get( "AssemblyLoadContext" );
var reqAs = te.Get( "RequestingAssembly" ); var reqAs = te.Get( "RequestingAssembly" );
var reqAsLC = te.Get( "RequestingAssemblyLoadContext" ); var reqAsLC = te.Get( "RequestingAssemblyLoadContext" );
var reqAsName = te.Get( "ResultAssemblyName" ); var reqAsName = te.Get( "ResultAssemblyName" );
var reqAsPath = te.Get( "ResultAssemblyPath" ); var reqAsPath = te.Get( "ResultAssemblyPath" );
var success = te.Get( "Success" ); var success = te.Get( "Success" );
var cached = te.Get( "Cached" ); var cached = te.Get( "Cached" );
var errMsg = te.Get( "ErrorMessage" ); var errMsg = te.Get( "ErrorMessage" );
var stage = te.Get( "Stage" ); var stage = te.Get( "Stage" );
var result = te.Get( "Result" ); var result = te.Get( "Result" );
var source = te.Get( "Source" ); var source = te.Get( "Source" );
var modId = te.Get( "ModuleID" ); var modId = te.Get( "ModuleID" );
var modFlags = te.Get( "ModuleFlags" ); var modFlags = te.Get( "ModuleFlags" );
var modILPath = te.Get( "ModuleILPath" ); var modILPath = te.Get( "ModuleILPath" );
var modNativePath= te.Get( "ModuleNativePath" ); var modNativePath = te.Get( "ModuleNativePath" );
var manBuildPath= te.Get( "ManagedPdbBuildPath" ); var manBuildPath = te.Get( "ManagedPdbBuildPath" );
var fqaName = te.Get( "FullyQualifiedAssemblyName" ); var fqaName = te.Get( "FullyQualifiedAssemblyName" );
var bindingId = te.Get( "BindingID" ); var bindingId = te.Get( "BindingID" );
} }
@ -397,7 +407,7 @@ public class LogGC
//var eventDataStr = eventData.ToString(); //var eventDataStr = eventData.ToString();
Encoding enc = new UnicodeEncoding(false, false, true); Encoding enc = new UnicodeEncoding( false, false, true );
var eventDataUtf16 = enc.GetString( eventData ); var eventDataUtf16 = enc.GetString( eventData );
//var safeEventData = eventDataUtf16.Replace( (char)0, '\n' ); //var safeEventData = eventDataUtf16.Replace( (char)0, '\n' );

View File

@ -18,10 +18,10 @@ using System.Text;
/* /*
T O D O : T O D O :
x) Hook the C# prints from glue.
x) Fix
x) Refactor various logs in order to do automagic structured logging x) Refactor various logs in order to do automagic structured logging
ref: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/interpolated-string-handler ref: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/interpolated-string-handler
x) Add support for structured logging (e.g., JSON, XML)
x) Implement a centralized logger that can be used across the application
D O N E: D O N E:
@ -32,6 +32,63 @@ N O T  D O I N G :
*/ */
/*
// L L M
# Context: Logging Infrastructure (`log` static class)
**Strict Rule:** DO NOT use `Console.WriteLine`, `Debug.WriteLine`, or standard `ILogger`. Use the static `log` class for all diagnostics.
## Core Design Pattern
The logging system uses **Caller Info Attributes** (`[CallerMemberName]`, `[CallerFilePath]`, etc.) to automatically capture context. Do not manually format method names or file paths in messages.
## API Surface
### 1. Standard Levels. Standard goto loggin
* `log.trace(msg)`, `log.debug(msg)`, `log.info(msg)`
* `log.warn(msg)`, `log.high(msg)`
* `log.error(msg)`, `log.fatal(msg)`
* **Signature:** `(string msg, string cat = "", SourceLoc? loc = null)`
* *Note:* `cat` (Category) and `loc` (SourceLocation) are optional; the system auto-resolves `cat` based on directory structure if omitted.
### 2. Functional Pass-Throughs If necessary
Use these to log data flow without breaking the statement chain.
* `T log.var<T>(T val)`: Logs `name_of_var = value` and returns `val`.
* `T log.call<T>(Func<T> func)`: Logs entry, executes `func`, logs exit + result, returns result.
* `void log.call(Action func)`: Logs entry, executes `action`, logs exit.
* `log.operations(Action/Func)`: Wraps execution with info logs.
### 3. Special Types
* `Value<T>`: A struct wrapper to capture variable expressions alongside values. Use `log.Value(var)` when you need explicit expression capturing in custom constructs.
* `log.exception(Exception ex, string msg)`: specialized dump for exceptions.
* `log.logProps(object obj, string header)`: Reflection-based dump of all properties on an object.
## Idiomatic Usage Examples
**Good:**
```csharp
// Variable inspection (Pass-through)
int x = log.var(Calculate());
// Function tracing
var result = log.call(() => ComplexCalculation(input));
// Exception handling
try { ... }
catch (Exception ex) { log.exception(ex, "Calculation failed"); }
// Object Dump
log.logProps(userConfig, "Current Config State");
```
**Bad:**
```csharp
int x = Calculate();
Console.WriteLine("x is " + x); // Forbidden
log.info($"x = {x}"); // Redundant manual formatting
```
*/
public record struct Value<T>( T _val, string _exp = "" ) public record struct Value<T>( T _val, string _exp = "" )
{ {
public static T Default = default!; public static T Default = default!;
@ -190,7 +247,7 @@ static public class log
All = File | Console, All = File | Console,
} }
#region LogEvent
public struct LogEvent public struct LogEvent
{ {
public DateTime Time; public DateTime Time;
@ -254,6 +311,7 @@ static public class log
return logEvent; return logEvent;
} }
#endregion // LogEvent
public delegate void Log_delegate( LogEvent evt ); public delegate void Log_delegate( LogEvent evt );
@ -307,7 +365,7 @@ static public class log
pathPieces = path.Split( '/' ); pathPieces = path.Split( '/' );
} }
var lastPathPiece = pathPieces[pathPieces.Length - 1]; var lastPathPiece = pathPieces[pathPieces.Length - 1];
ImmutableInterlocked.AddOrUpdate( ref s_files, pathHash, lastPathPiece, ( key, value ) => { return lastPathPiece; } ); ImmutableInterlocked.AddOrUpdate( ref s_files, pathHash, lastPathPiece, ( key, value ) => { return lastPathPiece; } );
@ -404,32 +462,32 @@ static public class log
} }
[StackTraceHidden] [StackTraceHidden]
static public void info( string msg, string cat = "",SourceLoc? loc = null, static public void info( string msg, string cat = "", SourceLoc? loc = null,
[CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.Info, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.Info, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
[StackTraceHidden] [StackTraceHidden]
static public void debug( string msg, string cat = "",SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) static public void debug( string msg, string cat = "", SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.Debug, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.Debug, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
[StackTraceHidden] [StackTraceHidden]
static public void trace( string msg, string cat = "",SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) static public void trace( string msg, string cat = "", SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.Trace, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.Trace, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
[StackTraceHidden] [StackTraceHidden]
static public void warn( string msg, string cat = "",SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) static public void warn( string msg, string cat = "", SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.Warn, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.Warn, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
[StackTraceHidden] [StackTraceHidden]
static public void high( string msg, string cat = "",SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) static public void high( string msg, string cat = "", SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.High, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.High, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
@ -464,12 +522,12 @@ static public class log
[StackTraceHidden] [StackTraceHidden]
static public void fatal( string msg, string cat = "",SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" ) static public void fatal( string msg, string cat = "", SourceLoc? loc = null, [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1, [CallerMemberName] string dbgMethod = "", [CallerArgumentExpression( "msg" )] string dbgExp = "" )
{ {
logBase( msg, LogType.Fatal, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc ); logBase( msg, LogType.Fatal, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
} }
//new LogEvent( LogType.Raw, $"", "", 0, "", "lib.time", "", null ) //new LogEvent( LogType.Raw, $"", "", 0, "", "lib.time", "", null )
#endregion #endregion
@ -531,7 +589,7 @@ static public class log
foreach( var fr in stackTrace.GetFrames() ) foreach( var fr in stackTrace.GetFrames() )
{ {
logBase( $"{fr.Log}", LogType.Raw ); logBase( $"{fr.Log}", LogType.Raw );
} }
} }
@ -554,14 +612,14 @@ static public class log
} }
static public LogEvent logCreateEvent( string msg, LogType type = LogType.Debug, string dbgPath = "", int dbgLine = -1, string dbgMethod = "", string cat = "unk", string exp = "",SourceLoc? loc = null ) static public LogEvent logCreateEvent( string msg, LogType type = LogType.Debug, string dbgPath = "", int dbgLine = -1, string dbgMethod = "", string cat = "unk", string exp = "", SourceLoc? loc = null )
{ {
LogEvent evt = new LogEvent( type, msg, dbgPath, dbgLine, dbgMethod, cat, exp, loc ); LogEvent evt = new LogEvent( type, msg, dbgPath, dbgLine, dbgMethod, cat, exp, loc );
return evt; return evt;
} }
[StackTraceHidden] [StackTraceHidden]
static public void logBase( string msg, LogType type = LogType.Debug, string dbgPath = "", int dbgLine = -1, string dbgMethod = "", string cat = "unk", string exp = "",SourceLoc? loc = null ) static public void logBase( string msg, LogType type = LogType.Debug, string dbgPath = "", int dbgLine = -1, string dbgMethod = "", string cat = "unk", string exp = "", SourceLoc? loc = null )
{ {
var evt = logCreateEvent( msg, type, dbgPath, dbgLine, dbgMethod, cat, exp ); var evt = logCreateEvent( msg, type, dbgPath, dbgLine, dbgMethod, cat, exp );

View File

@ -31,9 +31,9 @@ namespace Tracing
private bool _monitorCpu = false; private bool _monitorCpu = false;
private readonly List<EventPipeProvider> _customProviders = new(); private readonly List<EventPipeProvider> _customProviders = new();
private Action<TraceEvent> _userCallback; private Action<TraceEvent> _userCallback;
private EventPipeSession _session; private EventPipeSession _session;
private TraceEventSource _traceLogSource; /// CHANGED private TraceEventSource _traceLogSource; /// CHANGED
private Task _processingTask; private Task _processingTask;

View File

@ -38,7 +38,7 @@ namespace math
/// </summary> /// </summary>
[DataStyle( DataStyle.Compact )] [DataStyle( DataStyle.Compact )]
[DataContract] [DataContract]
public struct AngleSingle: IComparable, IComparable<AngleSingle>, IEquatable<AngleSingle>, IFormattable public struct AngleSingle : IComparable, IComparable<AngleSingle>, IEquatable<AngleSingle>, IFormattable
{ {
/// <summary> /// <summary>
/// A value that specifies the size of a single degree. /// A value that specifies the size of a single degree.
@ -123,7 +123,7 @@ namespace math
/// </summary> /// </summary>
public void Wrap() public void Wrap()
{ {
float newangle = (float)Math.IEEERemainder(radians, MathUtil.TwoPi); float newangle = (float)Math.IEEERemainder( radians, MathUtil.TwoPi );
if( newangle <= -MathUtil.Pi ) if( newangle <= -MathUtil.Pi )
newangle += MathUtil.TwoPi; newangle += MathUtil.TwoPi;
@ -177,23 +177,23 @@ namespace math
{ {
get get
{ {
float degrees = MathUtil.RadiansToDegrees(radians); float degrees = MathUtil.RadiansToDegrees( radians );
if( degrees < 0 ) if( degrees < 0 )
{ {
float degreesfloor = (float)Math.Ceiling(degrees); float degreesfloor = (float)Math.Ceiling( degrees );
return ( degrees - degreesfloor ) * 60.0f; return ( degrees - degreesfloor ) * 60.0f;
} }
else else
{ {
float degreesfloor = (float)Math.Floor(degrees); float degreesfloor = (float)Math.Floor( degrees );
return ( degrees - degreesfloor ) * 60.0f; return ( degrees - degreesfloor ) * 60.0f;
} }
} }
set set
{ {
float degrees = MathUtil.RadiansToDegrees(radians); float degrees = MathUtil.RadiansToDegrees( radians );
float degreesfloor = (float)Math.Floor(degrees); float degreesfloor = (float)Math.Floor( degrees );
degreesfloor += value / 60.0f; degreesfloor += value / 60.0f;
radians = MathUtil.DegreesToRadians( degreesfloor ); radians = MathUtil.DegreesToRadians( degreesfloor );
@ -211,34 +211,34 @@ namespace math
{ {
get get
{ {
float degrees = MathUtil.RadiansToDegrees(radians); float degrees = MathUtil.RadiansToDegrees( radians );
if( degrees < 0 ) if( degrees < 0 )
{ {
float degreesfloor = (float)Math.Ceiling(degrees); float degreesfloor = (float)Math.Ceiling( degrees );
float minutes = (degrees - degreesfloor) * 60.0f; float minutes = ( degrees - degreesfloor ) * 60.0f;
float minutesfloor = (float)Math.Ceiling(minutes); float minutesfloor = (float)Math.Ceiling( minutes );
return ( minutes - minutesfloor ) * 60.0f; return ( minutes - minutesfloor ) * 60.0f;
} }
else else
{ {
float degreesfloor = (float)Math.Floor(degrees); float degreesfloor = (float)Math.Floor( degrees );
float minutes = (degrees - degreesfloor) * 60.0f; float minutes = ( degrees - degreesfloor ) * 60.0f;
float minutesfloor = (float)Math.Floor(minutes); float minutesfloor = (float)Math.Floor( minutes );
return ( minutes - minutesfloor ) * 60.0f; return ( minutes - minutesfloor ) * 60.0f;
} }
} }
set set
{ {
float degrees = MathUtil.RadiansToDegrees(radians); float degrees = MathUtil.RadiansToDegrees( radians );
float degreesfloor = (float)Math.Floor(degrees); float degreesfloor = (float)Math.Floor( degrees );
float minutes = (degrees - degreesfloor) * 60.0f; float minutes = ( degrees - degreesfloor ) * 60.0f;
float minutesfloor = (float)Math.Floor(minutes); float minutesfloor = (float)Math.Floor( minutes );
minutesfloor += value / 60.0f; minutesfloor += value / 60.0f;
degreesfloor += minutesfloor / 60.0f; degreesfloor += minutesfloor / 60.0f;
@ -648,7 +648,7 @@ namespace math
if( !( other is AngleSingle ) ) if( !( other is AngleSingle ) )
throw new ArgumentException( "Argument must be of type Angle.", "other" ); throw new ArgumentException( "Argument must be of type Angle.", "other" );
float radians = ((AngleSingle)other).radians; float radians = ( (AngleSingle)other ).radians;
if( this.radians > radians ) if( this.radians > radians )
return 1; return 1;

View File

@ -37,13 +37,13 @@ namespace math
/// Represents an axis-aligned bounding box in three dimensional space. /// Represents an axis-aligned bounding box in three dimensional space.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingBox : IEquatable<BoundingBox>, IFormattable public struct BoundingBox : IEquatable<BoundingBox>, IFormattable
{ {
/// <summary> /// <summary>
/// A <see cref="BoundingBox"/> which represents an empty space. /// A <see cref="BoundingBox"/> which represents an empty space.
/// </summary> /// </summary>
public static readonly BoundingBox Empty = new BoundingBox(new Vec3(float.MaxValue), new Vec3(float.MinValue)); public static readonly BoundingBox Empty = new BoundingBox( new Vec3( float.MaxValue ), new Vec3( float.MinValue ) );
/// <summary> /// <summary>
/// The minimum point of the box. /// The minimum point of the box.
@ -60,7 +60,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="minimum">The minimum vertex of the bounding box.</param> /// <param name="minimum">The minimum vertex of the bounding box.</param>
/// <param name="maximum">The maximum vertex of the bounding box.</param> /// <param name="maximum">The maximum vertex of the bounding box.</param>
public BoundingBox(Vec3 minimum, Vec3 maximum) public BoundingBox( Vec3 minimum, Vec3 maximum )
{ {
this.Minimum = minimum; this.Minimum = minimum;
this.Maximum = maximum; this.Maximum = maximum;
@ -71,7 +71,7 @@ namespace math
/// </summary> /// </summary>
public Vec3 Center public Vec3 Center
{ {
get { return (Minimum + Maximum) / 2; } get { return ( Minimum + Maximum ) / 2; }
} }
/// <summary> /// <summary>
@ -79,7 +79,7 @@ namespace math
/// </summary> /// </summary>
public Vec3 Extent public Vec3 Extent
{ {
get { return (Maximum - Minimum) / 2; } get { return ( Maximum - Minimum ) / 2; }
} }
/// <summary> /// <summary>
@ -89,14 +89,14 @@ namespace math
public Vec3[] GetCorners() public Vec3[] GetCorners()
{ {
Vec3[] results = new Vec3[8]; Vec3[] results = new Vec3[8];
results[0] = new Vec3(Minimum.X, Maximum.Y, Maximum.Z); results[0] = new Vec3( Minimum.X, Maximum.Y, Maximum.Z );
results[1] = new Vec3(Maximum.X, Maximum.Y, Maximum.Z); results[1] = new Vec3( Maximum.X, Maximum.Y, Maximum.Z );
results[2] = new Vec3(Maximum.X, Minimum.Y, Maximum.Z); results[2] = new Vec3( Maximum.X, Minimum.Y, Maximum.Z );
results[3] = new Vec3(Minimum.X, Minimum.Y, Maximum.Z); results[3] = new Vec3( Minimum.X, Minimum.Y, Maximum.Z );
results[4] = new Vec3(Minimum.X, Maximum.Y, Minimum.Z); results[4] = new Vec3( Minimum.X, Maximum.Y, Minimum.Z );
results[5] = new Vec3(Maximum.X, Maximum.Y, Minimum.Z); results[5] = new Vec3( Maximum.X, Maximum.Y, Minimum.Z );
results[6] = new Vec3(Maximum.X, Minimum.Y, Minimum.Z); results[6] = new Vec3( Maximum.X, Minimum.Y, Minimum.Z );
results[7] = new Vec3(Minimum.X, Minimum.Y, Minimum.Z); results[7] = new Vec3( Minimum.X, Minimum.Y, Minimum.Z );
return results; return results;
} }
@ -105,10 +105,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="ray">The ray to test.</param> /// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray) public bool Intersects( ref Ray ray )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsBox(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsBox( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -118,9 +118,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out float distance) public bool Intersects( ref Ray ray, out float distance )
{ {
return CollisionHelper.RayIntersectsBox(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsBox( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -130,9 +130,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out Vec3 point) public bool Intersects( ref Ray ray, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsBox(ref ray, ref this, out point); return CollisionHelper.RayIntersectsBox( ref ray, ref this, out point );
} }
/// <summary> /// <summary>
@ -140,9 +140,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The plane to test.</param> /// <param name="plane">The plane to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref Plane plane) public PlaneIntersectionType Intersects( ref Plane plane )
{ {
return CollisionHelper.PlaneIntersectsBox(ref plane, ref this); return CollisionHelper.PlaneIntersectsBox( ref plane, ref this );
} }
/* This implentation is wrong /* This implentation is wrong
@ -164,9 +164,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box) public bool Intersects( ref BoundingBox box )
{ {
return CollisionHelper.BoxIntersectsBox(ref this, ref box); return CollisionHelper.BoxIntersectsBox( ref this, ref box );
} }
/// <summary> /// <summary>
@ -174,9 +174,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere) public bool Intersects( ref BoundingSphere sphere )
{ {
return CollisionHelper.BoxIntersectsSphere(ref this, ref sphere); return CollisionHelper.BoxIntersectsSphere( ref this, ref sphere );
} }
/// <summary> /// <summary>
@ -184,9 +184,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">The point to test.</param> /// <param name="point">The point to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref Vec3 point) public ContainmentType Contains( ref Vec3 point )
{ {
return CollisionHelper.BoxContainsPoint(ref this, ref point); return CollisionHelper.BoxContainsPoint( ref this, ref point );
} }
/* This implentation is wrong /* This implentation is wrong
@ -208,9 +208,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref BoundingBox box) public ContainmentType Contains( ref BoundingBox box )
{ {
return CollisionHelper.BoxContainsBox(ref this, ref box); return CollisionHelper.BoxContainsBox( ref this, ref box );
} }
/// <summary> /// <summary>
@ -218,9 +218,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref BoundingSphere sphere) public ContainmentType Contains( ref BoundingSphere sphere )
{ {
return CollisionHelper.BoxContainsSphere(ref this, ref sphere); return CollisionHelper.BoxContainsSphere( ref this, ref sphere );
} }
/// <summary> /// <summary>
@ -229,21 +229,21 @@ namespace math
/// <param name="points">The points that will be contained by the box.</param> /// <param name="points">The points that will be contained by the box.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding box.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is <c>null</c>.</exception>
public static void FromPoints(Vec3[] points, out BoundingBox result) public static void FromPoints( Vec3[] points, out BoundingBox result )
{ {
if (points == null) if( points == null )
throw new ArgumentNullException("points"); throw new ArgumentNullException( "points" );
Vec3 min = new Vec3(float.MaxValue); Vec3 min = new Vec3( float.MaxValue );
Vec3 max = new Vec3(float.MinValue); Vec3 max = new Vec3( float.MinValue );
for (int i = 0; i < points.Length; ++i) for( int i = 0; i < points.Length; ++i )
{ {
Vec3.Min(ref min, ref points[i], out min); Vec3.Min( ref min, ref points[i], out min );
Vec3.Max(ref max, ref points[i], out max); Vec3.Max( ref max, ref points[i], out max );
} }
result = new BoundingBox(min, max); result = new BoundingBox( min, max );
} }
/// <summary> /// <summary>
@ -252,21 +252,21 @@ namespace math
/// <param name="points">The points that will be contained by the box.</param> /// <param name="points">The points that will be contained by the box.</param>
/// <returns>The newly constructed bounding box.</returns> /// <returns>The newly constructed bounding box.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is <c>null</c>.</exception>
public static BoundingBox FromPoints(Vec3[] points) public static BoundingBox FromPoints( Vec3[] points )
{ {
if (points == null) if( points == null )
throw new ArgumentNullException("points"); throw new ArgumentNullException( "points" );
Vec3 min = new Vec3(float.MaxValue); Vec3 min = new Vec3( float.MaxValue );
Vec3 max = new Vec3(float.MinValue); Vec3 max = new Vec3( float.MinValue );
for (int i = 0; i < points.Length; ++i) for( int i = 0; i < points.Length; ++i )
{ {
Vec3.Min(ref min, ref points[i], out min); Vec3.Min( ref min, ref points[i], out min );
Vec3.Max(ref max, ref points[i], out max); Vec3.Max( ref max, ref points[i], out max );
} }
return new BoundingBox(min, max); return new BoundingBox( min, max );
} }
/// <summary> /// <summary>
@ -274,10 +274,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere that will designate the extents of the box.</param> /// <param name="sphere">The sphere that will designate the extents of the box.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding box.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param>
public static void FromSphere(ref BoundingSphere sphere, out BoundingBox result) public static void FromSphere( ref BoundingSphere sphere, out BoundingBox result )
{ {
result.Minimum = new Vec3(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius); result.Minimum = new Vec3( sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius );
result.Maximum = new Vec3(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius); result.Maximum = new Vec3( sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius );
} }
/// <summary> /// <summary>
@ -285,11 +285,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere that will designate the extents of the box.</param> /// <param name="sphere">The sphere that will designate the extents of the box.</param>
/// <returns>The newly constructed bounding box.</returns> /// <returns>The newly constructed bounding box.</returns>
public static BoundingBox FromSphere(BoundingSphere sphere) public static BoundingBox FromSphere( BoundingSphere sphere )
{ {
BoundingBox box; BoundingBox box;
box.Minimum = new Vec3(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius); box.Minimum = new Vec3( sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius );
box.Maximum = new Vec3(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius); box.Maximum = new Vec3( sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius );
return box; return box;
} }
@ -299,10 +299,10 @@ namespace math
/// <param name="value">The original bounding box.</param> /// <param name="value">The original bounding box.</param>
/// <param name="transform">The transform to apply to the bounding box.</param> /// <param name="transform">The transform to apply to the bounding box.</param>
/// <param name="result">The transformed bounding box.</param> /// <param name="result">The transformed bounding box.</param>
public static void Transform(ref BoundingBox value, ref Matrix transform, out BoundingBox result) public static void Transform( ref BoundingBox value, ref Matrix transform, out BoundingBox result )
{ {
var boundingBox = new BoundingBoxExt(value); var boundingBox = new BoundingBoxExt( value );
boundingBox.Transform(transform); boundingBox.Transform( transform );
result = (BoundingBox)boundingBox; result = (BoundingBox)boundingBox;
} }
@ -312,10 +312,10 @@ namespace math
/// <param name="value1">The box to merge.</param> /// <param name="value1">The box to merge.</param>
/// <param name="value2">The point to merge.</param> /// <param name="value2">The point to merge.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding box.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param>
public static void Merge(ref BoundingBox value1, ref Vec3 value2, out BoundingBox result) public static void Merge( ref BoundingBox value1, ref Vec3 value2, out BoundingBox result )
{ {
Vec3.Min(ref value1.Minimum, ref value2, out result.Minimum); Vec3.Min( ref value1.Minimum, ref value2, out result.Minimum );
Vec3.Max(ref value1.Maximum, ref value2, out result.Maximum); Vec3.Max( ref value1.Maximum, ref value2, out result.Maximum );
} }
/// <summary> /// <summary>
@ -324,10 +324,10 @@ namespace math
/// <param name="value1">The first box to merge.</param> /// <param name="value1">The first box to merge.</param>
/// <param name="value2">The second box to merge.</param> /// <param name="value2">The second box to merge.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding box.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param>
public static void Merge(ref BoundingBox value1, ref BoundingBox value2, out BoundingBox result) public static void Merge( ref BoundingBox value1, ref BoundingBox value2, out BoundingBox result )
{ {
Vec3.Min(ref value1.Minimum, ref value2.Minimum, out result.Minimum); Vec3.Min( ref value1.Minimum, ref value2.Minimum, out result.Minimum );
Vec3.Max(ref value1.Maximum, ref value2.Maximum, out result.Maximum); Vec3.Max( ref value1.Maximum, ref value2.Maximum, out result.Maximum );
} }
/// <summary> /// <summary>
@ -336,11 +336,11 @@ namespace math
/// <param name="value1">The first box to merge.</param> /// <param name="value1">The first box to merge.</param>
/// <param name="value2">The second box to merge.</param> /// <param name="value2">The second box to merge.</param>
/// <returns>The newly constructed bounding box.</returns> /// <returns>The newly constructed bounding box.</returns>
public static BoundingBox Merge(BoundingBox value1, BoundingBox value2) public static BoundingBox Merge( BoundingBox value1, BoundingBox value2 )
{ {
BoundingBox box; BoundingBox box;
Vec3.Min(ref value1.Minimum, ref value2.Minimum, out box.Minimum); Vec3.Min( ref value1.Minimum, ref value2.Minimum, out box.Minimum );
Vec3.Max(ref value1.Maximum, ref value2.Maximum, out box.Maximum); Vec3.Max( ref value1.Maximum, ref value2.Maximum, out box.Maximum );
return box; return box;
} }
@ -350,9 +350,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(BoundingBox left, BoundingBox right) public static bool operator ==( BoundingBox left, BoundingBox right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -361,9 +361,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(BoundingBox left, BoundingBox right) public static bool operator !=( BoundingBox left, BoundingBox right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -374,7 +374,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString()); return string.Format( CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString() );
} }
/// <summary> /// <summary>
@ -384,13 +384,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(format, CultureInfo.CurrentCulture), return string.Format( CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString( format, CultureInfo.CurrentCulture ),
Maximum.ToString(format, CultureInfo.CurrentCulture)); Maximum.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -400,9 +400,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString()); return string.Format( formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString() );
} }
/// <summary> /// <summary>
@ -413,13 +413,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString(format, formatProvider), return string.Format( formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString( format, formatProvider ),
Maximum.ToString(format, formatProvider)); Maximum.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -440,7 +440,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(BoundingBox value) public bool Equals( BoundingBox value )
{ {
return Minimum == value.Minimum && Maximum == value.Maximum; return Minimum == value.Minimum && Maximum == value.Maximum;
} }
@ -452,15 +452,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((BoundingBox)value); return Equals( (BoundingBox)value );
} }
} }
} }

View File

@ -11,13 +11,13 @@ namespace math
/// Represents an axis-aligned bounding box in three dimensional space that store only the Center and Extent. /// Represents an axis-aligned bounding box in three dimensional space that store only the Center and Extent.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingBoxExt : IEquatable<BoundingBoxExt> public struct BoundingBoxExt : IEquatable<BoundingBoxExt>
{ {
/// <summary> /// <summary>
/// A <see cref="BoundingBoxExt"/> which represents an empty space. /// A <see cref="BoundingBoxExt"/> which represents an empty space.
/// </summary> /// </summary>
public static readonly BoundingBoxExt Empty = new BoundingBoxExt(BoundingBox.Empty); public static readonly BoundingBoxExt Empty = new BoundingBoxExt( BoundingBox.Empty );
/// <summary> /// <summary>
/// The center of this bounding box. /// The center of this bounding box.
@ -33,7 +33,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.BoundingBoxExt" /> struct. /// Initializes a new instance of the <see cref="math.BoundingBoxExt" /> struct.
/// </summary> /// </summary>
/// <param name="box">The box.</param> /// <param name="box">The box.</param>
public BoundingBoxExt(BoundingBox box) public BoundingBoxExt( BoundingBox box )
{ {
this.Center = box.Center; this.Center = box.Center;
this.Extent = box.Extent; this.Extent = box.Extent;
@ -44,10 +44,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="minimum">The minimum vertex of the bounding box.</param> /// <param name="minimum">The minimum vertex of the bounding box.</param>
/// <param name="maximum">The maximum vertex of the bounding box.</param> /// <param name="maximum">The maximum vertex of the bounding box.</param>
public BoundingBoxExt(Vec3 minimum, Vec3 maximum) public BoundingBoxExt( Vec3 minimum, Vec3 maximum )
{ {
this.Center = (minimum + maximum) / 2; this.Center = ( minimum + maximum ) / 2;
this.Extent = (maximum - minimum) / 2; this.Extent = ( maximum - minimum ) / 2;
} }
/// <summary> /// <summary>
@ -78,29 +78,29 @@ namespace math
/// Transform this Bounding box /// Transform this Bounding box
/// </summary> /// </summary>
/// <param name="world">The transform to apply to the bounding box.</param> /// <param name="world">The transform to apply to the bounding box.</param>
public void Transform(Matrix world) public void Transform( Matrix world )
{ {
// http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ // http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
// Compute transformed AABB (by world) // Compute transformed AABB (by world)
var center = Center; var center = Center;
var extent = Extent; var extent = Extent;
Vec3.TransformCoordinate(ref center, ref world, out Center); Vec3.TransformCoordinate( ref center, ref world, out Center );
// Update world matrix into absolute form // Update world matrix into absolute form
unsafe unsafe
{ {
// Perform an abs on the matrix // Perform an abs on the matrix
var matrixData = (float*)&world; var matrixData = (float*)&world;
for (int j = 0; j < 16; ++j) for( int j = 0; j < 16; ++j )
{ {
//*matrixData &= 0x7FFFFFFF; //*matrixData &= 0x7FFFFFFF;
*matrixData = Math.Abs(*matrixData); *matrixData = Math.Abs( *matrixData );
++matrixData; ++matrixData;
} }
} }
Vec3.TransformNormal(ref extent, ref world, out Extent); Vec3.TransformNormal( ref extent, ref world, out Extent );
} }
/// <summary> /// <summary>
@ -109,27 +109,28 @@ namespace math
/// <param name="value1">The first box to merge.</param> /// <param name="value1">The first box to merge.</param>
/// <param name="value2">The second box to merge.</param> /// <param name="value2">The second box to merge.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding box.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void Merge(ref BoundingBoxExt value1, ref BoundingBoxExt value2, out BoundingBoxExt result) public static void Merge( ref BoundingBoxExt value1, ref BoundingBoxExt value2, out BoundingBoxExt result )
{ {
var maximum = Vec3.Max(value1.Maximum, value2.Maximum); var maximum = Vec3.Max( value1.Maximum, value2.Maximum );
var minimum = Vec3.Min(value1.Minimum, value2.Minimum); var minimum = Vec3.Min( value1.Minimum, value2.Minimum );
result.Center = (minimum + maximum) / 2; result.Center = ( minimum + maximum ) / 2;
result.Extent = (maximum - minimum) / 2; result.Extent = ( maximum - minimum ) / 2;
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool Equals(BoundingBoxExt other) public bool Equals( BoundingBoxExt other )
{ {
return Center.Equals(other.Center) && Extent.Equals(other.Extent); return Center.Equals( other.Center ) && Extent.Equals( other.Extent );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
return obj is BoundingBoxExt && Equals((BoundingBoxExt)obj); return false;
return obj is BoundingBoxExt && Equals( (BoundingBoxExt)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -137,7 +138,7 @@ namespace math
{ {
unchecked unchecked
{ {
return (Center.GetHashCode() * 397) ^ Extent.GetHashCode(); return ( Center.GetHashCode() * 397 ) ^ Extent.GetHashCode();
} }
} }
@ -147,9 +148,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator ==(BoundingBoxExt left, BoundingBoxExt right) public static bool operator ==( BoundingBoxExt left, BoundingBoxExt right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -158,9 +159,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator !=(BoundingBoxExt left, BoundingBoxExt right) public static bool operator !=( BoundingBoxExt left, BoundingBoxExt right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -168,9 +169,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="bbExt">The bb ext.</param> /// <param name="bbExt">The bb ext.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator BoundingBox(BoundingBoxExt bbExt) public static explicit operator BoundingBox( BoundingBoxExt bbExt )
{ {
return new BoundingBox(bbExt.Minimum, bbExt.Maximum); return new BoundingBox( bbExt.Minimum, bbExt.Maximum );
} }
/// <summary> /// <summary>
@ -178,9 +179,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="boundingBox">The bounding box.</param> /// <param name="boundingBox">The bounding box.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator BoundingBoxExt(BoundingBox boundingBox) public static explicit operator BoundingBoxExt( BoundingBox boundingBox )
{ {
return new BoundingBoxExt(boundingBox); return new BoundingBoxExt( boundingBox );
} }
} }
} }

View File

@ -44,49 +44,49 @@ namespace math
/// Initializes a new instance of the <see cref="BoundingFrustum"/> struct from a matrix view-projection. /// Initializes a new instance of the <see cref="BoundingFrustum"/> struct from a matrix view-projection.
/// </summary> /// </summary>
/// <param name="matrix">The matrix view projection.</param> /// <param name="matrix">The matrix view projection.</param>
public BoundingFrustum(ref Matrix matrix) public BoundingFrustum( ref Matrix matrix )
{ {
// Left // Left
LeftPlane = Plane.Normalize(new Plane( LeftPlane = Plane.Normalize( new Plane(
matrix.M14 + matrix.M11, matrix.M14 + matrix.M11,
matrix.M24 + matrix.M21, matrix.M24 + matrix.M21,
matrix.M34 + matrix.M31, matrix.M34 + matrix.M31,
matrix.M44 + matrix.M41)); matrix.M44 + matrix.M41 ) );
// Right // Right
RightPlane = Plane.Normalize(new Plane( RightPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M11, matrix.M14 - matrix.M11,
matrix.M24 - matrix.M21, matrix.M24 - matrix.M21,
matrix.M34 - matrix.M31, matrix.M34 - matrix.M31,
matrix.M44 - matrix.M41)); matrix.M44 - matrix.M41 ) );
// Top // Top
TopPlane = Plane.Normalize(new Plane( TopPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M12, matrix.M14 - matrix.M12,
matrix.M24 - matrix.M22, matrix.M24 - matrix.M22,
matrix.M34 - matrix.M32, matrix.M34 - matrix.M32,
matrix.M44 - matrix.M42)); matrix.M44 - matrix.M42 ) );
// Bottom // Bottom
BottomPlane = Plane.Normalize(new Plane( BottomPlane = Plane.Normalize( new Plane(
matrix.M14 + matrix.M12, matrix.M14 + matrix.M12,
matrix.M24 + matrix.M22, matrix.M24 + matrix.M22,
matrix.M34 + matrix.M32, matrix.M34 + matrix.M32,
matrix.M44 + matrix.M42)); matrix.M44 + matrix.M42 ) );
// Near // Near
NearPlane = Plane.Normalize(new Plane( NearPlane = Plane.Normalize( new Plane(
matrix.M13, matrix.M13,
matrix.M23, matrix.M23,
matrix.M33, matrix.M33,
matrix.M43)); matrix.M43 ) );
// Far // Far
FarPlane = Plane.Normalize(new Plane( FarPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M13, matrix.M14 - matrix.M13,
matrix.M24 - matrix.M23, matrix.M24 - matrix.M23,
matrix.M34 - matrix.M33, matrix.M34 - matrix.M33,
matrix.M44 - matrix.M43)); matrix.M44 - matrix.M43 ) );
} }
/// <summary> /// <summary>
@ -94,10 +94,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="boundingBoxExt">The bounding box.</param> /// <param name="boundingBoxExt">The bounding box.</param>
/// <returns><c>true</c> if this frustum contains the specified bounding box.</returns> /// <returns><c>true</c> if this frustum contains the specified bounding box.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool Contains(ref BoundingBoxExt boundingBoxExt) public bool Contains( ref BoundingBoxExt boundingBoxExt )
{ {
return CollisionHelper.FrustumContainsBox(ref this, ref boundingBoxExt); return CollisionHelper.FrustumContainsBox( ref this, ref boundingBoxExt );
} }
} }
} }

View File

@ -37,7 +37,7 @@ namespace math
/// Represents a bounding sphere in three dimensional space. /// Represents a bounding sphere in three dimensional space.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingSphere : IEquatable<BoundingSphere>, IFormattable public struct BoundingSphere : IEquatable<BoundingSphere>, IFormattable
{ {
/// <summary> /// <summary>
@ -60,7 +60,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="center">The center of the sphere in three dimensional space.</param> /// <param name="center">The center of the sphere in three dimensional space.</param>
/// <param name="radius">The radius of the sphere.</param> /// <param name="radius">The radius of the sphere.</param>
public BoundingSphere(Vec3 center, float radius) public BoundingSphere( Vec3 center, float radius )
{ {
this.Center = center; this.Center = center;
this.Radius = radius; this.Radius = radius;
@ -71,10 +71,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="ray">The ray to test.</param> /// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray) public bool Intersects( ref Ray ray )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsSphere(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsSphere( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -84,9 +84,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out float distance) public bool Intersects( ref Ray ray, out float distance )
{ {
return CollisionHelper.RayIntersectsSphere(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsSphere( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -96,9 +96,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out Vec3 point) public bool Intersects( ref Ray ray, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsSphere(ref ray, ref this, out point); return CollisionHelper.RayIntersectsSphere( ref ray, ref this, out point );
} }
/// <summary> /// <summary>
@ -106,9 +106,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The plane to test.</param> /// <param name="plane">The plane to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref Plane plane) public PlaneIntersectionType Intersects( ref Plane plane )
{ {
return CollisionHelper.PlaneIntersectsSphere(ref plane, ref this); return CollisionHelper.PlaneIntersectsSphere( ref plane, ref this );
} }
/// <summary> /// <summary>
@ -118,9 +118,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle to test.</param> /// <param name="vertex2">The second vertex of the triagnle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param> /// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3) public bool Intersects( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3 )
{ {
return CollisionHelper.SphereIntersectsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3); return CollisionHelper.SphereIntersectsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3 );
} }
/// <summary> /// <summary>
@ -128,9 +128,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box) public bool Intersects( ref BoundingBox box )
{ {
return CollisionHelper.BoxIntersectsSphere(ref box, ref this); return CollisionHelper.BoxIntersectsSphere( ref box, ref this );
} }
/// <summary> /// <summary>
@ -138,9 +138,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere) public bool Intersects( ref BoundingSphere sphere )
{ {
return CollisionHelper.SphereIntersectsSphere(ref this, ref sphere); return CollisionHelper.SphereIntersectsSphere( ref this, ref sphere );
} }
/// <summary> /// <summary>
@ -148,9 +148,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">The point to test.</param> /// <param name="point">The point to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref Vec3 point) public ContainmentType Contains( ref Vec3 point )
{ {
return CollisionHelper.SphereContainsPoint(ref this, ref point); return CollisionHelper.SphereContainsPoint( ref this, ref point );
} }
/// <summary> /// <summary>
@ -160,9 +160,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle to test.</param> /// <param name="vertex2">The second vertex of the triagnle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param> /// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3) public ContainmentType Contains( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3 )
{ {
return CollisionHelper.SphereContainsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3); return CollisionHelper.SphereContainsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3 );
} }
/// <summary> /// <summary>
@ -170,9 +170,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref BoundingBox box) public ContainmentType Contains( ref BoundingBox box )
{ {
return CollisionHelper.SphereContainsBox(ref this, ref box); return CollisionHelper.SphereContainsBox( ref this, ref box );
} }
/// <summary> /// <summary>
@ -180,9 +180,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>The type of containment the two objects have.</returns> /// <returns>The type of containment the two objects have.</returns>
public ContainmentType Contains(ref BoundingSphere sphere) public ContainmentType Contains( ref BoundingSphere sphere )
{ {
return CollisionHelper.SphereContainsSphere(ref this, ref sphere); return CollisionHelper.SphereContainsSphere( ref this, ref sphere );
} }
/// <summary> /// <summary>
@ -190,12 +190,13 @@ namespace math
/// </summary> /// </summary>
/// <param name="points">The points that will be contained by the sphere.</param> /// <param name="points">The points that will be contained by the sphere.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param> /// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param>
public static unsafe void FromPoints(Vec3[] points, out BoundingSphere result) public static unsafe void FromPoints( Vec3[] points, out BoundingSphere result )
{ {
if (points == null) throw new ArgumentNullException("points"); if( points == null )
fixed (void* pointsPtr = points) throw new ArgumentNullException( "points" );
fixed( void* pointsPtr = points )
{ {
FromPoints((IntPtr)pointsPtr, 0, points.Length, lib.Util.SizeOf<Vec3>(), out result); FromPoints( (IntPtr)pointsPtr, 0, points.Length, lib.Util.SizeOf<Vec3>(), out result );
} }
} }
@ -207,11 +208,11 @@ namespace math
/// <param name="vertexCount">The verterx vertexCount.</param> /// <param name="vertexCount">The verterx vertexCount.</param>
/// <param name="vertexStride">The vertex stride (size of vertex).</param> /// <param name="vertexStride">The vertex stride (size of vertex).</param>
/// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param> /// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param>
public static unsafe void FromPoints(IntPtr vertexBufferPtr, int vertexPositionOffsetInBytes, int vertexCount, int vertexStride, out BoundingSphere result) public static unsafe void FromPoints( IntPtr vertexBufferPtr, int vertexPositionOffsetInBytes, int vertexCount, int vertexStride, out BoundingSphere result )
{ {
if (vertexBufferPtr == IntPtr.Zero) if( vertexBufferPtr == IntPtr.Zero )
{ {
throw new ArgumentNullException("vertexBufferPtr"); throw new ArgumentNullException( "vertexBufferPtr" );
} }
var startPoint = (byte*)vertexBufferPtr + vertexPositionOffsetInBytes; var startPoint = (byte*)vertexBufferPtr + vertexPositionOffsetInBytes;
@ -219,9 +220,9 @@ namespace math
//Find the center of all points. //Find the center of all points.
Vec3 center = Vec3.Zero; Vec3 center = Vec3.Zero;
var nextPoint = startPoint; var nextPoint = startPoint;
for (int i = 0; i < vertexCount; ++i) for( int i = 0; i < vertexCount; ++i )
{ {
Vec3.Add(ref *(Vec3*)nextPoint, ref center, out center); Vec3.Add( ref *(Vec3*)nextPoint, ref center, out center );
nextPoint += vertexStride; nextPoint += vertexStride;
} }
@ -231,20 +232,20 @@ namespace math
//Find the radius of the sphere //Find the radius of the sphere
float radius = 0f; float radius = 0f;
nextPoint = startPoint; nextPoint = startPoint;
for (int i = 0; i < vertexCount; ++i) for( int i = 0; i < vertexCount; ++i )
{ {
//We are doing a relative distance comparasin to find the maximum distance //We are doing a relative distance comparasin to find the maximum distance
//from the center of our sphere. //from the center of our sphere.
float distance; float distance;
Vec3.DistanceSquared(ref center, ref *(Vec3*)nextPoint, out distance); Vec3.DistanceSquared( ref center, ref *(Vec3*)nextPoint, out distance );
if (distance > radius) if( distance > radius )
radius = distance; radius = distance;
nextPoint += vertexStride; nextPoint += vertexStride;
} }
//Find the real distance from the DistanceSquared. //Find the real distance from the DistanceSquared.
radius = (float)Math.Sqrt(radius); radius = (float)Math.Sqrt( radius );
//Construct the sphere. //Construct the sphere.
result.Center = center; result.Center = center;
@ -256,10 +257,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="points">The points that will be contained by the sphere.</param> /// <param name="points">The points that will be contained by the sphere.</param>
/// <returns>The newly constructed bounding sphere.</returns> /// <returns>The newly constructed bounding sphere.</returns>
public static BoundingSphere FromPoints(Vec3[] points) public static BoundingSphere FromPoints( Vec3[] points )
{ {
BoundingSphere result; BoundingSphere result;
FromPoints(points, out result); FromPoints( points, out result );
return result; return result;
} }
@ -268,15 +269,15 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box that will designate the extents of the sphere.</param> /// <param name="box">The box that will designate the extents of the sphere.</param>
/// <param name="result">When the method completes, the newly constructed bounding sphere.</param> /// <param name="result">When the method completes, the newly constructed bounding sphere.</param>
public static void FromBox(ref BoundingBox box, out BoundingSphere result) public static void FromBox( ref BoundingBox box, out BoundingSphere result )
{ {
Vec3.Lerp(ref box.Minimum, ref box.Maximum, 0.5f, out result.Center); Vec3.Lerp( ref box.Minimum, ref box.Maximum, 0.5f, out result.Center );
float x = box.Minimum.X - box.Maximum.X; float x = box.Minimum.X - box.Maximum.X;
float y = box.Minimum.Y - box.Maximum.Y; float y = box.Minimum.Y - box.Maximum.Y;
float z = box.Minimum.Z - box.Maximum.Z; float z = box.Minimum.Z - box.Maximum.Z;
float distance = (float)(Math.Sqrt((x * x) + (y * y) + (z * z))); float distance = (float)( Math.Sqrt( ( x * x ) + ( y * y ) + ( z * z ) ) );
result.Radius = distance * 0.5f; result.Radius = distance * 0.5f;
} }
@ -285,10 +286,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box that will designate the extents of the sphere.</param> /// <param name="box">The box that will designate the extents of the sphere.</param>
/// <returns>The newly constructed bounding sphere.</returns> /// <returns>The newly constructed bounding sphere.</returns>
public static BoundingSphere FromBox(BoundingBox box) public static BoundingSphere FromBox( BoundingBox box )
{ {
BoundingSphere result; BoundingSphere result;
FromBox(ref box, out result); FromBox( ref box, out result );
return result; return result;
} }
@ -298,16 +299,16 @@ namespace math
/// <param name="value">The original bounding sphere.</param> /// <param name="value">The original bounding sphere.</param>
/// <param name="transform">The transform to apply to the bounding sphere.</param> /// <param name="transform">The transform to apply to the bounding sphere.</param>
/// <param name="result">The transformed bounding sphere.</param> /// <param name="result">The transformed bounding sphere.</param>
public static void Transform(ref BoundingSphere value, ref Matrix transform, out BoundingSphere result) public static void Transform( ref BoundingSphere value, ref Matrix transform, out BoundingSphere result )
{ {
Vec3.TransformCoordinate(ref value.Center, ref transform, out result.Center); Vec3.TransformCoordinate( ref value.Center, ref transform, out result.Center );
var majorAxisLengthSquared = Math.Max( var majorAxisLengthSquared = Math.Max(
(transform.M11 * transform.M11) + (transform.M12 * transform.M12) + (transform.M13 * transform.M13), Math.Max( ( transform.M11 * transform.M11 ) + ( transform.M12 * transform.M12 ) + ( transform.M13 * transform.M13 ), Math.Max(
(transform.M21 * transform.M21) + (transform.M22 * transform.M22) + (transform.M23 * transform.M23), ( transform.M21 * transform.M21 ) + ( transform.M22 * transform.M22 ) + ( transform.M23 * transform.M23 ),
(transform.M31 * transform.M31) + (transform.M32 * transform.M32) + (transform.M33 * transform.M33))); ( transform.M31 * transform.M31 ) + ( transform.M32 * transform.M32 ) + ( transform.M33 * transform.M33 ) ) );
result.Radius = value.Radius * (float)Math.Sqrt(majorAxisLengthSquared); result.Radius = value.Radius * (float)Math.Sqrt( majorAxisLengthSquared );
} }
/// <summary> /// <summary>
@ -316,16 +317,16 @@ namespace math
/// <param name="value1">The first sphere to merge.</param> /// <param name="value1">The first sphere to merge.</param>
/// <param name="value2">The second sphere to merge.</param> /// <param name="value2">The second sphere to merge.</param>
/// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param> /// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param>
public static void Merge(ref BoundingSphere value1, ref BoundingSphere value2, out BoundingSphere result) public static void Merge( ref BoundingSphere value1, ref BoundingSphere value2, out BoundingSphere result )
{ {
// Pre-exit if one of the bounding sphere by assuming that a merge with an empty sphere is equivalent at taking the non-empty sphere // Pre-exit if one of the bounding sphere by assuming that a merge with an empty sphere is equivalent at taking the non-empty sphere
if (value1 == Empty) if( value1 == Empty )
{ {
result = value2; result = value2;
return; return;
} }
if (value2 == Empty) if( value2 == Empty )
{ {
result = value1; result = value1;
return; return;
@ -337,26 +338,26 @@ namespace math
float radius = value1.Radius; float radius = value1.Radius;
float radius2 = value2.Radius; float radius2 = value2.Radius;
if (radius + radius2 >= length) if( radius + radius2 >= length )
{ {
if (radius - radius2 >= length) if( radius - radius2 >= length )
{ {
result = value1; result = value1;
return; return;
} }
if (radius2 - radius >= length) if( radius2 - radius >= length )
{ {
result = value2; result = value2;
return; return;
} }
} }
Vec3 vector = difference * (1.0f / length); Vec3 vector = difference * ( 1.0f / length );
float min = Math.Min(-radius, length - radius2); float min = Math.Min( -radius, length - radius2 );
float max = (Math.Max(radius, length + radius2) - min) * 0.5f; float max = ( Math.Max( radius, length + radius2 ) - min ) * 0.5f;
result.Center = value1.Center + vector * (max + min); result.Center = value1.Center + vector * ( max + min );
result.Radius = max; result.Radius = max;
} }
@ -366,10 +367,10 @@ namespace math
/// <param name="value1">The first sphere to merge.</param> /// <param name="value1">The first sphere to merge.</param>
/// <param name="value2">The second sphere to merge.</param> /// <param name="value2">The second sphere to merge.</param>
/// <returns>The newly constructed bounding sphere.</returns> /// <returns>The newly constructed bounding sphere.</returns>
public static BoundingSphere Merge(BoundingSphere value1, BoundingSphere value2) public static BoundingSphere Merge( BoundingSphere value1, BoundingSphere value2 )
{ {
BoundingSphere result; BoundingSphere result;
Merge(ref value1, ref value2, out result); Merge( ref value1, ref value2, out result );
return result; return result;
} }
@ -379,9 +380,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(BoundingSphere left, BoundingSphere right) public static bool operator ==( BoundingSphere left, BoundingSphere right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -390,9 +391,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(BoundingSphere left, BoundingSphere right) public static bool operator !=( BoundingSphere left, BoundingSphere right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -403,7 +404,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString(), Radius.ToString()); return string.Format( CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString(), Radius.ToString() );
} }
/// <summary> /// <summary>
@ -413,13 +414,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString(format, CultureInfo.CurrentCulture), return string.Format( CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString( format, CultureInfo.CurrentCulture ),
Radius.ToString(format, CultureInfo.CurrentCulture)); Radius.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -429,9 +430,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "Center:{0} Radius:{1}", Center.ToString(), Radius.ToString()); return string.Format( formatProvider, "Center:{0} Radius:{1}", Center.ToString(), Radius.ToString() );
} }
/// <summary> /// <summary>
@ -442,13 +443,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, "Center:{0} Radius:{1}", Center.ToString(format, formatProvider), return string.Format( formatProvider, "Center:{0} Radius:{1}", Center.ToString( format, formatProvider ),
Radius.ToString(format, formatProvider)); Radius.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -469,7 +470,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(BoundingSphere value) public bool Equals( BoundingSphere value )
{ {
return Center == value.Center && Radius == value.Radius; return Center == value.Center && Radius == value.Radius;
} }
@ -481,15 +482,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((BoundingSphere)value); return Equals( (BoundingSphere)value );
} }
#if SlimDX1xInterop #if SlimDX1xInterop

View File

@ -23,7 +23,7 @@ sealed public record Vector3Cm( Cm x, Cm y, Cm z )
/// Represents a fixed-point value in centimeters, stored as an integer. /// Represents a fixed-point value in centimeters, stored as an integer.
/// Implements INumber<Cm> for full generic math support. /// Implements INumber<Cm> for full generic math support.
/// </summary> /// </summary>
sealed public record Cm(int value) : INumber<Cm> sealed public record Cm( int value ) : INumber<Cm>
{ {
// --- Constants and Identities --- // --- Constants and Identities ---
@ -31,88 +31,88 @@ sealed public record Cm(int value) : INumber<Cm>
/// Represents the multiplicative identity (1.0). /// Represents the multiplicative identity (1.0).
/// The underlying value is 100 because 1.0 meter = 100 centimeters. /// The underlying value is 100 because 1.0 meter = 100 centimeters.
/// </summary> /// </summary>
public static Cm One => new Cm(100); public static Cm One => new Cm( 100 );
public static Cm Zero => new Cm(0); public static Cm Zero => new Cm( 0 );
public static int Radix => 10; public static int Radix => 10;
public static Cm AdditiveIdentity => Zero; public static Cm AdditiveIdentity => Zero;
public static Cm MultiplicativeIdentity => One; public static Cm MultiplicativeIdentity => One;
public float Float => ((float)value) * 0.01f; public float Float => ( (float)value ) * 0.01f;
public double Double => ((double)value) * 0.01; public double Double => ( (double)value ) * 0.01;
// --- Static Conversion Methods --- // --- Static Conversion Methods ---
public static Cm From(float v) => new Cm((int)(v * 100.0f + 0.5f)); public static Cm From( float v ) => new Cm( (int)( v * 100.0f + 0.5f ) );
public static Cm From(double v) => new Cm((int)(v * 100.0 + 0.5)); public static Cm From( double v ) => new Cm( (int)( v * 100.0 + 0.5 ) );
// --- Standard Functions --- // --- Standard Functions ---
public static Cm Abs(Cm c) => new Cm(Math.Abs(c.value)); public static Cm Abs( Cm c ) => new Cm( Math.Abs( c.value ) );
public static Cm MaxMagnitude(Cm x, Cm y) => Abs(x) > Abs(y) ? x : y; public static Cm MaxMagnitude( Cm x, Cm y ) => Abs( x ) > Abs( y ) ? x : y;
public static Cm MaxMagnitudeNumber(Cm x, Cm y) => MaxMagnitude(x, y); // Same for this type public static Cm MaxMagnitudeNumber( Cm x, Cm y ) => MaxMagnitude( x, y ); // Same for this type
public static Cm MinMagnitude(Cm x, Cm y) => Abs(x) < Abs(y) ? x : y; public static Cm MinMagnitude( Cm x, Cm y ) => Abs( x ) < Abs( y ) ? x : y;
public static Cm MinMagnitudeNumber(Cm x, Cm y) => MinMagnitude(x, y); // Same for this type public static Cm MinMagnitudeNumber( Cm x, Cm y ) => MinMagnitude( x, y ); // Same for this type
// --- Type Property Checks --- // --- Type Property Checks ---
public static bool IsCanonical(Cm c) => true; public static bool IsCanonical( Cm c ) => true;
public static bool IsComplexNumber(Cm c) => false; public static bool IsComplexNumber( Cm c ) => false;
public static bool IsEvenInteger(Cm c) => (c.value % 100 == 0) && (c.value / 100 % 2 == 0); public static bool IsEvenInteger( Cm c ) => ( c.value % 100 == 0 ) && ( c.value / 100 % 2 == 0 );
public static bool IsFinite(Cm c) => true; public static bool IsFinite( Cm c ) => true;
public static bool IsImaginaryNumber(Cm c) => false; public static bool IsImaginaryNumber( Cm c ) => false;
public static bool IsInfinity(Cm c) => false; public static bool IsInfinity( Cm c ) => false;
public static bool IsInteger(Cm c) => c.value % 100 == 0; public static bool IsInteger( Cm c ) => c.value % 100 == 0;
public static bool IsNaN(Cm c) => false; public static bool IsNaN( Cm c ) => false;
public static bool IsNegative(Cm c) => c.value < 0; public static bool IsNegative( Cm c ) => c.value < 0;
public static bool IsNegativeInfinity(Cm c) => false; public static bool IsNegativeInfinity( Cm c ) => false;
public static bool IsNormal(Cm c) => c.value != 0; public static bool IsNormal( Cm c ) => c.value != 0;
public static bool IsOddInteger(Cm c) => (c.value % 100 == 0) && (c.value / 100 % 2 != 0); public static bool IsOddInteger( Cm c ) => ( c.value % 100 == 0 ) && ( c.value / 100 % 2 != 0 );
public static bool IsPositive(Cm c) => c.value > 0; public static bool IsPositive( Cm c ) => c.value > 0;
public static bool IsPositiveInfinity(Cm c) => false; public static bool IsPositiveInfinity( Cm c ) => false;
public static bool IsRealNumber(Cm c) => true; // It is a real number public static bool IsRealNumber( Cm c ) => true; // It is a real number
public static bool IsSubnormal(Cm c) => false; public static bool IsSubnormal( Cm c ) => false;
public static bool IsZero(Cm c) => c.value == 0; public static bool IsZero( Cm c ) => c.value == 0;
// --- Parsing --- // --- Parsing ---
public static Cm Parse(string s, IFormatProvider? provider) => Parse(s, NumberStyles.Number, provider); public static Cm Parse( string s, IFormatProvider? provider ) => Parse( s, NumberStyles.Number, provider );
public static Cm Parse(ReadOnlySpan<char> s, IFormatProvider? provider) => Parse(s, NumberStyles.Number, provider); public static Cm Parse( ReadOnlySpan<char> s, IFormatProvider? provider ) => Parse( s, NumberStyles.Number, provider );
public static Cm Parse(string s, NumberStyles style, IFormatProvider? provider) public static Cm Parse( string s, NumberStyles style, IFormatProvider? provider )
{ {
if (TryParse(s, style, provider, out var result)) if( TryParse( s, style, provider, out var result ) )
{ {
return result; return result;
} }
throw new FormatException($"Input string '{s}' was not in a correct format."); throw new FormatException( $"Input string '{s}' was not in a correct format." );
} }
public static Cm Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider) public static Cm Parse( ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider )
{ {
if (TryParse(s, style, provider, out var result)) if( TryParse( s, style, provider, out var result ) )
{ {
return result; return result;
} }
throw new FormatException($"Input string was not in a correct format."); throw new FormatException( $"Input string was not in a correct format." );
} }
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out Cm result) => TryParse(s, NumberStyles.Number, provider, out result); public static bool TryParse( [NotNullWhen( true )] string? s, IFormatProvider? provider, [MaybeNullWhen( false )] out Cm result ) => TryParse( s, NumberStyles.Number, provider, out result );
public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, [MaybeNullWhen(false)] out Cm result) => TryParse(s, NumberStyles.Number, provider, out result); public static bool TryParse( ReadOnlySpan<char> s, IFormatProvider? provider, [MaybeNullWhen( false )] out Cm result ) => TryParse( s, NumberStyles.Number, provider, out result );
public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out Cm result) public static bool TryParse( [NotNullWhen( true )] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen( false )] out Cm result )
{ {
if (decimal.TryParse(s, style, provider, out decimal decValue)) if( decimal.TryParse( s, style, provider, out decimal decValue ) )
{ {
result = new Cm((int)(decValue * 100m)); result = new Cm( (int)( decValue * 100m ) );
return true; return true;
} }
result = Cm.Zero; result = Cm.Zero;
return false; return false;
} }
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out Cm result) public static bool TryParse( ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen( false )] out Cm result )
{ {
if (decimal.TryParse(s, style, provider, out decimal decValue)) if( decimal.TryParse( s, style, provider, out decimal decValue ) )
{ {
result = new Cm((int)(decValue * 100m)); result = new Cm( (int)( decValue * 100m ) );
return true; return true;
} }
result = Cm.Zero; result = Cm.Zero;
@ -121,20 +121,20 @@ sealed public record Cm(int value) : INumber<Cm>
// --- Generic Type Conversion --- // --- Generic Type Conversion ---
public static bool TryConvertFromChecked<TOther>(TOther value, out Cm result) where TOther : INumberBase<TOther> public static bool TryConvertFromChecked<TOther>( TOther value, out Cm result ) where TOther : INumberBase<TOther>
{ {
// For integer types, scale up. For floating point, convert. // For integer types, scale up. For floating point, convert.
if (TOther.IsInteger(value)) if( TOther.IsInteger( value ) )
{ {
try try
{ {
checked checked
{ {
result = new Cm(int.CreateChecked(value) * 100); result = new Cm( int.CreateChecked( value ) * 100 );
return true; return true;
} }
} }
catch (OverflowException) catch( OverflowException )
{ {
result = Cm.Zero; result = Cm.Zero;
return false; return false;
@ -142,22 +142,22 @@ sealed public record Cm(int value) : INumber<Cm>
} }
// Convert floating point types // Convert floating point types
if (typeof(TOther) == typeof(double)) if( typeof( TOther ) == typeof( double ) )
{ {
double d = double.CreateChecked(value); double d = double.CreateChecked( value );
result = From(d); result = From( d );
return true; return true;
} }
if (typeof(TOther) == typeof(float)) if( typeof( TOther ) == typeof( float ) )
{ {
float f = float.CreateChecked(value); float f = float.CreateChecked( value );
result = From(f); result = From( f );
return true; return true;
} }
if (typeof(TOther) == typeof(decimal)) if( typeof( TOther ) == typeof( decimal ) )
{ {
decimal m = decimal.CreateChecked(value); decimal m = decimal.CreateChecked( value );
result = new Cm((int)(m * 100m)); result = new Cm( (int)( m * 100m ) );
return true; return true;
} }
@ -165,65 +165,65 @@ sealed public record Cm(int value) : INumber<Cm>
return false; return false;
} }
public static bool TryConvertFromSaturating<TOther>(TOther value, out Cm result) where TOther : INumberBase<TOther> public static bool TryConvertFromSaturating<TOther>( TOther value, out Cm result ) where TOther : INumberBase<TOther>
{ {
if (TOther.IsInteger(value)) if( TOther.IsInteger( value ) )
{ {
result = new Cm(int.CreateSaturating(value) * 100); result = new Cm( int.CreateSaturating( value ) * 100 );
return true; return true;
} }
if (typeof(TOther) == typeof(double)) if( typeof( TOther ) == typeof( double ) )
{ {
double d = double.CreateSaturating(value); double d = double.CreateSaturating( value );
result = From(d); result = From( d );
return true; return true;
} }
if (typeof(TOther) == typeof(float)) if( typeof( TOther ) == typeof( float ) )
{ {
float f = float.CreateSaturating(value); float f = float.CreateSaturating( value );
result = From(f); result = From( f );
return true; return true;
} }
if (typeof(TOther) == typeof(decimal)) if( typeof( TOther ) == typeof( decimal ) )
{ {
decimal m = decimal.CreateSaturating(value); decimal m = decimal.CreateSaturating( value );
result = new Cm((int)(m * 100m)); result = new Cm( (int)( m * 100m ) );
return true; return true;
} }
result = Cm.Zero; result = Cm.Zero;
return false; return false;
} }
public static bool TryConvertFromTruncating<TOther>(TOther value, out Cm result) where TOther : INumberBase<TOther> public static bool TryConvertFromTruncating<TOther>( TOther value, out Cm result ) where TOther : INumberBase<TOther>
{ {
if (TOther.IsInteger(value)) if( TOther.IsInteger( value ) )
{ {
result = new Cm(int.CreateTruncating(value) * 100); result = new Cm( int.CreateTruncating( value ) * 100 );
return true; return true;
} }
if (typeof(TOther) == typeof(double)) if( typeof( TOther ) == typeof( double ) )
{ {
double d = double.CreateTruncating(value); double d = double.CreateTruncating( value );
result = From(d); result = From( d );
return true; return true;
} }
if (typeof(TOther) == typeof(float)) if( typeof( TOther ) == typeof( float ) )
{ {
float f = float.CreateTruncating(value); float f = float.CreateTruncating( value );
result = From(f); result = From( f );
return true; return true;
} }
if (typeof(TOther) == typeof(decimal)) if( typeof( TOther ) == typeof( decimal ) )
{ {
decimal m = decimal.CreateTruncating(value); decimal m = decimal.CreateTruncating( value );
result = new Cm((int)(m * 100m)); result = new Cm( (int)( m * 100m ) );
return true; return true;
} }
result = Cm.Zero; result = Cm.Zero;
return false; return false;
} }
public static bool TryConvertToChecked<TOther>(Cm value, out TOther result) where TOther : INumberBase<TOther> public static bool TryConvertToChecked<TOther>( Cm value, out TOther result ) where TOther : INumberBase<TOther>
{ {
// Convert our value (a count of centimeters) to another type. // Convert our value (a count of centimeters) to another type.
// This typically involves scaling down by 100. // This typically involves scaling down by 100.
@ -231,109 +231,109 @@ sealed public record Cm(int value) : INumber<Cm>
{ {
checked checked
{ {
if (TOther.IsInteger(TOther.Zero)) if( TOther.IsInteger( TOther.Zero ) )
{ {
result = TOther.CreateChecked(value.value / 100); result = TOther.CreateChecked( value.value / 100 );
return true; return true;
} }
// For floating points, perform floating point division // For floating points, perform floating point division
result = TOther.CreateChecked(value.value) / TOther.CreateChecked(100); result = TOther.CreateChecked( value.value ) / TOther.CreateChecked( 100 );
return true; return true;
} }
} }
catch (OverflowException) catch( OverflowException )
{ {
result = default!; result = default!;
return false; return false;
} }
} }
public static bool TryConvertToSaturating<TOther>(Cm value, out TOther result) where TOther : INumberBase<TOther> public static bool TryConvertToSaturating<TOther>( Cm value, out TOther result ) where TOther : INumberBase<TOther>
{ {
if (TOther.IsInteger(TOther.Zero)) if( TOther.IsInteger( TOther.Zero ) )
{ {
result = TOther.CreateSaturating(value.value / 100); result = TOther.CreateSaturating( value.value / 100 );
return true; return true;
} }
result = TOther.CreateSaturating(value.value) / TOther.CreateSaturating(100); result = TOther.CreateSaturating( value.value ) / TOther.CreateSaturating( 100 );
return true; return true;
} }
public static bool TryConvertToTruncating<TOther>(Cm value, out TOther result) where TOther : INumberBase<TOther> public static bool TryConvertToTruncating<TOther>( Cm value, out TOther result ) where TOther : INumberBase<TOther>
{ {
if (TOther.IsInteger(TOther.Zero)) if( TOther.IsInteger( TOther.Zero ) )
{ {
result = TOther.CreateTruncating(value.value / 100); result = TOther.CreateTruncating( value.value / 100 );
return true; return true;
} }
result = TOther.CreateTruncating(value.value) / TOther.CreateTruncating(100); result = TOther.CreateTruncating( value.value ) / TOther.CreateTruncating( 100 );
return true; return true;
} }
// --- Comparison --- // --- Comparison ---
public int CompareTo(object? obj) public int CompareTo( object? obj )
{ {
if (obj is Cm other) if( obj is Cm other )
{ {
return CompareTo(other); return CompareTo( other );
} }
return obj is null ? 1 : throw new ArgumentException("Object must be of type Cm.", nameof(obj)); return obj is null ? 1 : throw new ArgumentException( "Object must be of type Cm.", nameof( obj ) );
} }
public int CompareTo(Cm? other) => value.CompareTo(other?.value); public int CompareTo( Cm? other ) => value.CompareTo( other?.value );
public bool Equals(Cm? other) => value == other?.value; public bool Equals( Cm? other ) => value == other?.value;
public override int GetHashCode() => value.GetHashCode(); public override int GetHashCode() => value.GetHashCode();
// --- Formatting --- // --- Formatting ---
public override string ToString() => (value / 100.0).ToString("F2", CultureInfo.InvariantCulture); public override string ToString() => ( value / 100.0 ).ToString( "F2", CultureInfo.InvariantCulture );
public string ToString(string? format, IFormatProvider? formatProvider) public string ToString( string? format, IFormatProvider? formatProvider )
{ {
// Format as a floating point number // Format as a floating point number
return (value / 100.0).ToString(format, formatProvider); return ( value / 100.0 ).ToString( format, formatProvider );
} }
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) public bool TryFormat( Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider )
{ {
return (value / 100.0).TryFormat(destination, out charsWritten, format, provider); return ( value / 100.0 ).TryFormat( destination, out charsWritten, format, provider );
} }
// --- Operators --- // --- Operators ---
public static Cm operator +(Cm c) => c; public static Cm operator +( Cm c ) => c;
public static Cm operator +(Cm left, Cm right) => new Cm(left.value + right.value); public static Cm operator +( Cm left, Cm right ) => new Cm( left.value + right.value );
public static Cm operator -(Cm c) => new Cm(-c.value); public static Cm operator -( Cm c ) => new Cm( -c.value );
public static Cm operator -(Cm left, Cm right) => new Cm(left.value - right.value); public static Cm operator -( Cm left, Cm right ) => new Cm( left.value - right.value );
public static Cm operator ++(Cm c) => new Cm(c.value + 1); public static Cm operator ++( Cm c ) => new Cm( c.value + 1 );
public static Cm operator --(Cm c) => new Cm(c.value - 1); public static Cm operator --( Cm c ) => new Cm( c.value - 1 );
// For fixed-point, multiplication/division require scaling // For fixed-point, multiplication/division require scaling
public static Cm operator *(Cm left, Cm right) public static Cm operator *( Cm left, Cm right )
{ {
// (a/100) * (b/100) = (a*b)/10000. To get back to our format, multiply by 100. // (a/100) * (b/100) = (a*b)/10000. To get back to our format, multiply by 100.
// So, (a*b)/100. Use long to prevent intermediate overflow. // So, (a*b)/100. Use long to prevent intermediate overflow.
return new Cm((int)(((long)left.value * right.value) / 100)); return new Cm( (int)( ( (long)left.value * right.value ) / 100 ) );
} }
public static Cm operator /(Cm left, Cm right) public static Cm operator /( Cm left, Cm right )
{ {
// (a/100) / (b/100) = a/b. To get back to our format, multiply by 100. // (a/100) / (b/100) = a/b. To get back to our format, multiply by 100.
// So, (a*100)/b. Use long to prevent intermediate overflow. // So, (a*100)/b. Use long to prevent intermediate overflow.
return new Cm((int)(((long)left.value * 100) / right.value)); return new Cm( (int)( ( (long)left.value * 100 ) / right.value ) );
} }
public static Cm operator %(Cm left, Cm right) => new Cm(left.value % right.value); public static Cm operator %( Cm left, Cm right ) => new Cm( left.value % right.value );
// --- Comparison Operators --- // --- Comparison Operators ---
public static bool operator <(Cm left, Cm right) => left.value < right.value; public static bool operator <( Cm left, Cm right ) => left.value < right.value;
public static bool operator >(Cm left, Cm right) => left.value > right.value; public static bool operator >( Cm left, Cm right ) => left.value > right.value;
public static bool operator <=(Cm left, Cm right) => left.value <= right.value; public static bool operator <=( Cm left, Cm right ) => left.value <= right.value;
public static bool operator >=(Cm left, Cm right) => left.value >= right.value; public static bool operator >=( Cm left, Cm right ) => left.value >= right.value;
} }
/// <summary> /// <summary>
@ -344,20 +344,20 @@ public static class CentEx
// --- Static Conversion Methods --- // --- Static Conversion Methods ---
public static Cm From(float v) => new Cm((int)(v * 100.0f + 0.5f)); public static Cm From( float v ) => new Cm( (int)( v * 100.0f + 0.5f ) );
public static Cm From(double v) => new Cm((int)(v * 100.0 + 0.5)); public static Cm From( double v ) => new Cm( (int)( v * 100.0 + 0.5 ) );
//public static Cm Cm(this float r) => CentEx.From(r); //public static Cm Cm(this float r) => CentEx.From(r);
//public static Cm Cm(this double r) => CentEx.From(r); //public static Cm Cm(this double r) => CentEx.From(r);
extension(float r) extension( float r )
{ {
public Cm Cm => CentEx.From( r ); public Cm Cm => CentEx.From( r );
} }
extension(double r) extension( double r )
{ {
public Cm Cm => CentEx.From( r ); public Cm Cm => CentEx.From( r );
} }

File diff suppressed because it is too large Load Diff

View File

@ -10,716 +10,716 @@ namespace math
/// <summary> /// <summary>
/// Zero color. /// Zero color.
/// </summary> /// </summary>
public static readonly Color Zero = Color.FromBgra(0x00000000); public static readonly Color Zero = Color.FromBgra( 0x00000000 );
/// <summary> /// <summary>
/// Transparent color. /// Transparent color.
/// </summary> /// </summary>
public static readonly Color Transparent = Color.FromBgra(0x00000000); public static readonly Color Transparent = Color.FromBgra( 0x00000000 );
/// <summary> /// <summary>
/// AliceBlue color. /// AliceBlue color.
/// </summary> /// </summary>
public static readonly Color AliceBlue = Color.FromBgra(0xFFF0F8FF); public static readonly Color AliceBlue = Color.FromBgra( 0xFFF0F8FF );
/// <summary> /// <summary>
/// AntiqueWhite color. /// AntiqueWhite color.
/// </summary> /// </summary>
public static readonly Color AntiqueWhite = Color.FromBgra(0xFFFAEBD7); public static readonly Color AntiqueWhite = Color.FromBgra( 0xFFFAEBD7 );
/// <summary> /// <summary>
/// Aqua color. /// Aqua color.
/// </summary> /// </summary>
public static readonly Color Aqua = Color.FromBgra(0xFF00FFFF); public static readonly Color Aqua = Color.FromBgra( 0xFF00FFFF );
/// <summary> /// <summary>
/// Aquamarine color. /// Aquamarine color.
/// </summary> /// </summary>
public static readonly Color Aquamarine = Color.FromBgra(0xFF7FFFD4); public static readonly Color Aquamarine = Color.FromBgra( 0xFF7FFFD4 );
/// <summary> /// <summary>
/// Azure color. /// Azure color.
/// </summary> /// </summary>
public static readonly Color Azure = Color.FromBgra(0xFFF0FFFF); public static readonly Color Azure = Color.FromBgra( 0xFFF0FFFF );
/// <summary> /// <summary>
/// Beige color. /// Beige color.
/// </summary> /// </summary>
public static readonly Color Beige = Color.FromBgra(0xFFF5F5DC); public static readonly Color Beige = Color.FromBgra( 0xFFF5F5DC );
/// <summary> /// <summary>
/// Bisque color. /// Bisque color.
/// </summary> /// </summary>
public static readonly Color Bisque = Color.FromBgra(0xFFFFE4C4); public static readonly Color Bisque = Color.FromBgra( 0xFFFFE4C4 );
/// <summary> /// <summary>
/// Black color. /// Black color.
/// </summary> /// </summary>
public static readonly Color Black = Color.FromBgra(0xFF000000); public static readonly Color Black = Color.FromBgra( 0xFF000000 );
/// <summary> /// <summary>
/// BlanchedAlmond color. /// BlanchedAlmond color.
/// </summary> /// </summary>
public static readonly Color BlanchedAlmond = Color.FromBgra(0xFFFFEBCD); public static readonly Color BlanchedAlmond = Color.FromBgra( 0xFFFFEBCD );
/// <summary> /// <summary>
/// Blue color. /// Blue color.
/// </summary> /// </summary>
public static readonly Color Blue = Color.FromBgra(0xFF0000FF); public static readonly Color Blue = Color.FromBgra( 0xFF0000FF );
/// <summary> /// <summary>
/// BlueViolet color. /// BlueViolet color.
/// </summary> /// </summary>
public static readonly Color BlueViolet = Color.FromBgra(0xFF8A2BE2); public static readonly Color BlueViolet = Color.FromBgra( 0xFF8A2BE2 );
/// <summary> /// <summary>
/// Brown color. /// Brown color.
/// </summary> /// </summary>
public static readonly Color Brown = Color.FromBgra(0xFFA52A2A); public static readonly Color Brown = Color.FromBgra( 0xFFA52A2A );
/// <summary> /// <summary>
/// BurlyWood color. /// BurlyWood color.
/// </summary> /// </summary>
public static readonly Color BurlyWood = Color.FromBgra(0xFFDEB887); public static readonly Color BurlyWood = Color.FromBgra( 0xFFDEB887 );
/// <summary> /// <summary>
/// CadetBlue color. /// CadetBlue color.
/// </summary> /// </summary>
public static readonly Color CadetBlue = Color.FromBgra(0xFF5F9EA0); public static readonly Color CadetBlue = Color.FromBgra( 0xFF5F9EA0 );
/// <summary> /// <summary>
/// Chartreuse color. /// Chartreuse color.
/// </summary> /// </summary>
public static readonly Color Chartreuse = Color.FromBgra(0xFF7FFF00); public static readonly Color Chartreuse = Color.FromBgra( 0xFF7FFF00 );
/// <summary> /// <summary>
/// Chocolate color. /// Chocolate color.
/// </summary> /// </summary>
public static readonly Color Chocolate = Color.FromBgra(0xFFD2691E); public static readonly Color Chocolate = Color.FromBgra( 0xFFD2691E );
/// <summary> /// <summary>
/// Coral color. /// Coral color.
/// </summary> /// </summary>
public static readonly Color Coral = Color.FromBgra(0xFFFF7F50); public static readonly Color Coral = Color.FromBgra( 0xFFFF7F50 );
/// <summary> /// <summary>
/// CornflowerBlue color. /// CornflowerBlue color.
/// </summary> /// </summary>
public static readonly Color CornflowerBlue = Color.FromBgra(0xFF6495ED); public static readonly Color CornflowerBlue = Color.FromBgra( 0xFF6495ED );
/// <summary> /// <summary>
/// Cornsilk color. /// Cornsilk color.
/// </summary> /// </summary>
public static readonly Color Cornsilk = Color.FromBgra(0xFFFFF8DC); public static readonly Color Cornsilk = Color.FromBgra( 0xFFFFF8DC );
/// <summary> /// <summary>
/// Crimson color. /// Crimson color.
/// </summary> /// </summary>
public static readonly Color Crimson = Color.FromBgra(0xFFDC143C); public static readonly Color Crimson = Color.FromBgra( 0xFFDC143C );
/// <summary> /// <summary>
/// Cyan color. /// Cyan color.
/// </summary> /// </summary>
public static readonly Color Cyan = Color.FromBgra(0xFF00FFFF); public static readonly Color Cyan = Color.FromBgra( 0xFF00FFFF );
/// <summary> /// <summary>
/// DarkBlue color. /// DarkBlue color.
/// </summary> /// </summary>
public static readonly Color DarkBlue = Color.FromBgra(0xFF00008B); public static readonly Color DarkBlue = Color.FromBgra( 0xFF00008B );
/// <summary> /// <summary>
/// DarkCyan color. /// DarkCyan color.
/// </summary> /// </summary>
public static readonly Color DarkCyan = Color.FromBgra(0xFF008B8B); public static readonly Color DarkCyan = Color.FromBgra( 0xFF008B8B );
/// <summary> /// <summary>
/// DarkGoldenrod color. /// DarkGoldenrod color.
/// </summary> /// </summary>
public static readonly Color DarkGoldenrod = Color.FromBgra(0xFFB8860B); public static readonly Color DarkGoldenrod = Color.FromBgra( 0xFFB8860B );
/// <summary> /// <summary>
/// DarkGray color. /// DarkGray color.
/// </summary> /// </summary>
public static readonly Color DarkGray = Color.FromBgra(0xFFA9A9A9); public static readonly Color DarkGray = Color.FromBgra( 0xFFA9A9A9 );
/// <summary> /// <summary>
/// DarkGreen color. /// DarkGreen color.
/// </summary> /// </summary>
public static readonly Color DarkGreen = Color.FromBgra(0xFF006400); public static readonly Color DarkGreen = Color.FromBgra( 0xFF006400 );
/// <summary> /// <summary>
/// DarkKhaki color. /// DarkKhaki color.
/// </summary> /// </summary>
public static readonly Color DarkKhaki = Color.FromBgra(0xFFBDB76B); public static readonly Color DarkKhaki = Color.FromBgra( 0xFFBDB76B );
/// <summary> /// <summary>
/// DarkMagenta color. /// DarkMagenta color.
/// </summary> /// </summary>
public static readonly Color DarkMagenta = Color.FromBgra(0xFF8B008B); public static readonly Color DarkMagenta = Color.FromBgra( 0xFF8B008B );
/// <summary> /// <summary>
/// DarkOliveGreen color. /// DarkOliveGreen color.
/// </summary> /// </summary>
public static readonly Color DarkOliveGreen = Color.FromBgra(0xFF556B2F); public static readonly Color DarkOliveGreen = Color.FromBgra( 0xFF556B2F );
/// <summary> /// <summary>
/// DarkOrange color. /// DarkOrange color.
/// </summary> /// </summary>
public static readonly Color DarkOrange = Color.FromBgra(0xFFFF8C00); public static readonly Color DarkOrange = Color.FromBgra( 0xFFFF8C00 );
/// <summary> /// <summary>
/// DarkOrchid color. /// DarkOrchid color.
/// </summary> /// </summary>
public static readonly Color DarkOrchid = Color.FromBgra(0xFF9932CC); public static readonly Color DarkOrchid = Color.FromBgra( 0xFF9932CC );
/// <summary> /// <summary>
/// DarkRed color. /// DarkRed color.
/// </summary> /// </summary>
public static readonly Color DarkRed = Color.FromBgra(0xFF8B0000); public static readonly Color DarkRed = Color.FromBgra( 0xFF8B0000 );
/// <summary> /// <summary>
/// DarkSalmon color. /// DarkSalmon color.
/// </summary> /// </summary>
public static readonly Color DarkSalmon = Color.FromBgra(0xFFE9967A); public static readonly Color DarkSalmon = Color.FromBgra( 0xFFE9967A );
/// <summary> /// <summary>
/// DarkSeaGreen color. /// DarkSeaGreen color.
/// </summary> /// </summary>
public static readonly Color DarkSeaGreen = Color.FromBgra(0xFF8FBC8B); public static readonly Color DarkSeaGreen = Color.FromBgra( 0xFF8FBC8B );
/// <summary> /// <summary>
/// DarkSlateBlue color. /// DarkSlateBlue color.
/// </summary> /// </summary>
public static readonly Color DarkSlateBlue = Color.FromBgra(0xFF483D8B); public static readonly Color DarkSlateBlue = Color.FromBgra( 0xFF483D8B );
/// <summary> /// <summary>
/// DarkSlateGray color. /// DarkSlateGray color.
/// </summary> /// </summary>
public static readonly Color DarkSlateGray = Color.FromBgra(0xFF2F4F4F); public static readonly Color DarkSlateGray = Color.FromBgra( 0xFF2F4F4F );
/// <summary> /// <summary>
/// DarkTurquoise color. /// DarkTurquoise color.
/// </summary> /// </summary>
public static readonly Color DarkTurquoise = Color.FromBgra(0xFF00CED1); public static readonly Color DarkTurquoise = Color.FromBgra( 0xFF00CED1 );
/// <summary> /// <summary>
/// DarkViolet color. /// DarkViolet color.
/// </summary> /// </summary>
public static readonly Color DarkViolet = Color.FromBgra(0xFF9400D3); public static readonly Color DarkViolet = Color.FromBgra( 0xFF9400D3 );
/// <summary> /// <summary>
/// DeepPink color. /// DeepPink color.
/// </summary> /// </summary>
public static readonly Color DeepPink = Color.FromBgra(0xFFFF1493); public static readonly Color DeepPink = Color.FromBgra( 0xFFFF1493 );
/// <summary> /// <summary>
/// DeepSkyBlue color. /// DeepSkyBlue color.
/// </summary> /// </summary>
public static readonly Color DeepSkyBlue = Color.FromBgra(0xFF00BFFF); public static readonly Color DeepSkyBlue = Color.FromBgra( 0xFF00BFFF );
/// <summary> /// <summary>
/// DimGray color. /// DimGray color.
/// </summary> /// </summary>
public static readonly Color DimGray = Color.FromBgra(0xFF696969); public static readonly Color DimGray = Color.FromBgra( 0xFF696969 );
/// <summary> /// <summary>
/// VeryDimGray color. /// VeryDimGray color.
/// </summary> /// </summary>
public static readonly Color VeryDimGray = Color.FromBgra(0xFF404040); public static readonly Color VeryDimGray = Color.FromBgra( 0xFF404040 );
/// <summary> /// <summary>
/// DodgerBlue color. /// DodgerBlue color.
/// </summary> /// </summary>
public static readonly Color DodgerBlue = Color.FromBgra(0xFF1E90FF); public static readonly Color DodgerBlue = Color.FromBgra( 0xFF1E90FF );
/// <summary> /// <summary>
/// Firebrick color. /// Firebrick color.
/// </summary> /// </summary>
public static readonly Color Firebrick = Color.FromBgra(0xFFB22222); public static readonly Color Firebrick = Color.FromBgra( 0xFFB22222 );
/// <summary> /// <summary>
/// FloralWhite color. /// FloralWhite color.
/// </summary> /// </summary>
public static readonly Color FloralWhite = Color.FromBgra(0xFFFFFAF0); public static readonly Color FloralWhite = Color.FromBgra( 0xFFFFFAF0 );
/// <summary> /// <summary>
/// ForestGreen color. /// ForestGreen color.
/// </summary> /// </summary>
public static readonly Color ForestGreen = Color.FromBgra(0xFF228B22); public static readonly Color ForestGreen = Color.FromBgra( 0xFF228B22 );
/// <summary> /// <summary>
/// Fuchsia color. /// Fuchsia color.
/// </summary> /// </summary>
public static readonly Color Fuchsia = Color.FromBgra(0xFFFF00FF); public static readonly Color Fuchsia = Color.FromBgra( 0xFFFF00FF );
/// <summary> /// <summary>
/// Gainsboro color. /// Gainsboro color.
/// </summary> /// </summary>
public static readonly Color Gainsboro = Color.FromBgra(0xFFDCDCDC); public static readonly Color Gainsboro = Color.FromBgra( 0xFFDCDCDC );
/// <summary> /// <summary>
/// GhostWhite color. /// GhostWhite color.
/// </summary> /// </summary>
public static readonly Color GhostWhite = Color.FromBgra(0xFFF8F8FF); public static readonly Color GhostWhite = Color.FromBgra( 0xFFF8F8FF );
/// <summary> /// <summary>
/// Gold color. /// Gold color.
/// </summary> /// </summary>
public static readonly Color Gold = Color.FromBgra(0xFFFFD700); public static readonly Color Gold = Color.FromBgra( 0xFFFFD700 );
/// <summary> /// <summary>
/// Goldenrod color. /// Goldenrod color.
/// </summary> /// </summary>
public static readonly Color Goldenrod = Color.FromBgra(0xFFDAA520); public static readonly Color Goldenrod = Color.FromBgra( 0xFFDAA520 );
/// <summary> /// <summary>
/// Gray color. /// Gray color.
/// </summary> /// </summary>
public static readonly Color Gray = Color.FromBgra(0xFF808080); public static readonly Color Gray = Color.FromBgra( 0xFF808080 );
/// <summary> /// <summary>
/// Green color. /// Green color.
/// </summary> /// </summary>
public static readonly Color Green = Color.FromBgra(0xFF008000); public static readonly Color Green = Color.FromBgra( 0xFF008000 );
/// <summary> /// <summary>
/// GreenYellow color. /// GreenYellow color.
/// </summary> /// </summary>
public static readonly Color GreenYellow = Color.FromBgra(0xFFADFF2F); public static readonly Color GreenYellow = Color.FromBgra( 0xFFADFF2F );
/// <summary> /// <summary>
/// Honeydew color. /// Honeydew color.
/// </summary> /// </summary>
public static readonly Color Honeydew = Color.FromBgra(0xFFF0FFF0); public static readonly Color Honeydew = Color.FromBgra( 0xFFF0FFF0 );
/// <summary> /// <summary>
/// HotPink color. /// HotPink color.
/// </summary> /// </summary>
public static readonly Color HotPink = Color.FromBgra(0xFFFF69B4); public static readonly Color HotPink = Color.FromBgra( 0xFFFF69B4 );
/// <summary> /// <summary>
/// IndianRed color. /// IndianRed color.
/// </summary> /// </summary>
public static readonly Color IndianRed = Color.FromBgra(0xFFCD5C5C); public static readonly Color IndianRed = Color.FromBgra( 0xFFCD5C5C );
/// <summary> /// <summary>
/// Indigo color. /// Indigo color.
/// </summary> /// </summary>
public static readonly Color Indigo = Color.FromBgra(0xFF4B0082); public static readonly Color Indigo = Color.FromBgra( 0xFF4B0082 );
/// <summary> /// <summary>
/// Ivory color. /// Ivory color.
/// </summary> /// </summary>
public static readonly Color Ivory = Color.FromBgra(0xFFFFFFF0); public static readonly Color Ivory = Color.FromBgra( 0xFFFFFFF0 );
/// <summary> /// <summary>
/// Khaki color. /// Khaki color.
/// </summary> /// </summary>
public static readonly Color Khaki = Color.FromBgra(0xFFF0E68C); public static readonly Color Khaki = Color.FromBgra( 0xFFF0E68C );
/// <summary> /// <summary>
/// Lavender color. /// Lavender color.
/// </summary> /// </summary>
public static readonly Color Lavender = Color.FromBgra(0xFFE6E6FA); public static readonly Color Lavender = Color.FromBgra( 0xFFE6E6FA );
/// <summary> /// <summary>
/// LavenderBlush color. /// LavenderBlush color.
/// </summary> /// </summary>
public static readonly Color LavenderBlush = Color.FromBgra(0xFFFFF0F5); public static readonly Color LavenderBlush = Color.FromBgra( 0xFFFFF0F5 );
/// <summary> /// <summary>
/// LawnGreen color. /// LawnGreen color.
/// </summary> /// </summary>
public static readonly Color LawnGreen = Color.FromBgra(0xFF7CFC00); public static readonly Color LawnGreen = Color.FromBgra( 0xFF7CFC00 );
/// <summary> /// <summary>
/// LemonChiffon color. /// LemonChiffon color.
/// </summary> /// </summary>
public static readonly Color LemonChiffon = Color.FromBgra(0xFFFFFACD); public static readonly Color LemonChiffon = Color.FromBgra( 0xFFFFFACD );
/// <summary> /// <summary>
/// LightBlue color. /// LightBlue color.
/// </summary> /// </summary>
public static readonly Color LightBlue = Color.FromBgra(0xFFADD8E6); public static readonly Color LightBlue = Color.FromBgra( 0xFFADD8E6 );
/// <summary> /// <summary>
/// LightCoral color. /// LightCoral color.
/// </summary> /// </summary>
public static readonly Color LightCoral = Color.FromBgra(0xFFF08080); public static readonly Color LightCoral = Color.FromBgra( 0xFFF08080 );
/// <summary> /// <summary>
/// LightCyan color. /// LightCyan color.
/// </summary> /// </summary>
public static readonly Color LightCyan = Color.FromBgra(0xFFE0FFFF); public static readonly Color LightCyan = Color.FromBgra( 0xFFE0FFFF );
/// <summary> /// <summary>
/// LightGoldenrodYellow color. /// LightGoldenrodYellow color.
/// </summary> /// </summary>
public static readonly Color LightGoldenrodYellow = Color.FromBgra(0xFFFAFAD2); public static readonly Color LightGoldenrodYellow = Color.FromBgra( 0xFFFAFAD2 );
/// <summary> /// <summary>
/// LightGray color. /// LightGray color.
/// </summary> /// </summary>
public static readonly Color LightGray = Color.FromBgra(0xFFD3D3D3); public static readonly Color LightGray = Color.FromBgra( 0xFFD3D3D3 );
/// <summary> /// <summary>
/// LightGreen color. /// LightGreen color.
/// </summary> /// </summary>
public static readonly Color LightGreen = Color.FromBgra(0xFF90EE90); public static readonly Color LightGreen = Color.FromBgra( 0xFF90EE90 );
/// <summary> /// <summary>
/// LightPink color. /// LightPink color.
/// </summary> /// </summary>
public static readonly Color LightPink = Color.FromBgra(0xFFFFB6C1); public static readonly Color LightPink = Color.FromBgra( 0xFFFFB6C1 );
/// <summary> /// <summary>
/// LightSalmon color. /// LightSalmon color.
/// </summary> /// </summary>
public static readonly Color LightSalmon = Color.FromBgra(0xFFFFA07A); public static readonly Color LightSalmon = Color.FromBgra( 0xFFFFA07A );
/// <summary> /// <summary>
/// LightSeaGreen color. /// LightSeaGreen color.
/// </summary> /// </summary>
public static readonly Color LightSeaGreen = Color.FromBgra(0xFF20B2AA); public static readonly Color LightSeaGreen = Color.FromBgra( 0xFF20B2AA );
/// <summary> /// <summary>
/// LightSkyBlue color. /// LightSkyBlue color.
/// </summary> /// </summary>
public static readonly Color LightSkyBlue = Color.FromBgra(0xFF87CEFA); public static readonly Color LightSkyBlue = Color.FromBgra( 0xFF87CEFA );
/// <summary> /// <summary>
/// LightSlateGray color. /// LightSlateGray color.
/// </summary> /// </summary>
public static readonly Color LightSlateGray = Color.FromBgra(0xFF778899); public static readonly Color LightSlateGray = Color.FromBgra( 0xFF778899 );
/// <summary> /// <summary>
/// LightSteelBlue color. /// LightSteelBlue color.
/// </summary> /// </summary>
public static readonly Color LightSteelBlue = Color.FromBgra(0xFFB0C4DE); public static readonly Color LightSteelBlue = Color.FromBgra( 0xFFB0C4DE );
/// <summary> /// <summary>
/// LightYellow color. /// LightYellow color.
/// </summary> /// </summary>
public static readonly Color LightYellow = Color.FromBgra(0xFFFFFFE0); public static readonly Color LightYellow = Color.FromBgra( 0xFFFFFFE0 );
/// <summary> /// <summary>
/// Lime color. /// Lime color.
/// </summary> /// </summary>
public static readonly Color Lime = Color.FromBgra(0xFF00FF00); public static readonly Color Lime = Color.FromBgra( 0xFF00FF00 );
/// <summary> /// <summary>
/// LimeGreen color. /// LimeGreen color.
/// </summary> /// </summary>
public static readonly Color LimeGreen = Color.FromBgra(0xFF32CD32); public static readonly Color LimeGreen = Color.FromBgra( 0xFF32CD32 );
/// <summary> /// <summary>
/// Linen color. /// Linen color.
/// </summary> /// </summary>
public static readonly Color Linen = Color.FromBgra(0xFFFAF0E6); public static readonly Color Linen = Color.FromBgra( 0xFFFAF0E6 );
/// <summary> /// <summary>
/// Magenta color. /// Magenta color.
/// </summary> /// </summary>
public static readonly Color Magenta = Color.FromBgra(0xFFFF00FF); public static readonly Color Magenta = Color.FromBgra( 0xFFFF00FF );
/// <summary> /// <summary>
/// Maroon color. /// Maroon color.
/// </summary> /// </summary>
public static readonly Color Maroon = Color.FromBgra(0xFF800000); public static readonly Color Maroon = Color.FromBgra( 0xFF800000 );
/// <summary> /// <summary>
/// MediumAquamarine color. /// MediumAquamarine color.
/// </summary> /// </summary>
public static readonly Color MediumAquamarine = Color.FromBgra(0xFF66CDAA); public static readonly Color MediumAquamarine = Color.FromBgra( 0xFF66CDAA );
/// <summary> /// <summary>
/// MediumBlue color. /// MediumBlue color.
/// </summary> /// </summary>
public static readonly Color MediumBlue = Color.FromBgra(0xFF0000CD); public static readonly Color MediumBlue = Color.FromBgra( 0xFF0000CD );
/// <summary> /// <summary>
/// MediumOrchid color. /// MediumOrchid color.
/// </summary> /// </summary>
public static readonly Color MediumOrchid = Color.FromBgra(0xFFBA55D3); public static readonly Color MediumOrchid = Color.FromBgra( 0xFFBA55D3 );
/// <summary> /// <summary>
/// MediumPurple color. /// MediumPurple color.
/// </summary> /// </summary>
public static readonly Color MediumPurple = Color.FromBgra(0xFF9370DB); public static readonly Color MediumPurple = Color.FromBgra( 0xFF9370DB );
/// <summary> /// <summary>
/// MediumSeaGreen color. /// MediumSeaGreen color.
/// </summary> /// </summary>
public static readonly Color MediumSeaGreen = Color.FromBgra(0xFF3CB371); public static readonly Color MediumSeaGreen = Color.FromBgra( 0xFF3CB371 );
/// <summary> /// <summary>
/// MediumSlateBlue color. /// MediumSlateBlue color.
/// </summary> /// </summary>
public static readonly Color MediumSlateBlue = Color.FromBgra(0xFF7B68EE); public static readonly Color MediumSlateBlue = Color.FromBgra( 0xFF7B68EE );
/// <summary> /// <summary>
/// MediumSpringGreen color. /// MediumSpringGreen color.
/// </summary> /// </summary>
public static readonly Color MediumSpringGreen = Color.FromBgra(0xFF00FA9A); public static readonly Color MediumSpringGreen = Color.FromBgra( 0xFF00FA9A );
/// <summary> /// <summary>
/// MediumTurquoise color. /// MediumTurquoise color.
/// </summary> /// </summary>
public static readonly Color MediumTurquoise = Color.FromBgra(0xFF48D1CC); public static readonly Color MediumTurquoise = Color.FromBgra( 0xFF48D1CC );
/// <summary> /// <summary>
/// MediumVioletRed color. /// MediumVioletRed color.
/// </summary> /// </summary>
public static readonly Color MediumVioletRed = Color.FromBgra(0xFFC71585); public static readonly Color MediumVioletRed = Color.FromBgra( 0xFFC71585 );
/// <summary> /// <summary>
/// MidnightBlue color. /// MidnightBlue color.
/// </summary> /// </summary>
public static readonly Color MidnightBlue = Color.FromBgra(0xFF191970); public static readonly Color MidnightBlue = Color.FromBgra( 0xFF191970 );
/// <summary> /// <summary>
/// MintCream color. /// MintCream color.
/// </summary> /// </summary>
public static readonly Color MintCream = Color.FromBgra(0xFFF5FFFA); public static readonly Color MintCream = Color.FromBgra( 0xFFF5FFFA );
/// <summary> /// <summary>
/// MistyRose color. /// MistyRose color.
/// </summary> /// </summary>
public static readonly Color MistyRose = Color.FromBgra(0xFFFFE4E1); public static readonly Color MistyRose = Color.FromBgra( 0xFFFFE4E1 );
/// <summary> /// <summary>
/// Moccasin color. /// Moccasin color.
/// </summary> /// </summary>
public static readonly Color Moccasin = Color.FromBgra(0xFFFFE4B5); public static readonly Color Moccasin = Color.FromBgra( 0xFFFFE4B5 );
/// <summary> /// <summary>
/// NavajoWhite color. /// NavajoWhite color.
/// </summary> /// </summary>
public static readonly Color NavajoWhite = Color.FromBgra(0xFFFFDEAD); public static readonly Color NavajoWhite = Color.FromBgra( 0xFFFFDEAD );
/// <summary> /// <summary>
/// Navy color. /// Navy color.
/// </summary> /// </summary>
public static readonly Color Navy = Color.FromBgra(0xFF000080); public static readonly Color Navy = Color.FromBgra( 0xFF000080 );
/// <summary> /// <summary>
/// OldLace color. /// OldLace color.
/// </summary> /// </summary>
public static readonly Color OldLace = Color.FromBgra(0xFFFDF5E6); public static readonly Color OldLace = Color.FromBgra( 0xFFFDF5E6 );
/// <summary> /// <summary>
/// Olive color. /// Olive color.
/// </summary> /// </summary>
public static readonly Color Olive = Color.FromBgra(0xFF808000); public static readonly Color Olive = Color.FromBgra( 0xFF808000 );
/// <summary> /// <summary>
/// OliveDrab color. /// OliveDrab color.
/// </summary> /// </summary>
public static readonly Color OliveDrab = Color.FromBgra(0xFF6B8E23); public static readonly Color OliveDrab = Color.FromBgra( 0xFF6B8E23 );
/// <summary> /// <summary>
/// Orange color. /// Orange color.
/// </summary> /// </summary>
public static readonly Color Orange = Color.FromBgra(0xFFFFA500); public static readonly Color Orange = Color.FromBgra( 0xFFFFA500 );
/// <summary> /// <summary>
/// OrangeRed color. /// OrangeRed color.
/// </summary> /// </summary>
public static readonly Color OrangeRed = Color.FromBgra(0xFFFF4500); public static readonly Color OrangeRed = Color.FromBgra( 0xFFFF4500 );
/// <summary> /// <summary>
/// Orchid color. /// Orchid color.
/// </summary> /// </summary>
public static readonly Color Orchid = Color.FromBgra(0xFFDA70D6); public static readonly Color Orchid = Color.FromBgra( 0xFFDA70D6 );
/// <summary> /// <summary>
/// PaleGoldenrod color. /// PaleGoldenrod color.
/// </summary> /// </summary>
public static readonly Color PaleGoldenrod = Color.FromBgra(0xFFEEE8AA); public static readonly Color PaleGoldenrod = Color.FromBgra( 0xFFEEE8AA );
/// <summary> /// <summary>
/// PaleGreen color. /// PaleGreen color.
/// </summary> /// </summary>
public static readonly Color PaleGreen = Color.FromBgra(0xFF98FB98); public static readonly Color PaleGreen = Color.FromBgra( 0xFF98FB98 );
/// <summary> /// <summary>
/// PaleTurquoise color. /// PaleTurquoise color.
/// </summary> /// </summary>
public static readonly Color PaleTurquoise = Color.FromBgra(0xFFAFEEEE); public static readonly Color PaleTurquoise = Color.FromBgra( 0xFFAFEEEE );
/// <summary> /// <summary>
/// PaleVioletRed color. /// PaleVioletRed color.
/// </summary> /// </summary>
public static readonly Color PaleVioletRed = Color.FromBgra(0xFFDB7093); public static readonly Color PaleVioletRed = Color.FromBgra( 0xFFDB7093 );
/// <summary> /// <summary>
/// PapayaWhip color. /// PapayaWhip color.
/// </summary> /// </summary>
public static readonly Color PapayaWhip = Color.FromBgra(0xFFFFEFD5); public static readonly Color PapayaWhip = Color.FromBgra( 0xFFFFEFD5 );
/// <summary> /// <summary>
/// PeachPuff color. /// PeachPuff color.
/// </summary> /// </summary>
public static readonly Color PeachPuff = Color.FromBgra(0xFFFFDAB9); public static readonly Color PeachPuff = Color.FromBgra( 0xFFFFDAB9 );
/// <summary> /// <summary>
/// Peru color. /// Peru color.
/// </summary> /// </summary>
public static readonly Color Peru = Color.FromBgra(0xFFCD853F); public static readonly Color Peru = Color.FromBgra( 0xFFCD853F );
/// <summary> /// <summary>
/// Pink color. /// Pink color.
/// </summary> /// </summary>
public static readonly Color Pink = Color.FromBgra(0xFFFFC0CB); public static readonly Color Pink = Color.FromBgra( 0xFFFFC0CB );
/// <summary> /// <summary>
/// Plum color. /// Plum color.
/// </summary> /// </summary>
public static readonly Color Plum = Color.FromBgra(0xFFDDA0DD); public static readonly Color Plum = Color.FromBgra( 0xFFDDA0DD );
/// <summary> /// <summary>
/// PowderBlue color. /// PowderBlue color.
/// </summary> /// </summary>
public static readonly Color PowderBlue = Color.FromBgra(0xFFB0E0E6); public static readonly Color PowderBlue = Color.FromBgra( 0xFFB0E0E6 );
/// <summary> /// <summary>
/// Purple color. /// Purple color.
/// </summary> /// </summary>
public static readonly Color Purple = Color.FromBgra(0xFF800080); public static readonly Color Purple = Color.FromBgra( 0xFF800080 );
/// <summary> /// <summary>
/// Red color. /// Red color.
/// </summary> /// </summary>
public static readonly Color Red = Color.FromBgra(0xFFFF0000); public static readonly Color Red = Color.FromBgra( 0xFFFF0000 );
/// <summary> /// <summary>
/// RosyBrown color. /// RosyBrown color.
/// </summary> /// </summary>
public static readonly Color RosyBrown = Color.FromBgra(0xFFBC8F8F); public static readonly Color RosyBrown = Color.FromBgra( 0xFFBC8F8F );
/// <summary> /// <summary>
/// RoyalBlue color. /// RoyalBlue color.
/// </summary> /// </summary>
public static readonly Color RoyalBlue = Color.FromBgra(0xFF4169E1); public static readonly Color RoyalBlue = Color.FromBgra( 0xFF4169E1 );
/// <summary> /// <summary>
/// SaddleBrown color. /// SaddleBrown color.
/// </summary> /// </summary>
public static readonly Color SaddleBrown = Color.FromBgra(0xFF8B4513); public static readonly Color SaddleBrown = Color.FromBgra( 0xFF8B4513 );
/// <summary> /// <summary>
/// Salmon color. /// Salmon color.
/// </summary> /// </summary>
public static readonly Color Salmon = Color.FromBgra(0xFFFA8072); public static readonly Color Salmon = Color.FromBgra( 0xFFFA8072 );
/// <summary> /// <summary>
/// SandyBrown color. /// SandyBrown color.
/// </summary> /// </summary>
public static readonly Color SandyBrown = Color.FromBgra(0xFFF4A460); public static readonly Color SandyBrown = Color.FromBgra( 0xFFF4A460 );
/// <summary> /// <summary>
/// SeaGreen color. /// SeaGreen color.
/// </summary> /// </summary>
public static readonly Color SeaGreen = Color.FromBgra(0xFF2E8B57); public static readonly Color SeaGreen = Color.FromBgra( 0xFF2E8B57 );
/// <summary> /// <summary>
/// SeaShell color. /// SeaShell color.
/// </summary> /// </summary>
public static readonly Color SeaShell = Color.FromBgra(0xFFFFF5EE); public static readonly Color SeaShell = Color.FromBgra( 0xFFFFF5EE );
/// <summary> /// <summary>
/// Sienna color. /// Sienna color.
/// </summary> /// </summary>
public static readonly Color Sienna = Color.FromBgra(0xFFA0522D); public static readonly Color Sienna = Color.FromBgra( 0xFFA0522D );
/// <summary> /// <summary>
/// Silver color. /// Silver color.
/// </summary> /// </summary>
public static readonly Color Silver = Color.FromBgra(0xFFC0C0C0); public static readonly Color Silver = Color.FromBgra( 0xFFC0C0C0 );
/// <summary> /// <summary>
/// SkyBlue color. /// SkyBlue color.
/// </summary> /// </summary>
public static readonly Color SkyBlue = Color.FromBgra(0xFF87CEEB); public static readonly Color SkyBlue = Color.FromBgra( 0xFF87CEEB );
/// <summary> /// <summary>
/// SlateBlue color. /// SlateBlue color.
/// </summary> /// </summary>
public static readonly Color SlateBlue = Color.FromBgra(0xFF6A5ACD); public static readonly Color SlateBlue = Color.FromBgra( 0xFF6A5ACD );
/// <summary> /// <summary>
/// SlateGray color. /// SlateGray color.
/// </summary> /// </summary>
public static readonly Color SlateGray = Color.FromBgra(0xFF708090); public static readonly Color SlateGray = Color.FromBgra( 0xFF708090 );
/// <summary> /// <summary>
/// Snow color. /// Snow color.
/// </summary> /// </summary>
public static readonly Color Snow = Color.FromBgra(0xFFFFFAFA); public static readonly Color Snow = Color.FromBgra( 0xFFFFFAFA );
/// <summary> /// <summary>
/// SpringGreen color. /// SpringGreen color.
/// </summary> /// </summary>
public static readonly Color SpringGreen = Color.FromBgra(0xFF00FF7F); public static readonly Color SpringGreen = Color.FromBgra( 0xFF00FF7F );
/// <summary> /// <summary>
/// SteelBlue color. /// SteelBlue color.
/// </summary> /// </summary>
public static readonly Color SteelBlue = Color.FromBgra(0xFF4682B4); public static readonly Color SteelBlue = Color.FromBgra( 0xFF4682B4 );
/// <summary> /// <summary>
/// Tan color. /// Tan color.
/// </summary> /// </summary>
public static readonly Color Tan = Color.FromBgra(0xFFD2B48C); public static readonly Color Tan = Color.FromBgra( 0xFFD2B48C );
/// <summary> /// <summary>
/// Teal color. /// Teal color.
/// </summary> /// </summary>
public static readonly Color Teal = Color.FromBgra(0xFF008080); public static readonly Color Teal = Color.FromBgra( 0xFF008080 );
/// <summary> /// <summary>
/// Thistle color. /// Thistle color.
/// </summary> /// </summary>
public static readonly Color Thistle = Color.FromBgra(0xFFD8BFD8); public static readonly Color Thistle = Color.FromBgra( 0xFFD8BFD8 );
/// <summary> /// <summary>
/// Tomato color. /// Tomato color.
/// </summary> /// </summary>
public static readonly Color Tomato = Color.FromBgra(0xFFFF6347); public static readonly Color Tomato = Color.FromBgra( 0xFFFF6347 );
/// <summary> /// <summary>
/// Turquoise color. /// Turquoise color.
/// </summary> /// </summary>
public static readonly Color Turquoise = Color.FromBgra(0xFF40E0D0); public static readonly Color Turquoise = Color.FromBgra( 0xFF40E0D0 );
/// <summary> /// <summary>
/// Violet color. /// Violet color.
/// </summary> /// </summary>
public static readonly Color Violet = Color.FromBgra(0xFFEE82EE); public static readonly Color Violet = Color.FromBgra( 0xFFEE82EE );
/// <summary> /// <summary>
/// Wheat color. /// Wheat color.
/// </summary> /// </summary>
public static readonly Color Wheat = Color.FromBgra(0xFFF5DEB3); public static readonly Color Wheat = Color.FromBgra( 0xFFF5DEB3 );
/// <summary> /// <summary>
/// White color. /// White color.
/// </summary> /// </summary>
public static readonly Color White = Color.FromBgra(0xFFFFFFFF); public static readonly Color White = Color.FromBgra( 0xFFFFFFFF );
/// <summary> /// <summary>
/// WhiteSmoke color. /// WhiteSmoke color.
/// </summary> /// </summary>
public static readonly Color WhiteSmoke = Color.FromBgra(0xFFF5F5F5); public static readonly Color WhiteSmoke = Color.FromBgra( 0xFFF5F5F5 );
/// <summary> /// <summary>
/// Yellow color. /// Yellow color.
/// </summary> /// </summary>
public static readonly Color Yellow = Color.FromBgra(0xFFFFFF00); public static readonly Color Yellow = Color.FromBgra( 0xFFFFFF00 );
/// <summary> /// <summary>
/// YellowGreen color. /// YellowGreen color.
/// </summary> /// </summary>
public static readonly Color YellowGreen = Color.FromBgra(0xFF9ACD32); public static readonly Color YellowGreen = Color.FromBgra( 0xFF9ACD32 );
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -36,9 +36,9 @@ namespace math
/// <summary> /// <summary>
/// Represents a color in the form of rgb. /// Represents a color in the form of rgb.
/// </summary> /// </summary>
[DataContract( Name = "Color3")] [DataContract( Name = "Color3" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Color3 : IEquatable<Color3>, IFormattable public struct Color3 : IEquatable<Color3>, IFormattable
{ {
private const string ToStringFormat = "R:{0} G:{1} B:{2}"; private const string ToStringFormat = "R:{0} G:{1} B:{2}";
@ -65,7 +65,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color3"/> struct. /// Initializes a new instance of the <see cref="Color3"/> struct.
/// </summary> /// </summary>
/// <param name="value">The value that will be assigned to all components.</param> /// <param name="value">The value that will be assigned to all components.</param>
public Color3(float value) public Color3( float value )
{ {
R = G = B = value; R = G = B = value;
} }
@ -76,7 +76,7 @@ namespace math
/// <param name="red">The red component of the color.</param> /// <param name="red">The red component of the color.</param>
/// <param name="green">The green component of the color.</param> /// <param name="green">The green component of the color.</param>
/// <param name="blue">The blue component of the color.</param> /// <param name="blue">The blue component of the color.</param>
public Color3(float red, float green, float blue) public Color3( float red, float green, float blue )
{ {
R = red; R = red;
G = green; G = green;
@ -87,7 +87,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color3"/> struct. /// Initializes a new instance of the <see cref="Color3"/> struct.
/// </summary> /// </summary>
/// <param name="value">The red, green, and blue components of the color.</param> /// <param name="value">The red, green, and blue components of the color.</param>
public Color3(Vec3 value) public Color3( Vec3 value )
{ {
R = value.X; R = value.X;
G = value.Y; G = value.Y;
@ -99,11 +99,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="rgb">A packed integer containing all three color components. /// <param name="rgb">A packed integer containing all three color components.
/// The alpha component is ignored.</param> /// The alpha component is ignored.</param>
public Color3(int rgb) public Color3( int rgb )
{ {
B = ((rgb >> 16) & 255) / 255.0f; B = ( ( rgb >> 16 ) & 255 ) / 255.0f;
G = ((rgb >> 8) & 255) / 255.0f; G = ( ( rgb >> 8 ) & 255 ) / 255.0f;
R = (rgb & 255) / 255.0f; R = ( rgb & 255 ) / 255.0f;
} }
/// <summary> /// <summary>
@ -111,11 +111,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="rgb">A packed unsigned integer containing all three color components. /// <param name="rgb">A packed unsigned integer containing all three color components.
/// The alpha component is ignored.</param> /// The alpha component is ignored.</param>
public Color3(uint rgb) public Color3( uint rgb )
{ {
B = ((rgb >> 16) & 255) / 255.0f; B = ( ( rgb >> 16 ) & 255 ) / 255.0f;
G = ((rgb >> 8) & 255) / 255.0f; G = ( ( rgb >> 8 ) & 255 ) / 255.0f;
R = (rgb & 255) / 255.0f; R = ( rgb & 255 ) / 255.0f;
} }
/// <summary> /// <summary>
@ -124,12 +124,12 @@ namespace math
/// <param name="values">The values to assign to the red, green, and blue components of the color. This must be an array with three elements.</param> /// <param name="values">The values to assign to the red, green, and blue components of the color. This must be an array with three elements.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception>
public Color3(float[] values) public Color3( float[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException(nameof(values)); throw new ArgumentNullException( nameof( values ) );
if (values.Length != 3) if( values.Length != 3 )
throw new ArgumentOutOfRangeException(nameof(values), "There must be three and only three input values for Color3."); throw new ArgumentOutOfRangeException( nameof( values ), "There must be three and only three input values for Color3." );
R = values[0]; R = values[0];
G = values[1]; G = values[1];
@ -147,24 +147,34 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: return R; case 0:
case 1: return G; return R;
case 2: return B; case 1:
return G;
case 2:
return B;
} }
throw new ArgumentOutOfRangeException(nameof(index), "Indices for Color3 run from 0 to 2, inclusive."); throw new ArgumentOutOfRangeException( nameof( index ), "Indices for Color3 run from 0 to 2, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: R = value; break; case 0:
case 1: G = value; break; R = value;
case 2: B = value; break; break;
default: throw new ArgumentOutOfRangeException(nameof(index), "Indices for Color3 run from 0 to 2, inclusive."); case 1:
G = value;
break;
case 2:
B = value;
break;
default:
throw new ArgumentOutOfRangeException( nameof( index ), "Indices for Color3 run from 0 to 2, inclusive." );
} }
} }
} }
@ -177,9 +187,9 @@ namespace math
public int ToRgb() public int ToRgb()
{ {
uint a = 255; uint a = 255;
uint r = (uint)(R * 255.0f); uint r = (uint)( R * 255.0f );
uint g = (uint)(G * 255.0f); uint g = (uint)( G * 255.0f );
uint b = (uint)(B * 255.0f); uint b = (uint)( B * 255.0f );
uint value = r; uint value = r;
value += g << 8; value += g << 8;
@ -193,11 +203,11 @@ namespace math
/// Raises the exponent for each components. /// Raises the exponent for each components.
/// </summary> /// </summary>
/// <param name="exponent">The exponent.</param> /// <param name="exponent">The exponent.</param>
public void Pow(float exponent) public void Pow( float exponent )
{ {
R = (float)Math.Pow(R, exponent); R = (float)Math.Pow( R, exponent );
G = (float)Math.Pow(G, exponent); G = (float)Math.Pow( G, exponent );
B = (float)Math.Pow(B, exponent); B = (float)Math.Pow( B, exponent );
} }
/// <summary> /// <summary>
@ -206,7 +216,7 @@ namespace math
/// <returns>A three component vector containing the red, green, and blue components of the color.</returns> /// <returns>A three component vector containing the red, green, and blue components of the color.</returns>
public Vec3 ToVector3() public Vec3 ToVector3()
{ {
return new Vec3(R, G, B); return new Vec3( R, G, B );
} }
/// <summary> /// <summary>
@ -224,7 +234,7 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <param name="result">When the method completes, completes the sum of the two colors.</param> /// <param name="result">When the method completes, completes the sum of the two colors.</param>
public static void Add(ref Color3 left, ref Color3 right, out Color3 result) public static void Add( ref Color3 left, ref Color3 right, out Color3 result )
{ {
result.R = left.R + right.R; result.R = left.R + right.R;
result.G = left.G + right.G; result.G = left.G + right.G;
@ -237,9 +247,9 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <returns>The sum of the two colors.</returns> /// <returns>The sum of the two colors.</returns>
public static Color3 Add(Color3 left, Color3 right) public static Color3 Add( Color3 left, Color3 right )
{ {
return new Color3(left.R + right.R, left.G + right.G, left.B + right.B); return new Color3( left.R + right.R, left.G + right.G, left.B + right.B );
} }
/// <summary> /// <summary>
@ -248,7 +258,7 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param> /// <param name="right">The second color to subtract.</param>
/// <param name="result">WHen the method completes, contains the difference of the two colors.</param> /// <param name="result">WHen the method completes, contains the difference of the two colors.</param>
public static void Subtract(ref Color3 left, ref Color3 right, out Color3 result) public static void Subtract( ref Color3 left, ref Color3 right, out Color3 result )
{ {
result.R = left.R - right.R; result.R = left.R - right.R;
result.G = left.G - right.G; result.G = left.G - right.G;
@ -261,9 +271,9 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract</param> /// <param name="right">The second color to subtract</param>
/// <returns>The difference of the two colors.</returns> /// <returns>The difference of the two colors.</returns>
public static Color3 Subtract(Color3 left, Color3 right) public static Color3 Subtract( Color3 left, Color3 right )
{ {
return new Color3(left.R - right.R, left.G - right.G, left.B - right.B); return new Color3( left.R - right.R, left.G - right.G, left.B - right.B );
} }
/// <summary> /// <summary>
@ -272,7 +282,7 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <param name="result">When the method completes, contains the modulated color.</param> /// <param name="result">When the method completes, contains the modulated color.</param>
public static void Modulate(ref Color3 left, ref Color3 right, out Color3 result) public static void Modulate( ref Color3 left, ref Color3 right, out Color3 result )
{ {
result.R = left.R * right.R; result.R = left.R * right.R;
result.G = left.G * right.G; result.G = left.G * right.G;
@ -285,9 +295,9 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <returns>The modulated color.</returns> /// <returns>The modulated color.</returns>
public static Color3 Modulate(Color3 left, Color3 right) public static Color3 Modulate( Color3 left, Color3 right )
{ {
return new Color3(left.R * right.R, left.G * right.G, left.B * right.B); return new Color3( left.R * right.R, left.G * right.G, left.B * right.B );
} }
/// <summary> /// <summary>
@ -296,7 +306,7 @@ namespace math
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param> /// <param name="scale">The amount by which to scale.</param>
/// <param name="result">When the method completes, contains the scaled color.</param> /// <param name="result">When the method completes, contains the scaled color.</param>
public static void Scale(ref Color3 value, float scale, out Color3 result) public static void Scale( ref Color3 value, float scale, out Color3 result )
{ {
result.R = value.R * scale; result.R = value.R * scale;
result.G = value.G * scale; result.G = value.G * scale;
@ -309,9 +319,9 @@ namespace math
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param> /// <param name="scale">The amount by which to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color3 Scale(Color3 value, float scale) public static Color3 Scale( Color3 value, float scale )
{ {
return new Color3(value.R * scale, value.G * scale, value.B * scale); return new Color3( value.R * scale, value.G * scale, value.B * scale );
} }
/// <summary> /// <summary>
@ -319,7 +329,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <param name="result">When the method completes, contains the negated color.</param> /// <param name="result">When the method completes, contains the negated color.</param>
public static void Negate(ref Color3 value, out Color3 result) public static void Negate( ref Color3 value, out Color3 result )
{ {
result.R = 1.0f - value.R; result.R = 1.0f - value.R;
result.G = 1.0f - value.G; result.G = 1.0f - value.G;
@ -331,9 +341,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <returns>The negated color.</returns> /// <returns>The negated color.</returns>
public static Color3 Negate(Color3 value) public static Color3 Negate( Color3 value )
{ {
return new Color3(1.0f - value.R, 1.0f - value.G, 1.0f - value.B); return new Color3( 1.0f - value.R, 1.0f - value.G, 1.0f - value.B );
} }
/// <summary> /// <summary>
@ -343,21 +353,21 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <param name="result">When the method completes, contains the clamped value.</param> /// <param name="result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref Color3 value, ref Color3 min, ref Color3 max, out Color3 result) public static void Clamp( ref Color3 value, ref Color3 min, ref Color3 max, out Color3 result )
{ {
float red = value.R; float red = value.R;
red = (red > max.R) ? max.R : red; red = ( red > max.R ) ? max.R : red;
red = (red < min.R) ? min.R : red; red = ( red < min.R ) ? min.R : red;
float green = value.G; float green = value.G;
green = (green > max.G) ? max.G : green; green = ( green > max.G ) ? max.G : green;
green = (green < min.G) ? min.G : green; green = ( green < min.G ) ? min.G : green;
float blue = value.B; float blue = value.B;
blue = (blue > max.B) ? max.B : blue; blue = ( blue > max.B ) ? max.B : blue;
blue = (blue < min.B) ? min.B : blue; blue = ( blue < min.B ) ? min.B : blue;
result = new Color3(red, green, blue); result = new Color3( red, green, blue );
} }
/// <summary> /// <summary>
@ -367,10 +377,10 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static Color3 Clamp(Color3 value, Color3 min, Color3 max) public static Color3 Clamp( Color3 value, Color3 min, Color3 max )
{ {
Color3 result; Color3 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -386,11 +396,11 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static void Lerp(ref Color3 start, ref Color3 end, float amount, out Color3 result) public static void Lerp( ref Color3 start, ref Color3 end, float amount, out Color3 result )
{ {
result.R = start.R + amount * (end.R - start.R); result.R = start.R + amount * ( end.R - start.R );
result.G = start.G + amount * (end.G - start.G); result.G = start.G + amount * ( end.G - start.G );
result.B = start.B + amount * (end.B - start.B); result.B = start.B + amount * ( end.B - start.B );
} }
/// <summary> /// <summary>
@ -405,12 +415,12 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static Color3 Lerp(Color3 start, Color3 end, float amount) public static Color3 Lerp( Color3 start, Color3 end, float amount )
{ {
return new Color3( return new Color3(
start.R + amount * (end.R - start.R), start.R + amount * ( end.R - start.R ),
start.G + amount * (end.G - start.G), start.G + amount * ( end.G - start.G ),
start.B + amount * (end.B - start.B)); start.B + amount * ( end.B - start.B ) );
} }
/// <summary> /// <summary>
@ -420,14 +430,14 @@ namespace math
/// <param name="end">End color.</param> /// <param name="end">End color.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <param name="result">When the method completes, contains the cubic interpolation of the two colors.</param> /// <param name="result">When the method completes, contains the cubic interpolation of the two colors.</param>
public static void SmoothStep(ref Color3 start, ref Color3 end, float amount, out Color3 result) public static void SmoothStep( ref Color3 start, ref Color3 end, float amount, out Color3 result )
{ {
amount = (amount > 1.0f) ? 1.0f : ((amount < 0.0f) ? 0.0f : amount); amount = ( amount > 1.0f ) ? 1.0f : ( ( amount < 0.0f ) ? 0.0f : amount );
amount = (amount * amount) * (3.0f - (2.0f * amount)); amount = ( amount * amount ) * ( 3.0f - ( 2.0f * amount ) );
result.R = start.R + ((end.R - start.R) * amount); result.R = start.R + ( ( end.R - start.R ) * amount );
result.G = start.G + ((end.G - start.G) * amount); result.G = start.G + ( ( end.G - start.G ) * amount );
result.B = start.B + ((end.B - start.B) * amount); result.B = start.B + ( ( end.B - start.B ) * amount );
} }
/// <summary> /// <summary>
@ -437,15 +447,15 @@ namespace math
/// <param name="end">End color.</param> /// <param name="end">End color.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <returns>The cubic interpolation of the two colors.</returns> /// <returns>The cubic interpolation of the two colors.</returns>
public static Color3 SmoothStep(Color3 start, Color3 end, float amount) public static Color3 SmoothStep( Color3 start, Color3 end, float amount )
{ {
amount = (amount > 1.0f) ? 1.0f : ((amount < 0.0f) ? 0.0f : amount); amount = ( amount > 1.0f ) ? 1.0f : ( ( amount < 0.0f ) ? 0.0f : amount );
amount = (amount * amount) * (3.0f - (2.0f * amount)); amount = ( amount * amount ) * ( 3.0f - ( 2.0f * amount ) );
return new Color3( return new Color3(
start.R + ((end.R - start.R) * amount), start.R + ( ( end.R - start.R ) * amount ),
start.G + ((end.G - start.G) * amount), start.G + ( ( end.G - start.G ) * amount ),
start.B + ((end.B - start.B) * amount)); start.B + ( ( end.B - start.B ) * amount ) );
} }
/// <summary> /// <summary>
@ -454,11 +464,11 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <param name="result">When the method completes, contains an new color composed of the largest components of the source colorss.</param> /// <param name="result">When the method completes, contains an new color composed of the largest components of the source colorss.</param>
public static void Max(ref Color3 left, ref Color3 right, out Color3 result) public static void Max( ref Color3 left, ref Color3 right, out Color3 result )
{ {
result.R = (left.R > right.R) ? left.R : right.R; result.R = ( left.R > right.R ) ? left.R : right.R;
result.G = (left.G > right.G) ? left.G : right.G; result.G = ( left.G > right.G ) ? left.G : right.G;
result.B = (left.B > right.B) ? left.B : right.B; result.B = ( left.B > right.B ) ? left.B : right.B;
} }
/// <summary> /// <summary>
@ -467,10 +477,10 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <returns>A color containing the largest components of the source colors.</returns> /// <returns>A color containing the largest components of the source colors.</returns>
public static Color3 Max(Color3 left, Color3 right) public static Color3 Max( Color3 left, Color3 right )
{ {
Color3 result; Color3 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -480,11 +490,11 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <param name="result">When the method completes, contains an new color composed of the smallest components of the source colors.</param> /// <param name="result">When the method completes, contains an new color composed of the smallest components of the source colors.</param>
public static void Min(ref Color3 left, ref Color3 right, out Color3 result) public static void Min( ref Color3 left, ref Color3 right, out Color3 result )
{ {
result.R = (left.R < right.R) ? left.R : right.R; result.R = ( left.R < right.R ) ? left.R : right.R;
result.G = (left.G < right.G) ? left.G : right.G; result.G = ( left.G < right.G ) ? left.G : right.G;
result.B = (left.B < right.B) ? left.B : right.B; result.B = ( left.B < right.B ) ? left.B : right.B;
} }
/// <summary> /// <summary>
@ -493,10 +503,10 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <returns>A color containing the smallest components of the source colors.</returns> /// <returns>A color containing the smallest components of the source colors.</returns>
public static Color3 Min(Color3 left, Color3 right) public static Color3 Min( Color3 left, Color3 right )
{ {
Color3 result; Color3 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -506,11 +516,11 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param> /// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param> /// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <param name="result">When the method completes, contains the adjusted color.</param> /// <param name="result">When the method completes, contains the adjusted color.</param>
public static void AdjustContrast(ref Color3 value, float contrast, out Color3 result) public static void AdjustContrast( ref Color3 value, float contrast, out Color3 result )
{ {
result.R = 0.5f + contrast * (value.R - 0.5f); result.R = 0.5f + contrast * ( value.R - 0.5f );
result.G = 0.5f + contrast * (value.G - 0.5f); result.G = 0.5f + contrast * ( value.G - 0.5f );
result.B = 0.5f + contrast * (value.B - 0.5f); result.B = 0.5f + contrast * ( value.B - 0.5f );
} }
/// <summary> /// <summary>
@ -519,12 +529,12 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param> /// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param> /// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <returns>The adjusted color.</returns> /// <returns>The adjusted color.</returns>
public static Color3 AdjustContrast(Color3 value, float contrast) public static Color3 AdjustContrast( Color3 value, float contrast )
{ {
return new Color3( return new Color3(
0.5f + contrast * (value.R - 0.5f), 0.5f + contrast * ( value.R - 0.5f ),
0.5f + contrast * (value.G - 0.5f), 0.5f + contrast * ( value.G - 0.5f ),
0.5f + contrast * (value.B - 0.5f)); 0.5f + contrast * ( value.B - 0.5f ) );
} }
/// <summary> /// <summary>
@ -533,13 +543,13 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param> /// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param> /// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <param name="result">When the method completes, contains the adjusted color.</param> /// <param name="result">When the method completes, contains the adjusted color.</param>
public static void AdjustSaturation(ref Color3 value, float saturation, out Color3 result) public static void AdjustSaturation( ref Color3 value, float saturation, out Color3 result )
{ {
float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f; float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f;
result.R = grey + saturation * (value.R - grey); result.R = grey + saturation * ( value.R - grey );
result.G = grey + saturation * (value.G - grey); result.G = grey + saturation * ( value.G - grey );
result.B = grey + saturation * (value.B - grey); result.B = grey + saturation * ( value.B - grey );
} }
/// <summary> /// <summary>
@ -548,14 +558,14 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param> /// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param> /// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <returns>The adjusted color.</returns> /// <returns>The adjusted color.</returns>
public static Color3 AdjustSaturation(Color3 value, float saturation) public static Color3 AdjustSaturation( Color3 value, float saturation )
{ {
float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f; float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f;
return new Color3( return new Color3(
grey + saturation * (value.R - grey), grey + saturation * ( value.R - grey ),
grey + saturation * (value.G - grey), grey + saturation * ( value.G - grey ),
grey + saturation * (value.B - grey)); grey + saturation * ( value.B - grey ) );
} }
/// <summary> /// <summary>
@ -564,7 +574,7 @@ namespace math
/// <returns>A color3 in sRGB space.</returns> /// <returns>A color3 in sRGB space.</returns>
public Color3 ToSRgb() public Color3 ToSRgb()
{ {
return new Color3(MathUtil.LinearToSRgb(R), MathUtil.LinearToSRgb(G), MathUtil.LinearToSRgb(B)); return new Color3( MathUtil.LinearToSRgb( R ), MathUtil.LinearToSRgb( G ), MathUtil.LinearToSRgb( B ) );
} }
/// <summary> /// <summary>
@ -573,7 +583,7 @@ namespace math
/// <returns>Color3.</returns> /// <returns>Color3.</returns>
public Color3 ToLinear() public Color3 ToLinear()
{ {
return new Color3(MathUtil.SRgbToLinear(R), MathUtil.SRgbToLinear(G), MathUtil.SRgbToLinear(B)); return new Color3( MathUtil.SRgbToLinear( R ), MathUtil.SRgbToLinear( G ), MathUtil.SRgbToLinear( B ) );
} }
/// <summary> /// <summary>
@ -582,9 +592,9 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <returns>The sum of the two colors.</returns> /// <returns>The sum of the two colors.</returns>
public static Color3 operator +(Color3 left, Color3 right) public static Color3 operator +( Color3 left, Color3 right )
{ {
return new Color3(left.R + right.R, left.G + right.G, left.B + right.B); return new Color3( left.R + right.R, left.G + right.G, left.B + right.B );
} }
/// <summary> /// <summary>
@ -592,7 +602,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to assert (unchange).</param> /// <param name="value">The color to assert (unchange).</param>
/// <returns>The asserted (unchanged) color.</returns> /// <returns>The asserted (unchanged) color.</returns>
public static Color3 operator +(Color3 value) public static Color3 operator +( Color3 value )
{ {
return value; return value;
} }
@ -603,9 +613,9 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param> /// <param name="right">The second color to subtract.</param>
/// <returns>The difference of the two colors.</returns> /// <returns>The difference of the two colors.</returns>
public static Color3 operator -(Color3 left, Color3 right) public static Color3 operator -( Color3 left, Color3 right )
{ {
return new Color3(left.R - right.R, left.G - right.G, left.B - right.B); return new Color3( left.R - right.R, left.G - right.G, left.B - right.B );
} }
/// <summary> /// <summary>
@ -613,9 +623,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <returns>A negated color.</returns> /// <returns>A negated color.</returns>
public static Color3 operator -(Color3 value) public static Color3 operator -( Color3 value )
{ {
return new Color3(-value.R, -value.G, -value.B); return new Color3( -value.R, -value.G, -value.B );
} }
/// <summary> /// <summary>
@ -624,9 +634,9 @@ namespace math
/// <param name="scale">The factor by which to scale the color.</param> /// <param name="scale">The factor by which to scale the color.</param>
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color3 operator *(float scale, Color3 value) public static Color3 operator *( float scale, Color3 value )
{ {
return new Color3(value.R * scale, value.G * scale, value.B * scale); return new Color3( value.R * scale, value.G * scale, value.B * scale );
} }
/// <summary> /// <summary>
@ -635,9 +645,9 @@ namespace math
/// <param name="value">The factor by which to scale the color.</param> /// <param name="value">The factor by which to scale the color.</param>
/// <param name="scale">The color to scale.</param> /// <param name="scale">The color to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color3 operator *(Color3 value, float scale) public static Color3 operator *( Color3 value, float scale )
{ {
return new Color3(value.R * scale, value.G * scale, value.B * scale); return new Color3( value.R * scale, value.G * scale, value.B * scale );
} }
/// <summary> /// <summary>
@ -646,9 +656,9 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <returns>The modulated color.</returns> /// <returns>The modulated color.</returns>
public static Color3 operator *(Color3 left, Color3 right) public static Color3 operator *( Color3 left, Color3 right )
{ {
return new Color3(left.R * right.R, left.G * right.G, left.B * right.B); return new Color3( left.R * right.R, left.G * right.G, left.B * right.B );
} }
/// <summary> /// <summary>
@ -657,9 +667,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Color3 left, Color3 right) public static bool operator ==( Color3 left, Color3 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -668,9 +678,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Color3 left, Color3 right) public static bool operator !=( Color3 left, Color3 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -678,9 +688,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color4(Color3 value) public static explicit operator Color4( Color3 value )
{ {
return new Color4(value.R, value.G, value.B, 1.0f); return new Color4( value.R, value.G, value.B, 1.0f );
} }
/// <summary> /// <summary>
@ -688,9 +698,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(Color3 value) public static explicit operator Vec3( Color3 value )
{ {
return new Vec3(value.R, value.G, value.B); return new Vec3( value.R, value.G, value.B );
} }
/// <summary> /// <summary>
@ -698,9 +708,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color3(Vec3 value) public static explicit operator Color3( Vec3 value )
{ {
return new Color3(value.X, value.Y, value.Z); return new Color3( value.X, value.Y, value.Z );
} }
/// <summary> /// <summary>
@ -708,9 +718,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color3(int value) public static explicit operator Color3( int value )
{ {
return new Color3(value); return new Color3( value );
} }
/// <summary> /// <summary>
@ -721,7 +731,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return ToString(CultureInfo.CurrentCulture); return ToString( CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -730,7 +740,7 @@ namespace math
/// <returns>An equivalent <see cref="Color4"/> with an opaque alpha.</returns> /// <returns>An equivalent <see cref="Color4"/> with an opaque alpha.</returns>
public Color4 ToColor4() public Color4 ToColor4()
{ {
return new Color4(R, G, B, 1.0f); return new Color4( R, G, B, 1.0f );
} }
/// <summary> /// <summary>
@ -740,9 +750,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
return ToString(format, CultureInfo.CurrentCulture); return ToString( format, CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -752,9 +762,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, ToStringFormat, R, G, B); return string.Format( formatProvider, ToStringFormat, R, G, B );
} }
/// <summary> /// <summary>
@ -765,15 +775,15 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, ToStringFormat, return string.Format( formatProvider, ToStringFormat,
R.ToString(format, formatProvider), R.ToString( format, formatProvider ),
G.ToString(format, formatProvider), G.ToString( format, formatProvider ),
B.ToString(format, formatProvider)); B.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -794,7 +804,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="Color3"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="Color3"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Color3 other) public bool Equals( Color3 other )
{ {
return R == other.R && G == other.G && B == other.B; return R == other.R && G == other.G && B == other.B;
} }
@ -806,15 +816,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Color3)value); return Equals( (Color3)value );
} }
#if SlimDX1xInterop #if SlimDX1xInterop

View File

@ -36,9 +36,9 @@ namespace math
/// <summary> /// <summary>
/// Represents a color in the form of rgba. /// Represents a color in the form of rgba.
/// </summary> /// </summary>
[DataContract( Name = "Color4")] [DataContract( Name = "Color4" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Color4 : IEquatable<Color4>, IFormattable public struct Color4 : IEquatable<Color4>, IFormattable
{ {
private const string ToStringFormat = "A:{0} R:{1} G:{2} B:{3}"; private const string ToStringFormat = "A:{0} R:{1} G:{2} B:{3}";
@ -46,12 +46,12 @@ namespace math
/// <summary> /// <summary>
/// The Black color (0, 0, 0, 1). /// The Black color (0, 0, 0, 1).
/// </summary> /// </summary>
public static readonly Color4 Black = new Color4(0.0f, 0.0f, 0.0f, 1.0f); public static readonly Color4 Black = new Color4( 0.0f, 0.0f, 0.0f, 1.0f );
/// <summary> /// <summary>
/// The White color (1, 1, 1, 1). /// The White color (1, 1, 1, 1).
/// </summary> /// </summary>
public static readonly Color4 White = new Color4(1.0f, 1.0f, 1.0f, 1.0f); public static readonly Color4 White = new Color4( 1.0f, 1.0f, 1.0f, 1.0f );
/// <summary> /// <summary>
/// The red component of the color. /// The red component of the color.
@ -81,7 +81,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="value">The value that will be assigned to all components.</param> /// <param name="value">The value that will be assigned to all components.</param>
public Color4(float value) public Color4( float value )
{ {
A = R = G = B = value; A = R = G = B = value;
} }
@ -93,7 +93,7 @@ namespace math
/// <param name="green">The green component of the color.</param> /// <param name="green">The green component of the color.</param>
/// <param name="blue">The blue component of the color.</param> /// <param name="blue">The blue component of the color.</param>
/// <param name="alpha">The alpha component of the color.</param> /// <param name="alpha">The alpha component of the color.</param>
public Color4(float red, float green, float blue, float alpha) public Color4( float red, float green, float blue, float alpha )
{ {
R = red; R = red;
G = green; G = green;
@ -105,7 +105,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="value">The red, green, blue, and alpha components of the color.</param> /// <param name="value">The red, green, blue, and alpha components of the color.</param>
public Color4(Vec4 value) public Color4( Vec4 value )
{ {
R = value.X; R = value.X;
G = value.Y; G = value.Y;
@ -118,7 +118,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The red, green, and blue components of the color.</param> /// <param name="value">The red, green, and blue components of the color.</param>
/// <param name="alpha">The alpha component of the color.</param> /// <param name="alpha">The alpha component of the color.</param>
public Color4(Vec3 value, float alpha) public Color4( Vec3 value, float alpha )
{ {
R = value.X; R = value.X;
G = value.Y; G = value.Y;
@ -130,24 +130,24 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="rgba">A packed integer containing all four color components in RGBA order.</param> /// <param name="rgba">A packed integer containing all four color components in RGBA order.</param>
public Color4(uint rgba) public Color4( uint rgba )
{ {
A = ((rgba >> 24) & 255) / 255.0f; A = ( ( rgba >> 24 ) & 255 ) / 255.0f;
B = ((rgba >> 16) & 255) / 255.0f; B = ( ( rgba >> 16 ) & 255 ) / 255.0f;
G = ((rgba >> 8) & 255) / 255.0f; G = ( ( rgba >> 8 ) & 255 ) / 255.0f;
R = (rgba & 255) / 255.0f; R = ( rgba & 255 ) / 255.0f;
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="rgba">A packed integer containing all four color components in RGBA order.</param> /// <param name="rgba">A packed integer containing all four color components in RGBA order.</param>
public Color4(int rgba) public Color4( int rgba )
{ {
A = ((rgba >> 24) & 255) / 255.0f; A = ( ( rgba >> 24 ) & 255 ) / 255.0f;
B = ((rgba >> 16) & 255) / 255.0f; B = ( ( rgba >> 16 ) & 255 ) / 255.0f;
G = ((rgba >> 8) & 255) / 255.0f; G = ( ( rgba >> 8 ) & 255 ) / 255.0f;
R = (rgba & 255) / 255.0f; R = ( rgba & 255 ) / 255.0f;
} }
/// <summary> /// <summary>
@ -156,12 +156,12 @@ namespace math
/// <param name="values">The values to assign to the red, green, blue, and alpha components of the color. This must be an array with four elements.</param> /// <param name="values">The values to assign to the red, green, blue, and alpha components of the color. This must be an array with four elements.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception>
public Color4(float[] values) public Color4( float[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException(nameof(values)); throw new ArgumentNullException( nameof( values ) );
if (values.Length != 4) if( values.Length != 4 )
throw new ArgumentOutOfRangeException(nameof(values), "There must be four and only four input values for Color4."); throw new ArgumentOutOfRangeException( nameof( values ), "There must be four and only four input values for Color4." );
R = values[0]; R = values[0];
G = values[1]; G = values[1];
@ -173,7 +173,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="color"><see cref="Color3"/> used to initialize the color.</param> /// <param name="color"><see cref="Color3"/> used to initialize the color.</param>
public Color4(Color3 color) public Color4( Color3 color )
{ {
R = color.R; R = color.R;
G = color.G; G = color.G;
@ -185,7 +185,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="color"><see cref="Color"/> used to initialize the color.</param> /// <param name="color"><see cref="Color"/> used to initialize the color.</param>
public Color4(Color color) public Color4( Color color )
{ {
R = color.R / 255.0f; R = color.R / 255.0f;
G = color.G / 255.0f; G = color.G / 255.0f;
@ -197,7 +197,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct. /// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary> /// </summary>
/// <param name="color"><see cref="Color"/> used to initialize the color.</param> /// <param name="color"><see cref="Color"/> used to initialize the color.</param>
public Color4(ColorBGRA color) public Color4( ColorBGRA color )
{ {
R = color.R / 255.0f; R = color.R / 255.0f;
G = color.G / 255.0f; G = color.G / 255.0f;
@ -210,7 +210,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="color"><see cref="Color3"/> used to initialize the color.</param> /// <param name="color"><see cref="Color3"/> used to initialize the color.</param>
/// <param name="alpha">The alpha component of the color.</param> /// <param name="alpha">The alpha component of the color.</param>
public Color4(Color3 color, float alpha) public Color4( Color3 color, float alpha )
{ {
R = color.R; R = color.R;
G = color.G; G = color.G;
@ -229,26 +229,39 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: return R; case 0:
case 1: return G; return R;
case 2: return B; case 1:
case 3: return A; return G;
case 2:
return B;
case 3:
return A;
} }
throw new ArgumentOutOfRangeException(nameof(index), "Indices for Color4 run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( nameof( index ), "Indices for Color4 run from 0 to 3, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: R = value; break; case 0:
case 1: G = value; break; R = value;
case 2: B = value; break; break;
case 3: A = value; break; case 1:
default: throw new ArgumentOutOfRangeException(nameof(index), "Indices for Color4 run from 0 to 3, inclusive."); G = value;
break;
case 2:
B = value;
break;
case 3:
A = value;
break;
default:
throw new ArgumentOutOfRangeException( nameof( index ), "Indices for Color4 run from 0 to 3, inclusive." );
} }
} }
} }
@ -259,10 +272,10 @@ namespace math
/// <returns>A packed integer containing all four color components.</returns> /// <returns>A packed integer containing all four color components.</returns>
public int ToBgra() public int ToBgra()
{ {
uint a = (uint)(A * 255.0f) & 255; uint a = (uint)( A * 255.0f ) & 255;
uint r = (uint)(R * 255.0f) & 255; uint r = (uint)( R * 255.0f ) & 255;
uint g = (uint)(G * 255.0f) & 255; uint g = (uint)( G * 255.0f ) & 255;
uint b = (uint)(B * 255.0f) & 255; uint b = (uint)( B * 255.0f ) & 255;
uint value = b; uint value = b;
value |= g << 8; value |= g << 8;
@ -275,12 +288,12 @@ namespace math
/// <summary> /// <summary>
/// Converts the color into a packed integer. /// Converts the color into a packed integer.
/// </summary> /// </summary>
public void ToBgra(out byte r, out byte g, out byte b, out byte a) public void ToBgra( out byte r, out byte g, out byte b, out byte a )
{ {
a = (byte)(A * 255.0f); a = (byte)( A * 255.0f );
r = (byte)(R * 255.0f); r = (byte)( R * 255.0f );
g = (byte)(G * 255.0f); g = (byte)( G * 255.0f );
b = (byte)(B * 255.0f); b = (byte)( B * 255.0f );
} }
/// <summary> /// <summary>
@ -289,10 +302,10 @@ namespace math
/// <returns>A packed integer containing all four color components.</returns> /// <returns>A packed integer containing all four color components.</returns>
public int ToRgba() public int ToRgba()
{ {
uint a = (uint)(A * 255.0f) & 255; uint a = (uint)( A * 255.0f ) & 255;
uint r = (uint)(R * 255.0f) & 255; uint r = (uint)( R * 255.0f ) & 255;
uint g = (uint)(G * 255.0f) & 255; uint g = (uint)( G * 255.0f ) & 255;
uint b = (uint)(B * 255.0f) & 255; uint b = (uint)( B * 255.0f ) & 255;
uint value = r; uint value = r;
value |= g << 8; value |= g << 8;
@ -308,7 +321,7 @@ namespace math
/// <returns>A three component vector containing the red, green, and blue components of the color.</returns> /// <returns>A three component vector containing the red, green, and blue components of the color.</returns>
public Vec3 ToVector3() public Vec3 ToVector3()
{ {
return new Vec3(R, G, B); return new Vec3( R, G, B );
} }
/// <summary> /// <summary>
@ -317,7 +330,7 @@ namespace math
/// <returns>A four component vector containing all four color components.</returns> /// <returns>A four component vector containing all four color components.</returns>
public Vec4 ToVector4() public Vec4 ToVector4()
{ {
return new Vec4(R, G, B, A); return new Vec4( R, G, B, A );
} }
/// <summary> /// <summary>
@ -335,7 +348,7 @@ namespace math
/// <returns>A color3 in sRGB space.</returns> /// <returns>A color3 in sRGB space.</returns>
public Color4 ToSRgb() public Color4 ToSRgb()
{ {
return new Color4(MathUtil.LinearToSRgb(R), MathUtil.LinearToSRgb(G), MathUtil.LinearToSRgb(B), A); return new Color4( MathUtil.LinearToSRgb( R ), MathUtil.LinearToSRgb( G ), MathUtil.LinearToSRgb( B ), A );
} }
/// <summary> /// <summary>
@ -344,7 +357,7 @@ namespace math
/// <returns>A color4 in linear space.</returns> /// <returns>A color4 in linear space.</returns>
public Color4 ToLinear() public Color4 ToLinear()
{ {
return new Color4(MathUtil.SRgbToLinear(R), MathUtil.SRgbToLinear(G), MathUtil.SRgbToLinear(B), A); return new Color4( MathUtil.SRgbToLinear( R ), MathUtil.SRgbToLinear( G ), MathUtil.SRgbToLinear( B ), A );
} }
/// <summary> /// <summary>
@ -353,7 +366,7 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <param name="result">When the method completes, completes the sum of the two colors.</param> /// <param name="result">When the method completes, completes the sum of the two colors.</param>
public static void Add(ref Color4 left, ref Color4 right, out Color4 result) public static void Add( ref Color4 left, ref Color4 right, out Color4 result )
{ {
result.A = left.A + right.A; result.A = left.A + right.A;
result.R = left.R + right.R; result.R = left.R + right.R;
@ -367,9 +380,9 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <returns>The sum of the two colors.</returns> /// <returns>The sum of the two colors.</returns>
public static Color4 Add(Color4 left, Color4 right) public static Color4 Add( Color4 left, Color4 right )
{ {
return new Color4(left.R + right.R, left.G + right.G, left.B + right.B, left.A + right.A); return new Color4( left.R + right.R, left.G + right.G, left.B + right.B, left.A + right.A );
} }
/// <summary> /// <summary>
@ -378,7 +391,7 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param> /// <param name="right">The second color to subtract.</param>
/// <param name="result">WHen the method completes, contains the difference of the two colors.</param> /// <param name="result">WHen the method completes, contains the difference of the two colors.</param>
public static void Subtract(ref Color4 left, ref Color4 right, out Color4 result) public static void Subtract( ref Color4 left, ref Color4 right, out Color4 result )
{ {
result.A = left.A - right.A; result.A = left.A - right.A;
result.R = left.R - right.R; result.R = left.R - right.R;
@ -392,9 +405,9 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract</param> /// <param name="right">The second color to subtract</param>
/// <returns>The difference of the two colors.</returns> /// <returns>The difference of the two colors.</returns>
public static Color4 Subtract(Color4 left, Color4 right) public static Color4 Subtract( Color4 left, Color4 right )
{ {
return new Color4(left.R - right.R, left.G - right.G, left.B - right.B, left.A - right.A); return new Color4( left.R - right.R, left.G - right.G, left.B - right.B, left.A - right.A );
} }
/// <summary> /// <summary>
@ -403,7 +416,7 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <param name="result">When the method completes, contains the modulated color.</param> /// <param name="result">When the method completes, contains the modulated color.</param>
public static void Modulate(ref Color4 left, ref Color4 right, out Color4 result) public static void Modulate( ref Color4 left, ref Color4 right, out Color4 result )
{ {
result.A = left.A * right.A; result.A = left.A * right.A;
result.R = left.R * right.R; result.R = left.R * right.R;
@ -417,9 +430,9 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <returns>The modulated color.</returns> /// <returns>The modulated color.</returns>
public static Color4 Modulate(Color4 left, Color4 right) public static Color4 Modulate( Color4 left, Color4 right )
{ {
return new Color4(left.R * right.R, left.G * right.G, left.B * right.B, left.A * right.A); return new Color4( left.R * right.R, left.G * right.G, left.B * right.B, left.A * right.A );
} }
/// <summary> /// <summary>
@ -428,7 +441,7 @@ namespace math
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param> /// <param name="scale">The amount by which to scale.</param>
/// <param name="result">When the method completes, contains the scaled color.</param> /// <param name="result">When the method completes, contains the scaled color.</param>
public static void Scale(ref Color4 value, float scale, out Color4 result) public static void Scale( ref Color4 value, float scale, out Color4 result )
{ {
result.A = value.A * scale; result.A = value.A * scale;
result.R = value.R * scale; result.R = value.R * scale;
@ -442,9 +455,9 @@ namespace math
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param> /// <param name="scale">The amount by which to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color4 Scale(Color4 value, float scale) public static Color4 Scale( Color4 value, float scale )
{ {
return new Color4(value.R * scale, value.G * scale, value.B * scale, value.A * scale); return new Color4( value.R * scale, value.G * scale, value.B * scale, value.A * scale );
} }
/// <summary> /// <summary>
@ -452,7 +465,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <param name="result">When the method completes, contains the negated color.</param> /// <param name="result">When the method completes, contains the negated color.</param>
public static void Negate(ref Color4 value, out Color4 result) public static void Negate( ref Color4 value, out Color4 result )
{ {
result.A = 1.0f - value.A; result.A = 1.0f - value.A;
result.R = 1.0f - value.R; result.R = 1.0f - value.R;
@ -465,9 +478,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <returns>The negated color.</returns> /// <returns>The negated color.</returns>
public static Color4 Negate(Color4 value) public static Color4 Negate( Color4 value )
{ {
return new Color4(1.0f - value.R, 1.0f - value.G, 1.0f - value.B, 1.0f - value.A); return new Color4( 1.0f - value.R, 1.0f - value.G, 1.0f - value.B, 1.0f - value.A );
} }
/// <summary> /// <summary>
@ -477,25 +490,25 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <param name="result">When the method completes, contains the clamped value.</param> /// <param name="result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref Color4 value, ref Color4 min, ref Color4 max, out Color4 result) public static void Clamp( ref Color4 value, ref Color4 min, ref Color4 max, out Color4 result )
{ {
float alpha = value.A; float alpha = value.A;
alpha = (alpha > max.A) ? max.A : alpha; alpha = ( alpha > max.A ) ? max.A : alpha;
alpha = (alpha < min.A) ? min.A : alpha; alpha = ( alpha < min.A ) ? min.A : alpha;
float red = value.R; float red = value.R;
red = (red > max.R) ? max.R : red; red = ( red > max.R ) ? max.R : red;
red = (red < min.R) ? min.R : red; red = ( red < min.R ) ? min.R : red;
float green = value.G; float green = value.G;
green = (green > max.G) ? max.G : green; green = ( green > max.G ) ? max.G : green;
green = (green < min.G) ? min.G : green; green = ( green < min.G ) ? min.G : green;
float blue = value.B; float blue = value.B;
blue = (blue > max.B) ? max.B : blue; blue = ( blue > max.B ) ? max.B : blue;
blue = (blue < min.B) ? min.B : blue; blue = ( blue < min.B ) ? min.B : blue;
result = new Color4(red, green, blue, alpha); result = new Color4( red, green, blue, alpha );
} }
/// <summary> /// <summary>
@ -505,10 +518,10 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static Color4 Clamp(Color4 value, Color4 min, Color4 max) public static Color4 Clamp( Color4 value, Color4 min, Color4 max )
{ {
Color4 result; Color4 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -522,12 +535,12 @@ namespace math
/// <remarks> /// <remarks>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static void Lerp(ref Color4 start, ref Color4 end, float amount, out Color4 result) public static void Lerp( ref Color4 start, ref Color4 end, float amount, out Color4 result )
{ {
result.R = MathUtil.Lerp(start.R, end.R, amount); result.R = MathUtil.Lerp( start.R, end.R, amount );
result.G = MathUtil.Lerp(start.G, end.G, amount); result.G = MathUtil.Lerp( start.G, end.G, amount );
result.B = MathUtil.Lerp(start.B, end.B, amount); result.B = MathUtil.Lerp( start.B, end.B, amount );
result.A = MathUtil.Lerp(start.A, end.A, amount); result.A = MathUtil.Lerp( start.A, end.A, amount );
} }
/// <summary> /// <summary>
@ -540,10 +553,10 @@ namespace math
/// <remarks> /// <remarks>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static Color4 Lerp(Color4 start, Color4 end, float amount) public static Color4 Lerp( Color4 start, Color4 end, float amount )
{ {
Color4 result; Color4 result;
Lerp(ref start, ref end, amount, out result); Lerp( ref start, ref end, amount, out result );
return result; return result;
} }
@ -554,10 +567,10 @@ namespace math
/// <param name="end">End color.</param> /// <param name="end">End color.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <param name="result">When the method completes, contains the cubic interpolation of the two colors.</param> /// <param name="result">When the method completes, contains the cubic interpolation of the two colors.</param>
public static void SmoothStep(ref Color4 start, ref Color4 end, float amount, out Color4 result) public static void SmoothStep( ref Color4 start, ref Color4 end, float amount, out Color4 result )
{ {
amount = MathUtil.SmoothStep(amount); amount = MathUtil.SmoothStep( amount );
Lerp(ref start, ref end, amount, out result); Lerp( ref start, ref end, amount, out result );
} }
/// <summary> /// <summary>
@ -567,10 +580,10 @@ namespace math
/// <param name="end">End color.</param> /// <param name="end">End color.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <returns>The cubic interpolation of the two colors.</returns> /// <returns>The cubic interpolation of the two colors.</returns>
public static Color4 SmoothStep(Color4 start, Color4 end, float amount) public static Color4 SmoothStep( Color4 start, Color4 end, float amount )
{ {
Color4 result; Color4 result;
SmoothStep(ref start, ref end, amount, out result); SmoothStep( ref start, ref end, amount, out result );
return result; return result;
} }
@ -580,12 +593,12 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <param name="result">When the method completes, contains an new color composed of the largest components of the source colors.</param> /// <param name="result">When the method completes, contains an new color composed of the largest components of the source colors.</param>
public static void Max(ref Color4 left, ref Color4 right, out Color4 result) public static void Max( ref Color4 left, ref Color4 right, out Color4 result )
{ {
result.A = (left.A > right.A) ? left.A : right.A; result.A = ( left.A > right.A ) ? left.A : right.A;
result.R = (left.R > right.R) ? left.R : right.R; result.R = ( left.R > right.R ) ? left.R : right.R;
result.G = (left.G > right.G) ? left.G : right.G; result.G = ( left.G > right.G ) ? left.G : right.G;
result.B = (left.B > right.B) ? left.B : right.B; result.B = ( left.B > right.B ) ? left.B : right.B;
} }
/// <summary> /// <summary>
@ -594,10 +607,10 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <returns>A color containing the largest components of the source colors.</returns> /// <returns>A color containing the largest components of the source colors.</returns>
public static Color4 Max(Color4 left, Color4 right) public static Color4 Max( Color4 left, Color4 right )
{ {
Color4 result; Color4 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -607,12 +620,12 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <param name="result">When the method completes, contains an new color composed of the smallest components of the source colors.</param> /// <param name="result">When the method completes, contains an new color composed of the smallest components of the source colors.</param>
public static void Min(ref Color4 left, ref Color4 right, out Color4 result) public static void Min( ref Color4 left, ref Color4 right, out Color4 result )
{ {
result.A = (left.A < right.A) ? left.A : right.A; result.A = ( left.A < right.A ) ? left.A : right.A;
result.R = (left.R < right.R) ? left.R : right.R; result.R = ( left.R < right.R ) ? left.R : right.R;
result.G = (left.G < right.G) ? left.G : right.G; result.G = ( left.G < right.G ) ? left.G : right.G;
result.B = (left.B < right.B) ? left.B : right.B; result.B = ( left.B < right.B ) ? left.B : right.B;
} }
/// <summary> /// <summary>
@ -621,10 +634,10 @@ namespace math
/// <param name="left">The first source color.</param> /// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param> /// <param name="right">The second source color.</param>
/// <returns>A color containing the smallest components of the source colors.</returns> /// <returns>A color containing the smallest components of the source colors.</returns>
public static Color4 Min(Color4 left, Color4 right) public static Color4 Min( Color4 left, Color4 right )
{ {
Color4 result; Color4 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -634,12 +647,12 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param> /// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param> /// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <param name="result">When the method completes, contains the adjusted color.</param> /// <param name="result">When the method completes, contains the adjusted color.</param>
public static void AdjustContrast(ref Color4 value, float contrast, out Color4 result) public static void AdjustContrast( ref Color4 value, float contrast, out Color4 result )
{ {
result.A = value.A; result.A = value.A;
result.R = 0.5f + contrast * (value.R - 0.5f); result.R = 0.5f + contrast * ( value.R - 0.5f );
result.G = 0.5f + contrast * (value.G - 0.5f); result.G = 0.5f + contrast * ( value.G - 0.5f );
result.B = 0.5f + contrast * (value.B - 0.5f); result.B = 0.5f + contrast * ( value.B - 0.5f );
} }
/// <summary> /// <summary>
@ -648,13 +661,13 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param> /// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param> /// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <returns>The adjusted color.</returns> /// <returns>The adjusted color.</returns>
public static Color4 AdjustContrast(Color4 value, float contrast) public static Color4 AdjustContrast( Color4 value, float contrast )
{ {
return new Color4( return new Color4(
0.5f + contrast * (value.R - 0.5f), 0.5f + contrast * ( value.R - 0.5f ),
0.5f + contrast * (value.G - 0.5f), 0.5f + contrast * ( value.G - 0.5f ),
0.5f + contrast * (value.B - 0.5f), 0.5f + contrast * ( value.B - 0.5f ),
value.A); value.A );
} }
/// <summary> /// <summary>
@ -663,14 +676,14 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param> /// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param> /// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <param name="result">When the method completes, contains the adjusted color.</param> /// <param name="result">When the method completes, contains the adjusted color.</param>
public static void AdjustSaturation(ref Color4 value, float saturation, out Color4 result) public static void AdjustSaturation( ref Color4 value, float saturation, out Color4 result )
{ {
float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f; float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f;
result.A = value.A; result.A = value.A;
result.R = grey + saturation * (value.R - grey); result.R = grey + saturation * ( value.R - grey );
result.G = grey + saturation * (value.G - grey); result.G = grey + saturation * ( value.G - grey );
result.B = grey + saturation * (value.B - grey); result.B = grey + saturation * ( value.B - grey );
} }
/// <summary> /// <summary>
@ -679,15 +692,15 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param> /// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param> /// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <returns>The adjusted color.</returns> /// <returns>The adjusted color.</returns>
public static Color4 AdjustSaturation(Color4 value, float saturation) public static Color4 AdjustSaturation( Color4 value, float saturation )
{ {
float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f; float grey = value.R * 0.2125f + value.G * 0.7154f + value.B * 0.0721f;
return new Color4( return new Color4(
grey + saturation * (value.R - grey), grey + saturation * ( value.R - grey ),
grey + saturation * (value.G - grey), grey + saturation * ( value.G - grey ),
grey + saturation * (value.B - grey), grey + saturation * ( value.B - grey ),
value.A); value.A );
} }
/// <summary> /// <summary>
@ -695,9 +708,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to premultiply.</param> /// <param name="value">The color to premultiply.</param>
/// <returns>A color with premultiplied alpha.</returns> /// <returns>A color with premultiplied alpha.</returns>
public static Color4 PremultiplyAlpha(Color4 value) public static Color4 PremultiplyAlpha( Color4 value )
{ {
return new Color4(value.R * value.A, value.G * value.A, value.B * value.A, value.A); return new Color4( value.R * value.A, value.G * value.A, value.B * value.A, value.A );
} }
/// <summary> /// <summary>
@ -706,9 +719,9 @@ namespace math
/// <param name="left">The first color to add.</param> /// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param> /// <param name="right">The second color to add.</param>
/// <returns>The sum of the two colors.</returns> /// <returns>The sum of the two colors.</returns>
public static Color4 operator +(Color4 left, Color4 right) public static Color4 operator +( Color4 left, Color4 right )
{ {
return new Color4(left.R + right.R, left.G + right.G, left.B + right.B, left.A + right.A); return new Color4( left.R + right.R, left.G + right.G, left.B + right.B, left.A + right.A );
} }
/// <summary> /// <summary>
@ -716,7 +729,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to assert (unchanged).</param> /// <param name="value">The color to assert (unchanged).</param>
/// <returns>The asserted (unchanged) color.</returns> /// <returns>The asserted (unchanged) color.</returns>
public static Color4 operator +(Color4 value) public static Color4 operator +( Color4 value )
{ {
return value; return value;
} }
@ -727,9 +740,9 @@ namespace math
/// <param name="left">The first color to subtract.</param> /// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param> /// <param name="right">The second color to subtract.</param>
/// <returns>The difference of the two colors.</returns> /// <returns>The difference of the two colors.</returns>
public static Color4 operator -(Color4 left, Color4 right) public static Color4 operator -( Color4 left, Color4 right )
{ {
return new Color4(left.R - right.R, left.G - right.G, left.B - right.B, left.A - right.A); return new Color4( left.R - right.R, left.G - right.G, left.B - right.B, left.A - right.A );
} }
/// <summary> /// <summary>
@ -737,9 +750,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The color to negate.</param> /// <param name="value">The color to negate.</param>
/// <returns>A negated color.</returns> /// <returns>A negated color.</returns>
public static Color4 operator -(Color4 value) public static Color4 operator -( Color4 value )
{ {
return new Color4(-value.R, -value.G, -value.B, -value.A); return new Color4( -value.R, -value.G, -value.B, -value.A );
} }
/// <summary> /// <summary>
@ -748,9 +761,9 @@ namespace math
/// <param name="scale">The factor by which to scale the color.</param> /// <param name="scale">The factor by which to scale the color.</param>
/// <param name="value">The color to scale.</param> /// <param name="value">The color to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color4 operator *(float scale, Color4 value) public static Color4 operator *( float scale, Color4 value )
{ {
return new Color4(value.R * scale, value.G * scale, value.B * scale, value.A * scale); return new Color4( value.R * scale, value.G * scale, value.B * scale, value.A * scale );
} }
/// <summary> /// <summary>
@ -759,9 +772,9 @@ namespace math
/// <param name="value">The factor by which to scale the color.</param> /// <param name="value">The factor by which to scale the color.</param>
/// <param name="scale">The color to scale.</param> /// <param name="scale">The color to scale.</param>
/// <returns>The scaled color.</returns> /// <returns>The scaled color.</returns>
public static Color4 operator *(Color4 value, float scale) public static Color4 operator *( Color4 value, float scale )
{ {
return new Color4(value.R * scale, value.G * scale, value.B * scale, value.A * scale); return new Color4( value.R * scale, value.G * scale, value.B * scale, value.A * scale );
} }
/// <summary> /// <summary>
@ -770,9 +783,9 @@ namespace math
/// <param name="left">The first color to modulate.</param> /// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param> /// <param name="right">The second color to modulate.</param>
/// <returns>The modulated color.</returns> /// <returns>The modulated color.</returns>
public static Color4 operator *(Color4 left, Color4 right) public static Color4 operator *( Color4 left, Color4 right )
{ {
return new Color4(left.R * right.R, left.G * right.G, left.B * right.B, left.A * right.A); return new Color4( left.R * right.R, left.G * right.G, left.B * right.B, left.A * right.A );
} }
/// <summary> /// <summary>
@ -781,9 +794,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Color4 left, Color4 right) public static bool operator ==( Color4 left, Color4 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -792,9 +805,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Color4 left, Color4 right) public static bool operator !=( Color4 left, Color4 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -802,9 +815,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color3(Color4 value) public static explicit operator Color3( Color4 value )
{ {
return new Color3(value.R, value.G, value.B); return new Color3( value.R, value.G, value.B );
} }
/// <summary> /// <summary>
@ -812,9 +825,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(Color4 value) public static explicit operator Vec3( Color4 value )
{ {
return new Vec3(value.R, value.G, value.B); return new Vec3( value.R, value.G, value.B );
} }
/// <summary> /// <summary>
@ -822,9 +835,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator Vec4(Color4 value) public static implicit operator Vec4( Color4 value )
{ {
return new Vec4(value.R, value.G, value.B, value.A); return new Vec4( value.R, value.G, value.B, value.A );
} }
/// <summary> /// <summary>
@ -832,9 +845,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color4(Vec3 value) public static explicit operator Color4( Vec3 value )
{ {
return new Color4(value.X, value.Y, value.Z, 1.0f); return new Color4( value.X, value.Y, value.Z, 1.0f );
} }
/// <summary> /// <summary>
@ -842,9 +855,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color4(Vec4 value) public static explicit operator Color4( Vec4 value )
{ {
return new Color4(value.X, value.Y, value.Z, value.W); return new Color4( value.X, value.Y, value.Z, value.W );
} }
/// <summary> /// <summary>
@ -852,9 +865,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Color4(ColorBGRA value) public static explicit operator Color4( ColorBGRA value )
{ {
return new Color4(value); return new Color4( value );
} }
/// <summary> /// <summary>
@ -862,9 +875,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator ColorBGRA(Color4 value) public static explicit operator ColorBGRA( Color4 value )
{ {
return new ColorBGRA(value.R, value.G, value.B, value.A); return new ColorBGRA( value.R, value.G, value.B, value.A );
} }
/// <summary> /// <summary>
@ -874,7 +887,7 @@ namespace math
/// <returns> /// <returns>
/// The result of the conversion. /// The result of the conversion.
/// </returns> /// </returns>
public static explicit operator int(Color4 value) public static explicit operator int( Color4 value )
{ {
return value.ToRgba(); return value.ToRgba();
} }
@ -886,9 +899,9 @@ namespace math
/// <returns> /// <returns>
/// The result of the conversion. /// The result of the conversion.
/// </returns> /// </returns>
public static explicit operator Color4(int value) public static explicit operator Color4( int value )
{ {
return new Color4(value); return new Color4( value );
} }
/// <summary> /// <summary>
@ -897,7 +910,7 @@ namespace math
/// <returns>An equivalent <see cref="Color3"/>, discarding the alpha channel.</returns> /// <returns>An equivalent <see cref="Color3"/>, discarding the alpha channel.</returns>
public Color3 ToColor3() public Color3 ToColor3()
{ {
return new Color3(R, G, B); return new Color3( R, G, B );
} }
/// <summary> /// <summary>
@ -908,7 +921,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return ToString(CultureInfo.CurrentCulture); return ToString( CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -918,9 +931,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
return ToString(format, CultureInfo.CurrentCulture); return ToString( format, CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -930,9 +943,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, ToStringFormat, A, R, G, B); return string.Format( formatProvider, ToStringFormat, A, R, G, B );
} }
/// <summary> /// <summary>
@ -943,16 +956,16 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, ToStringFormat, return string.Format( formatProvider, ToStringFormat,
A.ToString(format, formatProvider), A.ToString( format, formatProvider ),
R.ToString(format, formatProvider), R.ToString( format, formatProvider ),
G.ToString(format, formatProvider), G.ToString( format, formatProvider ),
B.ToString(format, formatProvider)); B.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -973,7 +986,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="Color4"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="Color4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Color4 other) public bool Equals( Color4 other )
{ {
return A == other.A && R == other.R && G == other.G && B == other.B; return A == other.A && R == other.R && G == other.G && B == other.B;
} }
@ -985,15 +998,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (!ReferenceEquals(value.GetType(), typeof(Color4))) if( !ReferenceEquals( value.GetType(), typeof( Color4 ) ) )
return false; return false;
return Equals((Color4)value); return Equals( (Color4)value );
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -16,9 +16,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="stringColor">The string to convert.</param> /// <param name="stringColor">The string to convert.</param>
/// <returns>True if the string can be converted, false otherwise.</returns> /// <returns>True if the string can be converted, false otherwise.</returns>
public static bool CanConvertStringToRgba([CanBeNull] string stringColor) public static bool CanConvertStringToRgba( [CanBeNull] string stringColor )
{ {
return stringColor?.StartsWith("#") ?? false; return stringColor?.StartsWith( "#" ) ?? false;
} }
/// <summary> /// <summary>
@ -26,36 +26,36 @@ namespace math
/// </summary> /// </summary>
/// <param name="stringColor">The string to convert.</param> /// <param name="stringColor">The string to convert.</param>
/// <returns>The converted RGBA value.</returns> /// <returns>The converted RGBA value.</returns>
public static uint StringToRgba([CanBeNull] string stringColor) public static uint StringToRgba( [CanBeNull] string stringColor )
{ {
var intValue = 0xFF000000; var intValue = 0xFF000000;
if (stringColor != null) if( stringColor != null )
{ {
if (stringColor.StartsWith("#")) if( stringColor.StartsWith( "#" ) )
{ {
if (stringColor.Length == "#000".Length && uint.TryParse(stringColor.Substring(1, 3), NumberStyles.HexNumber, null, out intValue)) if( stringColor.Length == "#000".Length && uint.TryParse( stringColor.Substring( 1, 3 ), NumberStyles.HexNumber, null, out intValue ) )
{ {
intValue = ((intValue & 0x00F) << 16) intValue = ( ( intValue & 0x00F ) << 16 )
| ((intValue & 0x00F) << 20) | ( ( intValue & 0x00F ) << 20 )
| ((intValue & 0x0F0) << 4) | ( ( intValue & 0x0F0 ) << 4 )
| ((intValue & 0x0F0) << 8) | ( ( intValue & 0x0F0 ) << 8 )
| ((intValue & 0xF00) >> 4) | ( ( intValue & 0xF00 ) >> 4 )
| ((intValue & 0xF00) >> 8) | ( ( intValue & 0xF00 ) >> 8 )
| (0xFF000000); | ( 0xFF000000 );
} }
if (stringColor.Length == "#000000".Length && uint.TryParse(stringColor.Substring(1, 6), NumberStyles.HexNumber, null, out intValue)) if( stringColor.Length == "#000000".Length && uint.TryParse( stringColor.Substring( 1, 6 ), NumberStyles.HexNumber, null, out intValue ) )
{ {
intValue = ((intValue & 0x000000FF) << 16) intValue = ( ( intValue & 0x000000FF ) << 16 )
| (intValue & 0x0000FF00) | ( intValue & 0x0000FF00 )
| ((intValue & 0x00FF0000) >> 16) | ( ( intValue & 0x00FF0000 ) >> 16 )
| (0xFF000000); | ( 0xFF000000 );
} }
if (stringColor.Length == "#00000000".Length && uint.TryParse(stringColor.Substring(1, 8), NumberStyles.HexNumber, null, out intValue)) if( stringColor.Length == "#00000000".Length && uint.TryParse( stringColor.Substring( 1, 8 ), NumberStyles.HexNumber, null, out intValue ) )
{ {
intValue = ((intValue & 0x000000FF) << 16) intValue = ( ( intValue & 0x000000FF ) << 16 )
| (intValue & 0x0000FF00) | ( intValue & 0x0000FF00 )
| ((intValue & 0x00FF0000) >> 16) | ( ( intValue & 0x00FF0000 ) >> 16 )
| (intValue & 0xFF000000); | ( intValue & 0xFF000000 );
} }
} }
} }
@ -68,11 +68,11 @@ namespace math
/// <param name="value">The RGB value to convert.</param> /// <param name="value">The RGB value to convert.</param>
/// <returns>The converted string.</returns> /// <returns>The converted string.</returns>
[NotNull] [NotNull]
public static string RgbToString(int value) public static string RgbToString( int value )
{ {
var r = (value & 0x000000FF); var r = ( value & 0x000000FF );
var g = (value & 0x0000FF00) >> 8; var g = ( value & 0x0000FF00 ) >> 8;
var b = (value & 0x00FF0000) >> 16; var b = ( value & 0x00FF0000 ) >> 16;
return $"#{r:X2}{g:X2}{b:X2}"; return $"#{r:X2}{g:X2}{b:X2}";
} }
@ -82,12 +82,12 @@ namespace math
/// <param name="value">The RGBA value to convert.</param> /// <param name="value">The RGBA value to convert.</param>
/// <returns>The converted string.</returns> /// <returns>The converted string.</returns>
[NotNull] [NotNull]
public static string RgbaToString(int value) public static string RgbaToString( int value )
{ {
var r = (value & 0x000000FF); var r = ( value & 0x000000FF );
var g = (value & 0x0000FF00) >> 8; var g = ( value & 0x0000FF00 ) >> 8;
var b = (value & 0x00FF0000) >> 16; var b = ( value & 0x00FF0000 ) >> 16;
var a = (value & 0xFF000000) >> 24; var a = ( value & 0xFF000000 ) >> 24;
return $"#{a:X2}{r:X2}{g:X2}{b:X2}"; return $"#{a:X2}{r:X2}{g:X2}{b:X2}";
} }
} }

View File

@ -10,8 +10,8 @@ namespace math
/// <summary> /// <summary>
/// Represents a color in the form of Hue, Saturation, Value, Alpha. /// Represents a color in the form of Hue, Saturation, Value, Alpha.
/// </summary> /// </summary>
[DataContract( Name = "ColorHSV")] [DataContract( Name = "ColorHSV" )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct ColorHSV : IEquatable<ColorHSV>, IFormattable public struct ColorHSV : IEquatable<ColorHSV>, IFormattable
{ {
private const string ToStringFormat = "Hue:{0} Saturation:{1} Value:{2} Alpha:{3}"; private const string ToStringFormat = "Hue:{0} Saturation:{1} Value:{2} Alpha:{3}";
@ -47,7 +47,7 @@ namespace math
/// <param name="s">The s.</param> /// <param name="s">The s.</param>
/// <param name="v">The v.</param> /// <param name="v">The v.</param>
/// <param name="a">A.</param> /// <param name="a">A.</param>
public ColorHSV(float h, float s, float v, float a) public ColorHSV( float h, float s, float v, float a )
{ {
H = h; H = h;
S = s; S = s;
@ -65,24 +65,24 @@ namespace math
int hi = (int)hdiv; int hi = (int)hdiv;
float f = hdiv - hi; float f = hdiv - hi;
float p = V * (1 - S); float p = V * ( 1 - S );
float q = V * (1 - (S * f)); float q = V * ( 1 - ( S * f ) );
float t = V * (1 - (S * (1 - f))); float t = V * ( 1 - ( S * ( 1 - f ) ) );
switch (hi) switch( hi )
{ {
case 0: case 0:
return new Color4(V, t, p, A); return new Color4( V, t, p, A );
case 1: case 1:
return new Color4(q, V, p, A); return new Color4( q, V, p, A );
case 2: case 2:
return new Color4(p, V, t, A); return new Color4( p, V, t, A );
case 3: case 3:
return new Color4(p, q, V, A); return new Color4( p, q, V, A );
case 4: case 4:
return new Color4(t, p, V, A); return new Color4( t, p, V, A );
default: default:
return new Color4(V, p, q, A); return new Color4( V, p, q, A );
} }
} }
@ -91,45 +91,47 @@ namespace math
/// </summary> /// </summary>
/// <param name="color">The color.</param> /// <param name="color">The color.</param>
/// <returns>A HSV color</returns> /// <returns>A HSV color</returns>
public static ColorHSV FromColor(Color4 color) public static ColorHSV FromColor( Color4 color )
{ {
float max = Math.Max(color.R, Math.Max(color.G, color.B)); float max = Math.Max( color.R, Math.Max( color.G, color.B ) );
float min = Math.Min(color.R, Math.Min(color.G, color.B)); float min = Math.Min( color.R, Math.Min( color.G, color.B ) );
float delta = max - min; float delta = max - min;
float h = 0.0f; float h = 0.0f;
if (delta > 0.0f) if( delta > 0.0f )
{ {
if (color.R >= max) if( color.R >= max )
h = (color.G - color.B) / delta; h = ( color.G - color.B ) / delta;
else if (color.G >= max) else if( color.G >= max )
h = (color.B - color.R) / delta + 2.0f; h = ( color.B - color.R ) / delta + 2.0f;
else else
h = (color.R - color.G) / delta + 4.0f; h = ( color.R - color.G ) / delta + 4.0f;
h *= 60.0f; h *= 60.0f;
if (h < 0) if( h < 0 )
h += 360f; h += 360f;
} }
float s = MathUtil.IsZero(max) ? 0.0f : delta / max; float s = MathUtil.IsZero( max ) ? 0.0f : delta / max;
return new ColorHSV(h, s, max, color.A); return new ColorHSV( h, s, max, color.A );
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool Equals(ColorHSV other) public bool Equals( ColorHSV other )
{ {
return other.H.Equals(H) && other.S.Equals(S) && other.V.Equals(V) && other.A.Equals(A); return other.H.Equals( H ) && other.S.Equals( S ) && other.V.Equals( V ) && other.A.Equals( A );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(ColorHSV)) return false; return false;
return Equals((ColorHSV)obj); if( obj.GetType() != typeof( ColorHSV ) )
return false;
return Equals( (ColorHSV)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -138,9 +140,9 @@ namespace math
unchecked unchecked
{ {
int result = H.GetHashCode(); int result = H.GetHashCode();
result = (result * 397) ^ S.GetHashCode(); result = ( result * 397 ) ^ S.GetHashCode();
result = (result * 397) ^ V.GetHashCode(); result = ( result * 397 ) ^ V.GetHashCode();
result = (result * 397) ^ A.GetHashCode(); result = ( result * 397 ) ^ A.GetHashCode();
return result; return result;
} }
} }
@ -153,7 +155,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return ToString(CultureInfo.CurrentCulture); return ToString( CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -163,9 +165,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
return ToString(format, CultureInfo.CurrentCulture); return ToString( format, CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -175,9 +177,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, ToStringFormat, H, S, V, A); return string.Format( formatProvider, ToStringFormat, H, S, V, A );
} }
/// <summary> /// <summary>
@ -188,16 +190,16 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, ToStringFormat, return string.Format( formatProvider, ToStringFormat,
H.ToString(format, formatProvider), H.ToString( format, formatProvider ),
S.ToString(format, formatProvider), S.ToString( format, formatProvider ),
V.ToString(format, formatProvider), V.ToString( format, formatProvider ),
A.ToString(format, formatProvider)); A.ToString( format, formatProvider ) );
} }
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -21,7 +21,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="cascadeIndex">The index of the rectangle</param> /// <param name="cascadeIndex">The index of the rectangle</param>
/// <param name="rectangle">The rectangle found</param> /// <param name="rectangle">The rectangle found</param>
public delegate void InsertRectangleCallback(int cascadeIndex, ref Rectangle rectangle); public delegate void InsertRectangleCallback( int cascadeIndex, ref Rectangle rectangle );
/// <summary> /// <summary>
/// Current width used by the packer. /// Current width used by the packer.
@ -38,10 +38,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="width">The width.</param> /// <param name="width">The width.</param>
/// <param name="height">The height.</param> /// <param name="height">The height.</param>
public void Clear(int width, int height) public void Clear( int width, int height )
{ {
freeRectangles.Clear(); freeRectangles.Clear();
freeRectangles.Add(new Rectangle { X = 0, Y = 0, Width = width, Height = height }); freeRectangles.Add( new Rectangle { X = 0, Y = 0, Width = width, Height = height } );
Width = width; Width = width;
Height = height; Height = height;
@ -52,16 +52,16 @@ namespace math
/// </summary> /// </summary>
public virtual void Clear() public virtual void Clear()
{ {
Clear(Width, Height); Clear( Width, Height );
} }
/// <summary> /// <summary>
/// Frees the specified old rectangle. /// Frees the specified old rectangle.
/// </summary> /// </summary>
/// <param name="oldRectangle">The old rectangle.</param> /// <param name="oldRectangle">The old rectangle.</param>
public void Free(ref Rectangle oldRectangle) public void Free( ref Rectangle oldRectangle )
{ {
freeRectangles.Add(oldRectangle); freeRectangles.Add( oldRectangle );
} }
/// <summary> /// <summary>
@ -71,9 +71,9 @@ namespace math
/// <param name="height">Height requested</param> /// <param name="height">Height requested</param>
/// <param name="bestRectangle">Fill with the rectangle if it was successfully inserted.</param> /// <param name="bestRectangle">Fill with the rectangle if it was successfully inserted.</param>
/// <returns><c>true</c> if it was successfully inserted.</returns> /// <returns><c>true</c> if it was successfully inserted.</returns>
public bool Insert(int width, int height, ref Rectangle bestRectangle) public bool Insert( int width, int height, ref Rectangle bestRectangle )
{ {
return Insert(width, height, freeRectangles, ref bestRectangle); return Insert( width, height, freeRectangles, ref bestRectangle );
} }
/// <summary> /// <summary>
@ -84,48 +84,48 @@ namespace math
/// <param name="count">The number of rectangle to fit.</param> /// <param name="count">The number of rectangle to fit.</param>
/// <param name="inserted">A callback called for each rectangle successfully fitted.</param> /// <param name="inserted">A callback called for each rectangle successfully fitted.</param>
/// <returns><c>true</c> if all rectangles were successfully fitted.</returns> /// <returns><c>true</c> if all rectangles were successfully fitted.</returns>
public bool TryInsert(int width, int height, int count, InsertRectangleCallback inserted) public bool TryInsert( int width, int height, int count, InsertRectangleCallback inserted )
{ {
var bestRectangle = new Rectangle(); var bestRectangle = new Rectangle();
tempFreeRectangles.Clear(); tempFreeRectangles.Clear();
foreach (var freeRectangle in freeRectangles) foreach( var freeRectangle in freeRectangles )
{ {
tempFreeRectangles.Add(freeRectangle); tempFreeRectangles.Add( freeRectangle );
} }
for (var i = 0; i < count; ++i) for( var i = 0; i < count; ++i )
{ {
if (!Insert(width, height, tempFreeRectangles, ref bestRectangle)) if( !Insert( width, height, tempFreeRectangles, ref bestRectangle ) )
{ {
tempFreeRectangles.Clear(); tempFreeRectangles.Clear();
return false; return false;
} }
inserted(i, ref bestRectangle); inserted( i, ref bestRectangle );
} }
// if the insertion went well, use the new configuration // if the insertion went well, use the new configuration
freeRectangles.Clear(); freeRectangles.Clear();
foreach (var tempFreeRectangle in tempFreeRectangles) foreach( var tempFreeRectangle in tempFreeRectangles )
{ {
freeRectangles.Add(tempFreeRectangle); freeRectangles.Add( tempFreeRectangle );
} }
tempFreeRectangles.Clear(); tempFreeRectangles.Clear();
return true; return true;
} }
private static bool Insert(int width, int height, List<Rectangle> freeRectanglesList, ref Rectangle bestRectangle) private static bool Insert( int width, int height, List<Rectangle> freeRectanglesList, ref Rectangle bestRectangle )
{ {
// Info on algorithm: http://clb.demon.fi/files/RectangleBinPack.pdf // Info on algorithm: http://clb.demon.fi/files/RectangleBinPack.pdf
int bestScore = int.MaxValue; int bestScore = int.MaxValue;
int freeRectangleIndex = -1; int freeRectangleIndex = -1;
// Find space for new rectangle // Find space for new rectangle
for (int i = 0; i < freeRectanglesList.Count; ++i) for( int i = 0; i < freeRectanglesList.Count; ++i )
{ {
var currentFreeRectangle = freeRectanglesList[i]; var currentFreeRectangle = freeRectanglesList[i];
if (width == currentFreeRectangle.Width && height == currentFreeRectangle.Height) if( width == currentFreeRectangle.Width && height == currentFreeRectangle.Height )
{ {
// Perfect fit // Perfect fit
bestRectangle.X = currentFreeRectangle.X; bestRectangle.X = currentFreeRectangle.X;
@ -135,12 +135,12 @@ namespace math
freeRectangleIndex = i; freeRectangleIndex = i;
break; break;
} }
if (width <= currentFreeRectangle.Width && height <= currentFreeRectangle.Height) if( width <= currentFreeRectangle.Width && height <= currentFreeRectangle.Height )
{ {
// Can fit inside // Can fit inside
// Use "BAF" heuristic (best area fit) // Use "BAF" heuristic (best area fit)
var score = currentFreeRectangle.Width * currentFreeRectangle.Height - width * height; var score = currentFreeRectangle.Width * currentFreeRectangle.Height - width * height;
if (score < bestScore) if( score < bestScore )
{ {
bestRectangle.X = currentFreeRectangle.X; bestRectangle.X = currentFreeRectangle.X;
bestRectangle.Y = currentFreeRectangle.Y; bestRectangle.Y = currentFreeRectangle.Y;
@ -153,7 +153,7 @@ namespace math
} }
// No space could be found // No space could be found
if (freeRectangleIndex == -1) if( freeRectangleIndex == -1 )
return false; return false;
var freeRectangle = freeRectanglesList[freeRectangleIndex]; var freeRectangle = freeRectanglesList[freeRectangleIndex];
@ -161,21 +161,21 @@ namespace math
// Choose an axis to split (trying to minimize the smaller area "MINAS") // Choose an axis to split (trying to minimize the smaller area "MINAS")
int w = freeRectangle.Width - bestRectangle.Width; int w = freeRectangle.Width - bestRectangle.Width;
int h = freeRectangle.Height - bestRectangle.Height; int h = freeRectangle.Height - bestRectangle.Height;
var splitHorizontal = (bestRectangle.Width * h > w * bestRectangle.Height); var splitHorizontal = ( bestRectangle.Width * h > w * bestRectangle.Height );
// Form the two new rectangles. // Form the two new rectangles.
var bottom = new Rectangle { X = freeRectangle.X, Y = freeRectangle.Y + bestRectangle.Height, Width = splitHorizontal ? freeRectangle.Width : bestRectangle.Width, Height = h }; var bottom = new Rectangle { X = freeRectangle.X, Y = freeRectangle.Y + bestRectangle.Height, Width = splitHorizontal ? freeRectangle.Width : bestRectangle.Width, Height = h };
var right = new Rectangle { X = freeRectangle.X + bestRectangle.Width, Y = freeRectangle.Y, Width = w, Height = splitHorizontal ? bestRectangle.Height : freeRectangle.Height }; var right = new Rectangle { X = freeRectangle.X + bestRectangle.Width, Y = freeRectangle.Y, Width = w, Height = splitHorizontal ? bestRectangle.Height : freeRectangle.Height };
if (bottom.Width > 0 && bottom.Height > 0) if( bottom.Width > 0 && bottom.Height > 0 )
freeRectanglesList.Add(bottom); freeRectanglesList.Add( bottom );
if (right.Width > 0 && right.Height > 0) if( right.Width > 0 && right.Height > 0 )
freeRectanglesList.Add(right); freeRectanglesList.Add( right );
// Remove previously selected freeRectangle // Remove previously selected freeRectangle
if (freeRectangleIndex != freeRectanglesList.Count - 1) if( freeRectangleIndex != freeRectanglesList.Count - 1 )
freeRectanglesList[freeRectangleIndex] = freeRectanglesList[freeRectanglesList.Count - 1]; freeRectanglesList[freeRectangleIndex] = freeRectanglesList[freeRectanglesList.Count - 1];
freeRectanglesList.RemoveAt(freeRectanglesList.Count - 1); freeRectanglesList.RemoveAt( freeRectanglesList.Count - 1 );
return true; return true;
} }

View File

@ -33,7 +33,7 @@ namespace math
/// A half precision (16 bit) floating point value. /// A half precision (16 bit) floating point value.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)] [StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half public struct Half
{ {
private ushort value; private ushort value;
@ -107,9 +107,9 @@ namespace math
/// Initializes a new instance of the <see cref="Half"/> structure. /// Initializes a new instance of the <see cref="Half"/> structure.
/// </summary> /// </summary>
/// <param name = "value">The floating point value that should be stored in 16 bit format.</param> /// <param name = "value">The floating point value that should be stored in 16 bit format.</param>
public Half(float value) public Half( float value )
{ {
this.value = HalfUtils.Pack(value); this.value = HalfUtils.Pack( value );
} }
/// <summary> /// <summary>
@ -126,11 +126,11 @@ namespace math
/// </summary> /// </summary>
/// <param name = "values">The values to be converted.</param> /// <param name = "values">The values to be converted.</param>
/// <returns>An array of converted values.</returns> /// <returns>An array of converted values.</returns>
public static float[] ConvertToFloat(Half[] values) public static float[] ConvertToFloat( Half[] values )
{ {
float[] results = new float[values.Length]; float[] results = new float[values.Length];
for (int i = 0; i < results.Length; i++) for( int i = 0; i < results.Length; i++ )
results[i] = HalfUtils.Unpack(values[i].RawValue); results[i] = HalfUtils.Unpack( values[i].RawValue );
return results; return results;
} }
@ -139,11 +139,11 @@ namespace math
/// </summary> /// </summary>
/// <param name = "values">The values to be converted.</param> /// <param name = "values">The values to be converted.</param>
/// <returns>An array of converted values.</returns> /// <returns>An array of converted values.</returns>
public static Half[] ConvertToHalf(float[] values) public static Half[] ConvertToHalf( float[] values )
{ {
Half[] results = new Half[values.Length]; Half[] results = new Half[values.Length];
for (int i = 0; i < results.Length; i++) for( int i = 0; i < results.Length; i++ )
results[i] = new Half(values[i]); results[i] = new Half( values[i] );
return results; return results;
} }
@ -152,9 +152,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value to be converted.</param> /// <param name = "value">The value to be converted.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static explicit operator Half(float value) public static explicit operator Half( float value )
{ {
return new Half(value); return new Half( value );
} }
/// <summary> /// <summary>
@ -162,9 +162,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value to be converted.</param> /// <param name = "value">The value to be converted.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static implicit operator float(Half value) public static implicit operator float( Half value )
{ {
return HalfUtils.Unpack(value.value); return HalfUtils.Unpack( value.value );
} }
/// <summary> /// <summary>
@ -174,7 +174,7 @@ namespace math
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Half left, Half right) public static bool operator ==( Half left, Half right )
{ {
return left.value == right.value; return left.value == right.value;
} }
@ -186,7 +186,7 @@ namespace math
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator !=(Half left, Half right) public static bool operator !=( Half left, Half right )
{ {
return left.value != right.value; return left.value != right.value;
} }
@ -198,7 +198,7 @@ namespace math
public override string ToString() public override string ToString()
{ {
float num = this; float num = this;
return num.ToString(CultureInfo.CurrentCulture); return num.ToString( CultureInfo.CurrentCulture );
} }
/// <summary> /// <summary>
@ -208,7 +208,7 @@ namespace math
public override int GetHashCode() public override int GetHashCode()
{ {
ushort num = value; ushort num = value;
return ((num * 3) / 2) ^ num; return ( ( num * 3 ) / 2 ) ^ num;
} }
/// <summary> /// <summary>
@ -219,7 +219,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if <paramref name = "value1" /> is the same instance as <paramref name = "value2" /> or /// <c>true</c> if <paramref name = "value1" /> is the same instance as <paramref name = "value2" /> or
/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns> /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
public static bool Equals(ref Half value1, ref Half value2) public static bool Equals( ref Half value1, ref Half value2 )
{ {
return value1.value == value2.value; return value1.value == value2.value;
} }
@ -230,7 +230,7 @@ namespace math
/// <param name = "other">Object to make the comparison with.</param> /// <param name = "other">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public bool Equals(Half other) public bool Equals( Half other )
{ {
return other.value == value; return other.value == value;
} }
@ -241,13 +241,13 @@ namespace math
/// <param name = "obj">Object to make the comparison with.</param> /// <param name = "obj">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (obj == null) if( obj == null )
{ {
return false; return false;
} }
if (obj.GetType() != GetType()) if( obj.GetType() != GetType() )
{ {
return false; return false;
} }

View File

@ -32,7 +32,7 @@ namespace math
/// Represents a two dimensional mathematical vector with half-precision floats. /// Represents a two dimensional mathematical vector with half-precision floats.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)] [StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half2 : IEquatable<Half2> public struct Half2 : IEquatable<Half2>
{ {
/// <summary> /// <summary>
@ -52,7 +52,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="x">The X component.</param> /// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param> /// <param name="y">The Y component.</param>
public Half2(Half x, Half y) public Half2( Half x, Half y )
{ {
this.X = x; this.X = x;
this.Y = y; this.Y = y;
@ -62,7 +62,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half2"/> structure. /// Initializes a new instance of the <see cref="Half2"/> structure.
/// </summary> /// </summary>
/// <param name="value">The value to set for both the X and Y components.</param> /// <param name="value">The value to set for both the X and Y components.</param>
public Half2(Half value) public Half2( Half value )
{ {
this.X = value; this.X = value;
this.Y = value; this.Y = value;
@ -73,7 +73,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="x">The X component.</param> /// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param> /// <param name="y">The Y component.</param>
public Half2(float x, float y) public Half2( float x, float y )
{ {
this.X = (Half)x; this.X = (Half)x;
this.Y = (Half)y; this.Y = (Half)y;
@ -83,7 +83,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half2"/> structure. /// Initializes a new instance of the <see cref="Half2"/> structure.
/// </summary> /// </summary>
/// <param name="value">The value to set for both the X and Y components.</param> /// <param name="value">The value to set for both the X and Y components.</param>
public Half2(float value) public Half2( float value )
{ {
this.X = (Half)value; this.X = (Half)value;
this.Y = (Half)value; this.Y = (Half)value;
@ -96,9 +96,9 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Half2 left, Half2 right) public static bool operator ==( Half2 left, Half2 right )
{ {
return Equals(ref left, ref right); return Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -108,10 +108,10 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns>
[return: MarshalAs(UnmanagedType.U1)] [return: MarshalAs( UnmanagedType.U1 )]
public static bool operator !=(Half2 left, Half2 right) public static bool operator !=( Half2 left, Half2 right )
{ {
return !Equals(ref left, ref right); return !Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -120,7 +120,7 @@ namespace math
/// <returns>A 32-bit signed integer hash code.</returns> /// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode() public override int GetHashCode()
{ {
return (this.Y.GetHashCode() + this.X.GetHashCode()); return ( this.Y.GetHashCode() + this.X.GetHashCode() );
} }
/// <summary> /// <summary>
@ -131,9 +131,9 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or /// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or
/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns> /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
public static bool Equals(ref Half2 value1, ref Half2 value2) public static bool Equals( ref Half2 value1, ref Half2 value2 )
{ {
return ((value1.X == value2.X) && (value1.Y == value2.Y)); return ( ( value1.X == value2.X ) && ( value1.Y == value2.Y ) );
} }
/// <summary> /// <summary>
@ -142,9 +142,9 @@ namespace math
/// <param name="other">Object to make the comparison with.</param> /// <param name="other">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public bool Equals(Half2 other) public bool Equals( Half2 other )
{ {
return ((this.X == other.X) && (this.Y == other.Y)); return ( ( this.X == other.X ) && ( this.Y == other.Y ) );
} }
/// <summary> /// <summary>
@ -153,17 +153,17 @@ namespace math
/// <param name="obj">Object to make the comparison with.</param> /// <param name="obj">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (obj == null) if( obj == null )
{ {
return false; return false;
} }
if (obj.GetType() != GetType()) if( obj.GetType() != GetType() )
{ {
return false; return false;
} }
return this.Equals((Half2)obj); return this.Equals( (Half2)obj );
} }
/// <summary> /// <summary>
@ -171,9 +171,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Half2(Vec2 value) public static explicit operator Half2( Vec2 value )
{ {
return new Half2((Half)value.X, (Half)value.Y); return new Half2( (Half)value.X, (Half)value.Y );
} }
/// <summary> /// <summary>
@ -181,9 +181,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec2(Half2 value) public static explicit operator Vec2( Half2 value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
} }
} }

View File

@ -32,7 +32,7 @@ namespace math
/// Represents a three dimensional mathematical vector with half-precision floats. /// Represents a three dimensional mathematical vector with half-precision floats.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)] [StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half3 : IEquatable<Half3> public struct Half3 : IEquatable<Half3>
{ {
/// <summary> /// <summary>
@ -59,7 +59,7 @@ namespace math
/// <param name="x">The X component.</param> /// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param> /// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param> /// <param name="z">The Z component.</param>
public Half3(Half x, Half y, Half z) public Half3( Half x, Half y, Half z )
{ {
this.X = x; this.X = x;
this.Y = y; this.Y = y;
@ -70,7 +70,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half3"/> structure. /// Initializes a new instance of the <see cref="Half3"/> structure.
/// </summary> /// </summary>
/// <param name="value">The value to set for the X, Y, and Z components.</param> /// <param name="value">The value to set for the X, Y, and Z components.</param>
public Half3(Half value) public Half3( Half value )
{ {
this.X = value; this.X = value;
this.Y = value; this.Y = value;
@ -83,7 +83,7 @@ namespace math
/// <param name="x">The X component.</param> /// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param> /// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param> /// <param name="z">The Z component.</param>
public Half3(float x, float y, float z) public Half3( float x, float y, float z )
{ {
this.X = (Half)x; this.X = (Half)x;
this.Y = (Half)y; this.Y = (Half)y;
@ -94,7 +94,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half3"/> structure. /// Initializes a new instance of the <see cref="Half3"/> structure.
/// </summary> /// </summary>
/// <param name="value">The value to set for the X, Y, and Z components.</param> /// <param name="value">The value to set for the X, Y, and Z components.</param>
public Half3(float value) public Half3( float value )
{ {
this.X = (Half)value; this.X = (Half)value;
this.Y = (Half)value; this.Y = (Half)value;
@ -108,9 +108,9 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Half3 left, Half3 right) public static bool operator ==( Half3 left, Half3 right )
{ {
return Equals(ref left, ref right); return Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -120,10 +120,10 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns>
[return: MarshalAs(UnmanagedType.U1)] [return: MarshalAs( UnmanagedType.U1 )]
public static bool operator !=(Half3 left, Half3 right) public static bool operator !=( Half3 left, Half3 right )
{ {
return !Equals(ref left, ref right); return !Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -133,7 +133,7 @@ namespace math
public override int GetHashCode() public override int GetHashCode()
{ {
int num = this.Z.GetHashCode() + this.Y.GetHashCode(); int num = this.Z.GetHashCode() + this.Y.GetHashCode();
return (this.X.GetHashCode() + num); return ( this.X.GetHashCode() + num );
} }
/// <summary> /// <summary>
@ -144,9 +144,9 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or /// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or
/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns> /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
public static bool Equals(ref Half3 value1, ref Half3 value2) public static bool Equals( ref Half3 value1, ref Half3 value2 )
{ {
return (((value1.X == value2.X) && (value1.Y == value2.Y)) && (value1.Z == value2.Z)); return ( ( ( value1.X == value2.X ) && ( value1.Y == value2.Y ) ) && ( value1.Z == value2.Z ) );
} }
/// <summary> /// <summary>
@ -155,9 +155,9 @@ namespace math
/// <param name="other">Object to make the comparison with.</param> /// <param name="other">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public bool Equals(Half3 other) public bool Equals( Half3 other )
{ {
return (((this.X == other.X) && (this.Y == other.Y)) && (this.Z == other.Z)); return ( ( ( this.X == other.X ) && ( this.Y == other.Y ) ) && ( this.Z == other.Z ) );
} }
/// <summary> /// <summary>
@ -165,9 +165,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Half3(Vec3 value) public static explicit operator Half3( Vec3 value )
{ {
return new Half3((Half)value.X, (Half)value.Y, (Half)value.Z); return new Half3( (Half)value.X, (Half)value.Y, (Half)value.Z );
} }
/// <summary> /// <summary>
@ -175,9 +175,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(Half3 value) public static explicit operator Vec3( Half3 value )
{ {
return new Vec3(value.X, value.Y, value.Z); return new Vec3( value.X, value.Y, value.Z );
} }
/// <summary> /// <summary>
@ -186,17 +186,17 @@ namespace math
/// <param name="obj">Object to make the comparison with.</param> /// <param name="obj">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (obj == null) if( obj == null )
{ {
return false; return false;
} }
if (obj.GetType() != GetType()) if( obj.GetType() != GetType() )
{ {
return false; return false;
} }
return this.Equals((Half3)obj); return this.Equals( (Half3)obj );
} }
} }
} }

View File

@ -33,7 +33,7 @@ namespace math
/// Represents a four dimensional mathematical vector with half-precision floats. /// Represents a four dimensional mathematical vector with half-precision floats.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)] [StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half4 : IEquatable<Half4> public struct Half4 : IEquatable<Half4>
{ {
/// <summary> /// <summary>
@ -67,7 +67,7 @@ namespace math
/// <param name="y">The Y component.</param> /// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param> /// <param name="z">The Z component.</param>
/// <param name="w">The W component.</param> /// <param name="w">The W component.</param>
public Half4(Half x, Half y, Half z, Half w) public Half4( Half x, Half y, Half z, Half w )
{ {
this.X = x; this.X = x;
this.Y = y; this.Y = y;
@ -79,7 +79,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half4"/> structure. /// Initializes a new instance of the <see cref="Half4"/> structure.
/// </summary> /// </summary>
/// <param name="value">The value to set for the X, Y, Z, and W components.</param> /// <param name="value">The value to set for the X, Y, Z, and W components.</param>
public Half4(Half value) public Half4( Half value )
{ {
this.X = value; this.X = value;
this.Y = value; this.Y = value;
@ -94,9 +94,9 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Half4 left, Half4 right) public static bool operator ==( Half4 left, Half4 right )
{ {
return Equals(ref left, ref right); return Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -106,9 +106,9 @@ namespace math
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns> /// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator !=(Half4 left, Half4 right) public static bool operator !=( Half4 left, Half4 right )
{ {
return !Equals(ref left, ref right); return !Equals( ref left, ref right );
} }
/// <summary> /// <summary>
@ -119,7 +119,7 @@ namespace math
{ {
int num2 = this.W.GetHashCode() + this.Z.GetHashCode(); int num2 = this.W.GetHashCode() + this.Z.GetHashCode();
int num = this.Y.GetHashCode() + num2; int num = this.Y.GetHashCode() + num2;
return (this.X.GetHashCode() + num); return ( this.X.GetHashCode() + num );
} }
/// <summary> /// <summary>
@ -130,9 +130,9 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or /// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or
/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns> /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
public static bool Equals(ref Half4 value1, ref Half4 value2) public static bool Equals( ref Half4 value1, ref Half4 value2 )
{ {
return (((value1.X == value2.X) && (value1.Y == value2.Y)) && ((value1.Z == value2.Z) && (value1.W == value2.W))); return ( ( ( value1.X == value2.X ) && ( value1.Y == value2.Y ) ) && ( ( value1.Z == value2.Z ) && ( value1.W == value2.W ) ) );
} }
/// <summary> /// <summary>
@ -141,9 +141,9 @@ namespace math
/// <param name="other">Object to make the comparison with.</param> /// <param name="other">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public bool Equals(Half4 other) public bool Equals( Half4 other )
{ {
return (((this.X == other.X) && (this.Y == other.Y)) && ((this.Z == other.Z) && (this.W == other.W))); return ( ( ( this.X == other.X ) && ( this.Y == other.Y ) ) && ( ( this.Z == other.Z ) && ( this.W == other.W ) ) );
} }
/// <summary> /// <summary>
@ -151,9 +151,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Half4(Vec4 value) public static explicit operator Half4( Vec4 value )
{ {
return new Half4((Half)value.X, (Half)value.Y, (Half)value.Z, (Half)value.W); return new Half4( (Half)value.X, (Half)value.Y, (Half)value.Z, (Half)value.W );
} }
/// <summary> /// <summary>
@ -161,9 +161,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec4(Half4 value) public static explicit operator Vec4( Half4 value )
{ {
return new Vec4(value.X, value.Y, value.Z, value.W); return new Vec4( value.X, value.Y, value.Z, value.W );
} }
/// <summary> /// <summary>
@ -172,17 +172,17 @@ namespace math
/// <param name="obj">Object to make the comparison with.</param> /// <param name="obj">Object to make the comparison with.</param>
/// <returns> /// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (obj == null) if( obj == null )
{ {
return false; return false;
} }
if (obj.GetType() != GetType()) if( obj.GetType() != GetType() )
{ {
return false; return false;
} }
return this.Equals((Half4)obj); return this.Equals( (Half4)obj );
} }
} }
} }

View File

@ -31,12 +31,12 @@ namespace math
/// </summary> /// </summary>
internal class HalfUtils internal class HalfUtils
{ {
[StructLayout(LayoutKind.Explicit, Pack = 4)] [StructLayout( LayoutKind.Explicit, Pack = 4 )]
private struct FloatToUint private struct FloatToUint
{ {
[FieldOffset(0)] [FieldOffset( 0 )]
public uint UIntValue; public uint UIntValue;
[FieldOffset(0)] [FieldOffset( 0 )]
public float FloatValue; public float FloatValue;
} }
@ -45,10 +45,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="h">The packed value.</param> /// <param name="h">The packed value.</param>
/// <returns>The float representation of the packed value.</returns> /// <returns>The float representation of the packed value.</returns>
public static float Unpack(ushort h) public static float Unpack( ushort h )
{ {
var conv = new FloatToUint(); var conv = new FloatToUint();
conv.UIntValue = HalfToFloatMantissaTable[HalfToFloatOffsetTable[h >> 10] + (((uint)h) & 0x3ff)] + HalfToFloatExponentTable[h >> 10]; conv.UIntValue = HalfToFloatMantissaTable[HalfToFloatOffsetTable[h >> 10] + ( ( (uint)h ) & 0x3ff )] + HalfToFloatExponentTable[h >> 10];
return conv.FloatValue; return conv.FloatValue;
} }
@ -57,11 +57,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="f">The float value.</param> /// <param name="f">The float value.</param>
/// <returns>The packed representation of the float value.</returns> /// <returns>The packed representation of the float value.</returns>
public static ushort Pack(float f) public static ushort Pack( float f )
{ {
FloatToUint conv = new FloatToUint(); FloatToUint conv = new FloatToUint();
conv.FloatValue = f; conv.FloatValue = f;
return (ushort)(FloatToHalfBaseTable[(conv.UIntValue >> 23) & 0x1ff] + ((conv.UIntValue & 0x007fffff) >> FloatToHalfShiftTable[(conv.UIntValue >> 23) & 0x1ff])); return (ushort)( FloatToHalfBaseTable[( conv.UIntValue >> 23 ) & 0x1ff] + ( ( conv.UIntValue & 0x007fffff ) >> FloatToHalfShiftTable[( conv.UIntValue >> 23 ) & 0x1ff] ) );
} }
private static readonly uint[] HalfToFloatMantissaTable = new uint[2048]; private static readonly uint[] HalfToFloatMantissaTable = new uint[2048];
@ -84,12 +84,12 @@ namespace math
HalfToFloatMantissaTable[0] = 0; HalfToFloatMantissaTable[0] = 0;
// Transform subnormal to normalized // Transform subnormal to normalized
for (i = 1; i < 1024; i++) for( i = 1; i < 1024; i++ )
{ {
uint m = ((uint)i) << 13; uint m = ( (uint)i ) << 13;
uint e = 0; uint e = 0;
while ((m & 0x00800000) == 0) while( ( m & 0x00800000 ) == 0 )
{ {
e -= 0x00800000; e -= 0x00800000;
m <<= 1; m <<= 1;
@ -100,20 +100,20 @@ namespace math
} }
// Normal case // Normal case
for (i = 1024; i < 2048; i++) for( i = 1024; i < 2048; i++ )
HalfToFloatMantissaTable[i] = 0x38000000 + (((uint)(i - 1024)) << 13); HalfToFloatMantissaTable[i] = 0x38000000 + ( ( (uint)( i - 1024 ) ) << 13 );
// Exponent table // Exponent table
// 0 => 0 // 0 => 0
HalfToFloatExponentTable[0] = 0; HalfToFloatExponentTable[0] = 0;
for (i = 1; i < 63; i++) for( i = 1; i < 63; i++ )
{ {
if (i < 31) // Positive Numbers if( i < 31 ) // Positive Numbers
HalfToFloatExponentTable[i] = ((uint)i) << 23; HalfToFloatExponentTable[i] = ( (uint)i ) << 23;
else // Negative Numbers else // Negative Numbers
HalfToFloatExponentTable[i] = 0x80000000 + (((uint)(i - 32)) << 23); HalfToFloatExponentTable[i] = 0x80000000 + ( ( (uint)( i - 32 ) ) << 23 );
} }
HalfToFloatExponentTable[31] = 0x47800000; HalfToFloatExponentTable[31] = 0x47800000;
HalfToFloatExponentTable[32] = 0x80000000; HalfToFloatExponentTable[32] = 0x80000000;
@ -121,7 +121,7 @@ namespace math
// Offset table // Offset table
HalfToFloatOffsetTable[0] = 0; HalfToFloatOffsetTable[0] = 0;
for (i = 1; i < 64; i++) for( i = 1; i < 64; i++ )
HalfToFloatOffsetTable[i] = 1024; HalfToFloatOffsetTable[i] = 1024;
HalfToFloatOffsetTable[32] = 0; HalfToFloatOffsetTable[32] = 0;
@ -129,31 +129,31 @@ namespace math
// Float to Half tables // Float to Half tables
// ------------------------------------------------------------------- // -------------------------------------------------------------------
for (i = 0; i < 256; i++) for( i = 0; i < 256; i++ )
{ {
int e = i - 127; int e = i - 127;
if (e < -24) if( e < -24 )
{ // Very small numbers map to zero { // Very small numbers map to zero
FloatToHalfBaseTable[i | 0x000] = 0x0000; FloatToHalfBaseTable[i | 0x000] = 0x0000;
FloatToHalfBaseTable[i | 0x100] = 0x8000; FloatToHalfBaseTable[i | 0x100] = 0x8000;
FloatToHalfShiftTable[i | 0x000] = 24; FloatToHalfShiftTable[i | 0x000] = 24;
FloatToHalfShiftTable[i | 0x100] = 24; FloatToHalfShiftTable[i | 0x100] = 24;
} }
else if (e < -14) else if( e < -14 )
{ // Small numbers map to denorms { // Small numbers map to denorms
FloatToHalfBaseTable[i | 0x000] = (ushort)((0x0400 >> (-e - 14))); FloatToHalfBaseTable[i | 0x000] = (ushort)( ( 0x0400 >> ( -e - 14 ) ) );
FloatToHalfBaseTable[i | 0x100] = (ushort)((0x0400 >> (-e - 14)) | 0x8000); FloatToHalfBaseTable[i | 0x100] = (ushort)( ( 0x0400 >> ( -e - 14 ) ) | 0x8000 );
FloatToHalfShiftTable[i | 0x000] = (byte)(-e - 1); FloatToHalfShiftTable[i | 0x000] = (byte)( -e - 1 );
FloatToHalfShiftTable[i | 0x100] = (byte)(-e - 1); FloatToHalfShiftTable[i | 0x100] = (byte)( -e - 1 );
} }
else if (e <= 15) else if( e <= 15 )
{ // Normal numbers just lose precision { // Normal numbers just lose precision
FloatToHalfBaseTable[i | 0x000] = (ushort)(((e + 15) << 10)); FloatToHalfBaseTable[i | 0x000] = (ushort)( ( ( e + 15 ) << 10 ) );
FloatToHalfBaseTable[i | 0x100] = (ushort)(((e + 15) << 10) | 0x8000); FloatToHalfBaseTable[i | 0x100] = (ushort)( ( ( e + 15 ) << 10 ) | 0x8000 );
FloatToHalfShiftTable[i | 0x000] = 13; FloatToHalfShiftTable[i | 0x000] = 13;
FloatToHalfShiftTable[i | 0x100] = 13; FloatToHalfShiftTable[i | 0x100] = 13;
} }
else if (e < 128) else if( e < 128 )
{ // Large numbers map to Infinity { // Large numbers map to Infinity
FloatToHalfBaseTable[i | 0x000] = 0x7C00; FloatToHalfBaseTable[i | 0x000] = 0x7C00;
FloatToHalfBaseTable[i | 0x100] = 0xFC00; FloatToHalfBaseTable[i | 0x100] = 0xFC00;

View File

@ -36,9 +36,9 @@ namespace math
/// <summary> /// <summary>
/// Represents a three dimensional mathematical vector. /// Represents a three dimensional mathematical vector.
/// </summary> /// </summary>
[DataContract( Name = "Int2")] [DataContract( Name = "Int2" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int2 : IEquatable<Int2>, IFormattable public struct Int2 : IEquatable<Int2>, IFormattable
{ {
/// <summary> /// <summary>
@ -54,17 +54,17 @@ namespace math
/// <summary> /// <summary>
/// The X unit <see cref="math.Int2"/> (1, 0, 0). /// The X unit <see cref="math.Int2"/> (1, 0, 0).
/// </summary> /// </summary>
public static readonly Int2 UnitX = new Int2(1, 0); public static readonly Int2 UnitX = new Int2( 1, 0 );
/// <summary> /// <summary>
/// The Y unit <see cref="math.Int2"/> (0, 1, 0). /// The Y unit <see cref="math.Int2"/> (0, 1, 0).
/// </summary> /// </summary>
public static readonly Int2 UnitY = new Int2(0, 1); public static readonly Int2 UnitY = new Int2( 0, 1 );
/// <summary> /// <summary>
/// A <see cref="math.Int2"/> with all of its components set to one. /// A <see cref="math.Int2"/> with all of its components set to one.
/// </summary> /// </summary>
public static readonly Int2 One = new Int2(1, 1); public static readonly Int2 One = new Int2( 1, 1 );
/// <summary> /// <summary>
/// The X component of the vector. /// The X component of the vector.
@ -82,7 +82,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Int2"/> struct. /// Initializes a new instance of the <see cref="math.Int2"/> struct.
/// </summary> /// </summary>
/// <param name="value">The value that will be assigned to all components.</param> /// <param name="value">The value that will be assigned to all components.</param>
public Int2(int value) public Int2( int value )
{ {
X = value; X = value;
Y = value; Y = value;
@ -93,7 +93,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="x">Initial value for the X component of the vector.</param> /// <param name="x">Initial value for the X component of the vector.</param>
/// <param name="y">Initial value for the Y component of the vector.</param> /// <param name="y">Initial value for the Y component of the vector.</param>
public Int2(int x, int y) public Int2( int x, int y )
{ {
X = x; X = x;
Y = y; Y = y;
@ -103,7 +103,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Int2"/> struct. /// Initializes a new instance of the <see cref="math.Int2"/> struct.
/// </summary> /// </summary>
/// <param name="value">A vector containing the values with which to initialize the X and Y components.</param> /// <param name="value">A vector containing the values with which to initialize the X and Y components.</param>
public Int2(Vec2 value) public Int2( Vec2 value )
{ {
X = (int)value.X; X = (int)value.X;
Y = (int)value.Y; Y = (int)value.Y;
@ -115,12 +115,12 @@ namespace math
/// <param name="values">The values to assign to the X, Y, and Z components of the vector. This must be an array with three elements.</param> /// <param name="values">The values to assign to the X, Y, and Z components of the vector. This must be an array with three elements.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than three elements.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than three elements.</exception>
public Int2(int[] values) public Int2( int[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException("values"); throw new ArgumentNullException( "values" );
if (values.Length != 2) if( values.Length != 2 )
throw new ArgumentOutOfRangeException("values", "There must be two and only two input values for Int2."); throw new ArgumentOutOfRangeException( "values", "There must be two and only two input values for Int2." );
X = values[0]; X = values[0];
Y = values[1]; Y = values[1];
@ -137,22 +137,29 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: return X; case 0:
case 1: return Y; return X;
case 1:
return Y;
} }
throw new ArgumentOutOfRangeException("index", "Indices for Int2 run from 0 to 1, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for Int2 run from 0 to 1, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: X = value; break; case 0:
case 1: Y = value; break; X = value;
default: throw new ArgumentOutOfRangeException("index", "Indices for Int2 run from 0 to 1, inclusive."); break;
case 1:
Y = value;
break;
default:
throw new ArgumentOutOfRangeException( "index", "Indices for Int2 run from 0 to 1, inclusive." );
} }
} }
} }
@ -167,7 +174,7 @@ namespace math
/// </remarks> /// </remarks>
public int Length() public int Length()
{ {
return (int)Math.Sqrt((X * X) + (Y * Y)); return (int)Math.Sqrt( ( X * X ) + ( Y * Y ) );
} }
/// <summary> /// <summary>
@ -180,17 +187,17 @@ namespace math
/// </remarks> /// </remarks>
public int LengthSquared() public int LengthSquared()
{ {
return (X * X) + (Y * Y); return ( X * X ) + ( Y * Y );
} }
/// <summary> /// <summary>
/// Raises the exponent for each components. /// Raises the exponent for each components.
/// </summary> /// </summary>
/// <param name="exponent">The exponent.</param> /// <param name="exponent">The exponent.</param>
public void Pow(int exponent) public void Pow( int exponent )
{ {
X = (int)Math.Pow(X, exponent); X = (int)Math.Pow( X, exponent );
Y = (int)Math.Pow(Y, exponent); Y = (int)Math.Pow( Y, exponent );
} }
/// <summary> /// <summary>
@ -208,9 +215,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <param name="result">When the method completes, contains the sum of the two vectors.</param> /// <param name="result">When the method completes, contains the sum of the two vectors.</param>
public static void Add(ref Int2 left, ref Int2 right, out Int2 result) public static void Add( ref Int2 left, ref Int2 right, out Int2 result )
{ {
result = new Int2(left.X + right.X, left.Y + right.Y); result = new Int2( left.X + right.X, left.Y + right.Y );
} }
/// <summary> /// <summary>
@ -219,9 +226,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int2 Add(Int2 left, Int2 right) public static Int2 Add( Int2 left, Int2 right )
{ {
return new Int2(left.X + right.X, left.Y + right.Y); return new Int2( left.X + right.X, left.Y + right.Y );
} }
/// <summary> /// <summary>
@ -230,9 +237,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <param name="result">When the method completes, contains the difference of the two vectors.</param> /// <param name="result">When the method completes, contains the difference of the two vectors.</param>
public static void Subtract(ref Int2 left, ref Int2 right, out Int2 result) public static void Subtract( ref Int2 left, ref Int2 right, out Int2 result )
{ {
result = new Int2(left.X - right.X, left.Y - right.Y); result = new Int2( left.X - right.X, left.Y - right.Y );
} }
/// <summary> /// <summary>
@ -241,9 +248,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int2 Subtract(Int2 left, Int2 right) public static Int2 Subtract( Int2 left, Int2 right )
{ {
return new Int2(left.X - right.X, left.Y - right.Y); return new Int2( left.X - right.X, left.Y - right.Y );
} }
/// <summary> /// <summary>
@ -252,9 +259,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <param name="result">When the method completes, contains the scaled vector.</param> /// <param name="result">When the method completes, contains the scaled vector.</param>
public static void Multiply(ref Int2 value, int scale, out Int2 result) public static void Multiply( ref Int2 value, int scale, out Int2 result )
{ {
result = new Int2(value.X * scale, value.Y * scale); result = new Int2( value.X * scale, value.Y * scale );
} }
/// <summary> /// <summary>
@ -263,9 +270,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int2 Multiply(Int2 value, int scale) public static Int2 Multiply( Int2 value, int scale )
{ {
return new Int2(value.X * scale, value.Y * scale); return new Int2( value.X * scale, value.Y * scale );
} }
/// <summary> /// <summary>
@ -274,9 +281,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param> /// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param> /// <param name="right">The second vector to modulate.</param>
/// <param name="result">When the method completes, contains the modulated vector.</param> /// <param name="result">When the method completes, contains the modulated vector.</param>
public static void Modulate(ref Int2 left, ref Int2 right, out Int2 result) public static void Modulate( ref Int2 left, ref Int2 right, out Int2 result )
{ {
result = new Int2(left.X * right.X, left.Y * right.Y); result = new Int2( left.X * right.X, left.Y * right.Y );
} }
/// <summary> /// <summary>
@ -285,9 +292,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param> /// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param> /// <param name="right">The second vector to modulate.</param>
/// <returns>The modulated vector.</returns> /// <returns>The modulated vector.</returns>
public static Int2 Modulate(Int2 left, Int2 right) public static Int2 Modulate( Int2 left, Int2 right )
{ {
return new Int2(left.X * right.X, left.Y * right.Y); return new Int2( left.X * right.X, left.Y * right.Y );
} }
/// <summary> /// <summary>
@ -296,9 +303,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <param name="result">When the method completes, contains the scaled vector.</param> /// <param name="result">When the method completes, contains the scaled vector.</param>
public static void Divide(ref Int2 value, int scale, out Int2 result) public static void Divide( ref Int2 value, int scale, out Int2 result )
{ {
result = new Int2(value.X / scale, value.Y / scale); result = new Int2( value.X / scale, value.Y / scale );
} }
/// <summary> /// <summary>
@ -307,9 +314,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int2 Divide(Int2 value, int scale) public static Int2 Divide( Int2 value, int scale )
{ {
return new Int2(value.X / scale, value.Y / scale); return new Int2( value.X / scale, value.Y / scale );
} }
/// <summary> /// <summary>
@ -317,9 +324,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <param name="result">When the method completes, contains a vector facing in the opposite direction.</param> /// <param name="result">When the method completes, contains a vector facing in the opposite direction.</param>
public static void Negate(ref Int2 value, out Int2 result) public static void Negate( ref Int2 value, out Int2 result )
{ {
result = new Int2(-value.X, -value.Y); result = new Int2( -value.X, -value.Y );
} }
/// <summary> /// <summary>
@ -327,9 +334,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int2 Negate(Int2 value) public static Int2 Negate( Int2 value )
{ {
return new Int2(-value.X, -value.Y); return new Int2( -value.X, -value.Y );
} }
/// <summary> /// <summary>
@ -339,17 +346,17 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <param name="result">When the method completes, contains the clamped value.</param> /// <param name="result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref Int2 value, ref Int2 min, ref Int2 max, out Int2 result) public static void Clamp( ref Int2 value, ref Int2 min, ref Int2 max, out Int2 result )
{ {
int x = value.X; int x = value.X;
x = (x > max.X) ? max.X : x; x = ( x > max.X ) ? max.X : x;
x = (x < min.X) ? min.X : x; x = ( x < min.X ) ? min.X : x;
int y = value.Y; int y = value.Y;
y = (y > max.Y) ? max.Y : y; y = ( y > max.Y ) ? max.Y : y;
y = (y < min.Y) ? min.Y : y; y = ( y < min.Y ) ? min.Y : y;
result = new Int2(x, y); result = new Int2( x, y );
} }
/// <summary> /// <summary>
@ -359,10 +366,10 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static Int2 Clamp(Int2 value, Int2 min, Int2 max) public static Int2 Clamp( Int2 value, Int2 min, Int2 max )
{ {
Int2 result; Int2 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -372,9 +379,9 @@ namespace math
/// <param name="left">First source vector.</param> /// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param> /// <param name="right">Second source vector.</param>
/// <param name="result">When the method completes, contains the dot product of the two vectors.</param> /// <param name="result">When the method completes, contains the dot product of the two vectors.</param>
public static void Dot(ref Int2 left, ref Int2 right, out int result) public static void Dot( ref Int2 left, ref Int2 right, out int result )
{ {
result = (left.X * right.X) + (left.Y * right.Y); result = ( left.X * right.X ) + ( left.Y * right.Y );
} }
/// <summary> /// <summary>
@ -383,9 +390,9 @@ namespace math
/// <param name="left">First source vector.</param> /// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param> /// <param name="right">Second source vector.</param>
/// <returns>The dot product of the two vectors.</returns> /// <returns>The dot product of the two vectors.</returns>
public static int Dot(Int2 left, Int2 right) public static int Dot( Int2 left, Int2 right )
{ {
return (left.X * right.X) + (left.Y * right.Y); return ( left.X * right.X ) + ( left.Y * right.Y );
} }
/// <summary> /// <summary>
@ -400,10 +407,10 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static void Lerp(ref Int2 start, ref Int2 end, float amount, out Int2 result) public static void Lerp( ref Int2 start, ref Int2 end, float amount, out Int2 result )
{ {
result.X = (int)(start.X + ((end.X - start.X) * amount)); result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount)); result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
} }
/// <summary> /// <summary>
@ -418,10 +425,10 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static Int2 Lerp(Int2 start, Int2 end, float amount) public static Int2 Lerp( Int2 start, Int2 end, float amount )
{ {
Int2 result; Int2 result;
Lerp(ref start, ref end, amount, out result); Lerp( ref start, ref end, amount, out result );
return result; return result;
} }
@ -432,13 +439,13 @@ namespace math
/// <param name="end">End vector.</param> /// <param name="end">End vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <param name="result">When the method completes, contains the cubic interpolation of the two vectors.</param> /// <param name="result">When the method completes, contains the cubic interpolation of the two vectors.</param>
public static void SmoothStep(ref Int2 start, ref Int2 end, float amount, out Int2 result) public static void SmoothStep( ref Int2 start, ref Int2 end, float amount, out Int2 result )
{ {
amount = (amount > 1) ? 1 : ((amount < 0) ? 0 : amount); amount = ( amount > 1 ) ? 1 : ( ( amount < 0 ) ? 0 : amount );
amount = (amount * amount) * (3 - (2 * amount)); amount = ( amount * amount ) * ( 3 - ( 2 * amount ) );
result.X = (int)(start.X + ((end.X - start.X) * amount)); result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount)); result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
} }
/// <summary> /// <summary>
@ -448,10 +455,10 @@ namespace math
/// <param name="end">End vector.</param> /// <param name="end">End vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <returns>The cubic interpolation of the two vectors.</returns> /// <returns>The cubic interpolation of the two vectors.</returns>
public static Int2 SmoothStep(Int2 start, Int2 end, float amount) public static Int2 SmoothStep( Int2 start, Int2 end, float amount )
{ {
Int2 result; Int2 result;
SmoothStep(ref start, ref end, amount, out result); SmoothStep( ref start, ref end, amount, out result );
return result; return result;
} }
@ -461,10 +468,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <param name="result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param> /// <param name="result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param>
public static void Max(ref Int2 left, ref Int2 right, out Int2 result) public static void Max( ref Int2 left, ref Int2 right, out Int2 result )
{ {
result.X = (left.X > right.X) ? left.X : right.X; result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = (left.Y > right.Y) ? left.Y : right.Y; result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
} }
/// <summary> /// <summary>
@ -473,10 +480,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <returns>A vector containing the largest components of the source vectors.</returns> /// <returns>A vector containing the largest components of the source vectors.</returns>
public static Int2 Max(Int2 left, Int2 right) public static Int2 Max( Int2 left, Int2 right )
{ {
Int2 result; Int2 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -486,10 +493,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <param name="result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param> /// <param name="result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param>
public static void Min(ref Int2 left, ref Int2 right, out Int2 result) public static void Min( ref Int2 left, ref Int2 right, out Int2 result )
{ {
result.X = (left.X < right.X) ? left.X : right.X; result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = (left.Y < right.Y) ? left.Y : right.Y; result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
} }
/// <summary> /// <summary>
@ -498,10 +505,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <returns>A vector containing the smallest components of the source vectors.</returns> /// <returns>A vector containing the smallest components of the source vectors.</returns>
public static Int2 Min(Int2 left, Int2 right) public static Int2 Min( Int2 left, Int2 right )
{ {
Int2 result; Int2 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -511,9 +518,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int2 operator +(Int2 left, Int2 right) public static Int2 operator +( Int2 left, Int2 right )
{ {
return new Int2(left.X + right.X, left.Y + right.Y); return new Int2( left.X + right.X, left.Y + right.Y );
} }
/// <summary> /// <summary>
@ -521,7 +528,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to assert (unchange).</param> /// <param name="value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns> /// <returns>The asserted (unchanged) vector.</returns>
public static Int2 operator +(Int2 value) public static Int2 operator +( Int2 value )
{ {
return value; return value;
} }
@ -532,9 +539,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int2 operator -(Int2 left, Int2 right) public static Int2 operator -( Int2 left, Int2 right )
{ {
return new Int2(left.X - right.X, left.Y - right.Y); return new Int2( left.X - right.X, left.Y - right.Y );
} }
/// <summary> /// <summary>
@ -542,9 +549,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int2 operator -(Int2 value) public static Int2 operator -( Int2 value )
{ {
return new Int2(-value.X, -value.Y); return new Int2( -value.X, -value.Y );
} }
/// <summary> /// <summary>
@ -553,9 +560,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int2 operator *(float scale, Int2 value) public static Int2 operator *( float scale, Int2 value )
{ {
return new Int2((int)(value.X * scale), (int)(value.Y * scale)); return new Int2( (int)( value.X * scale ), (int)( value.Y * scale ) );
} }
/// <summary> /// <summary>
@ -564,9 +571,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int2 operator *(Int2 value, float scale) public static Int2 operator *( Int2 value, float scale )
{ {
return new Int2((int)(value.X * scale), (int)(value.Y * scale)); return new Int2( (int)( value.X * scale ), (int)( value.Y * scale ) );
} }
/// <summary> /// <summary>
@ -575,9 +582,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int2 operator /(Int2 value, float scale) public static Int2 operator /( Int2 value, float scale )
{ {
return new Int2((int)(value.X / scale), (int)(value.Y / scale)); return new Int2( (int)( value.X / scale ), (int)( value.Y / scale ) );
} }
/// <summary> /// <summary>
@ -586,9 +593,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Int2 left, Int2 right) public static bool operator ==( Int2 left, Int2 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -597,9 +604,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Int2 left, Int2 right) public static bool operator !=( Int2 left, Int2 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -607,9 +614,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec2(Int2 value) public static explicit operator Vec2( Int2 value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
/// <summary> /// <summary>
@ -617,9 +624,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec4(Int2 value) public static explicit operator Vec4( Int2 value )
{ {
return new Vec4(value.X, value.Y, 0, 0); return new Vec4( value.X, value.Y, 0, 0 );
} }
/// <summary> /// <summary>
@ -630,7 +637,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1}", X, Y); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1}", X, Y );
} }
/// <summary> /// <summary>
@ -640,12 +647,12 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1}", X.ToString(format, CultureInfo.CurrentCulture), Y.ToString(format, CultureInfo.CurrentCulture)); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1}", X.ToString( format, CultureInfo.CurrentCulture ), Y.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -655,9 +662,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "X:{0} Y:{1}", X, Y); return string.Format( formatProvider, "X:{0} Y:{1}", X, Y );
} }
/// <summary> /// <summary>
@ -668,12 +675,12 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, "X:{0} Y:{1}", X.ToString(format, formatProvider), Y.ToString(format, formatProvider)); return string.Format( formatProvider, "X:{0} Y:{1}", X.ToString( format, formatProvider ), Y.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -694,10 +701,10 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="math.Int2"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="math.Int2"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Int2 other) public bool Equals( Int2 other )
{ {
return ((float)Math.Abs(other.X - X) < MathUtil.ZeroTolerance && return ( (float)Math.Abs( other.X - X ) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Y - Y) < MathUtil.ZeroTolerance); (float)Math.Abs( other.Y - Y ) < MathUtil.ZeroTolerance );
} }
/// <summary> /// <summary>
@ -707,15 +714,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Int2)value); return Equals( (Int2)value );
} }
#if WPFInterop #if WPFInterop
/// <summary> /// <summary>

View File

@ -36,9 +36,9 @@ namespace math
/// <summary> /// <summary>
/// Represents a three dimensional mathematical vector. /// Represents a three dimensional mathematical vector.
/// </summary> /// </summary>
[DataContract( Name = "Int3")] [DataContract( Name = "Int3" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int3 : IEquatable<Int3>, IFormattable public struct Int3 : IEquatable<Int3>, IFormattable
{ {
/// <summary> /// <summary>
@ -54,22 +54,22 @@ namespace math
/// <summary> /// <summary>
/// The X unit <see cref="Int3"/> (1, 0, 0). /// The X unit <see cref="Int3"/> (1, 0, 0).
/// </summary> /// </summary>
public static readonly Int3 UnitX = new Int3(1, 0, 0); public static readonly Int3 UnitX = new Int3( 1, 0, 0 );
/// <summary> /// <summary>
/// The Y unit <see cref="Int3"/> (0, 1, 0). /// The Y unit <see cref="Int3"/> (0, 1, 0).
/// </summary> /// </summary>
public static readonly Int3 UnitY = new Int3(0, 1, 0); public static readonly Int3 UnitY = new Int3( 0, 1, 0 );
/// <summary> /// <summary>
/// The Z unit <see cref="Int3"/> (0, 0, 1). /// The Z unit <see cref="Int3"/> (0, 0, 1).
/// </summary> /// </summary>
public static readonly Int3 UnitZ = new Int3(0, 0, 1); public static readonly Int3 UnitZ = new Int3( 0, 0, 1 );
/// <summary> /// <summary>
/// A <see cref="Int3"/> with all of its components set to one. /// A <see cref="Int3"/> with all of its components set to one.
/// </summary> /// </summary>
public static readonly Int3 One = new Int3(1, 1, 1); public static readonly Int3 One = new Int3( 1, 1, 1 );
/// <summary> /// <summary>
/// The X component of the vector. /// The X component of the vector.
@ -93,7 +93,7 @@ namespace math
/// Initializes a new instance of the <see cref="Int3"/> struct. /// Initializes a new instance of the <see cref="Int3"/> struct.
/// </summary> /// </summary>
/// <param name="value">The value that will be assigned to all components.</param> /// <param name="value">The value that will be assigned to all components.</param>
public Int3(int value) public Int3( int value )
{ {
X = value; X = value;
Y = value; Y = value;
@ -106,7 +106,7 @@ namespace math
/// <param name="x">Initial value for the X component of the vector.</param> /// <param name="x">Initial value for the X component of the vector.</param>
/// <param name="y">Initial value for the Y component of the vector.</param> /// <param name="y">Initial value for the Y component of the vector.</param>
/// <param name="z">Initial value for the Z component of the vector.</param> /// <param name="z">Initial value for the Z component of the vector.</param>
public Int3(int x, int y, int z) public Int3( int x, int y, int z )
{ {
X = x; X = x;
Y = y; Y = y;
@ -118,7 +118,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">A vector containing the values with which to initialize the X and Y components.</param> /// <param name="value">A vector containing the values with which to initialize the X and Y components.</param>
/// <param name="z">Initial value for the Z component of the vector.</param> /// <param name="z">Initial value for the Z component of the vector.</param>
public Int3(Vec2 value, int z) public Int3( Vec2 value, int z )
{ {
X = (int)value.X; X = (int)value.X;
Y = (int)value.Y; Y = (int)value.Y;
@ -131,12 +131,12 @@ namespace math
/// <param name="values">The values to assign to the X, Y, and Z components of the vector. This must be an array with three elements.</param> /// <param name="values">The values to assign to the X, Y, and Z components of the vector. This must be an array with three elements.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than three elements.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than three elements.</exception>
public Int3(int[] values) public Int3( int[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException("values"); throw new ArgumentNullException( "values" );
if (values.Length != 3) if( values.Length != 3 )
throw new ArgumentOutOfRangeException("values", "There must be three and only three input values for Int3."); throw new ArgumentOutOfRangeException( "values", "There must be three and only three input values for Int3." );
X = values[0]; X = values[0];
Y = values[1]; Y = values[1];
@ -154,24 +154,34 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: return X; case 0:
case 1: return Y; return X;
case 2: return Z; case 1:
return Y;
case 2:
return Z;
} }
throw new ArgumentOutOfRangeException("index", "Indices for Int3 run from 0 to 2, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for Int3 run from 0 to 2, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: X = value; break; case 0:
case 1: Y = value; break; X = value;
case 2: Z = value; break; break;
default: throw new ArgumentOutOfRangeException("index", "Indices for Int3 run from 0 to 2, inclusive."); case 1:
Y = value;
break;
case 2:
Z = value;
break;
default:
throw new ArgumentOutOfRangeException( "index", "Indices for Int3 run from 0 to 2, inclusive." );
} }
} }
} }
@ -186,7 +196,7 @@ namespace math
/// </remarks> /// </remarks>
public int Length() public int Length()
{ {
return (int)Math.Sqrt((X * X) + (Y * Y) + (Z * Z)); return (int)Math.Sqrt( ( X * X ) + ( Y * Y ) + ( Z * Z ) );
} }
/// <summary> /// <summary>
@ -199,18 +209,18 @@ namespace math
/// </remarks> /// </remarks>
public int LengthSquared() public int LengthSquared()
{ {
return (X * X) + (Y * Y) + (Z * Z); return ( X * X ) + ( Y * Y ) + ( Z * Z );
} }
/// <summary> /// <summary>
/// Raises the exponent for each components. /// Raises the exponent for each components.
/// </summary> /// </summary>
/// <param name="exponent">The exponent.</param> /// <param name="exponent">The exponent.</param>
public void Pow(int exponent) public void Pow( int exponent )
{ {
X = (int)Math.Pow(X, exponent); X = (int)Math.Pow( X, exponent );
Y = (int)Math.Pow(Y, exponent); Y = (int)Math.Pow( Y, exponent );
Z = (int)Math.Pow(Z, exponent); Z = (int)Math.Pow( Z, exponent );
} }
/// <summary> /// <summary>
@ -228,9 +238,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <param name="result">When the method completes, contains the sum of the two vectors.</param> /// <param name="result">When the method completes, contains the sum of the two vectors.</param>
public static void Add(ref Int3 left, ref Int3 right, out Int3 result) public static void Add( ref Int3 left, ref Int3 right, out Int3 result )
{ {
result = new Int3(left.X + right.X, left.Y + right.Y, left.Z + right.Z); result = new Int3( left.X + right.X, left.Y + right.Y, left.Z + right.Z );
} }
/// <summary> /// <summary>
@ -239,9 +249,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int3 Add(Int3 left, Int3 right) public static Int3 Add( Int3 left, Int3 right )
{ {
return new Int3(left.X + right.X, left.Y + right.Y, left.Z + right.Z); return new Int3( left.X + right.X, left.Y + right.Y, left.Z + right.Z );
} }
/// <summary> /// <summary>
@ -250,9 +260,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <param name="result">When the method completes, contains the difference of the two vectors.</param> /// <param name="result">When the method completes, contains the difference of the two vectors.</param>
public static void Subtract(ref Int3 left, ref Int3 right, out Int3 result) public static void Subtract( ref Int3 left, ref Int3 right, out Int3 result )
{ {
result = new Int3(left.X - right.X, left.Y - right.Y, left.Z - right.Z); result = new Int3( left.X - right.X, left.Y - right.Y, left.Z - right.Z );
} }
/// <summary> /// <summary>
@ -261,9 +271,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int3 Subtract(Int3 left, Int3 right) public static Int3 Subtract( Int3 left, Int3 right )
{ {
return new Int3(left.X - right.X, left.Y - right.Y, left.Z - right.Z); return new Int3( left.X - right.X, left.Y - right.Y, left.Z - right.Z );
} }
/// <summary> /// <summary>
@ -272,9 +282,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <param name="result">When the method completes, contains the scaled vector.</param> /// <param name="result">When the method completes, contains the scaled vector.</param>
public static void Multiply(ref Int3 value, int scale, out Int3 result) public static void Multiply( ref Int3 value, int scale, out Int3 result )
{ {
result = new Int3(value.X * scale, value.Y * scale, value.Z * scale); result = new Int3( value.X * scale, value.Y * scale, value.Z * scale );
} }
/// <summary> /// <summary>
@ -283,9 +293,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int3 Multiply(Int3 value, int scale) public static Int3 Multiply( Int3 value, int scale )
{ {
return new Int3(value.X * scale, value.Y * scale, value.Z * scale); return new Int3( value.X * scale, value.Y * scale, value.Z * scale );
} }
/// <summary> /// <summary>
@ -294,9 +304,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param> /// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param> /// <param name="right">The second vector to modulate.</param>
/// <param name="result">When the method completes, contains the modulated vector.</param> /// <param name="result">When the method completes, contains the modulated vector.</param>
public static void Modulate(ref Int3 left, ref Int3 right, out Int3 result) public static void Modulate( ref Int3 left, ref Int3 right, out Int3 result )
{ {
result = new Int3(left.X * right.X, left.Y * right.Y, left.Z * right.Z); result = new Int3( left.X * right.X, left.Y * right.Y, left.Z * right.Z );
} }
/// <summary> /// <summary>
@ -305,9 +315,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param> /// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param> /// <param name="right">The second vector to modulate.</param>
/// <returns>The modulated vector.</returns> /// <returns>The modulated vector.</returns>
public static Int3 Modulate(Int3 left, Int3 right) public static Int3 Modulate( Int3 left, Int3 right )
{ {
return new Int3(left.X * right.X, left.Y * right.Y, left.Z * right.Z); return new Int3( left.X * right.X, left.Y * right.Y, left.Z * right.Z );
} }
/// <summary> /// <summary>
@ -316,9 +326,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <param name="result">When the method completes, contains the scaled vector.</param> /// <param name="result">When the method completes, contains the scaled vector.</param>
public static void Divide(ref Int3 value, int scale, out Int3 result) public static void Divide( ref Int3 value, int scale, out Int3 result )
{ {
result = new Int3(value.X / scale, value.Y / scale, value.Z / scale); result = new Int3( value.X / scale, value.Y / scale, value.Z / scale );
} }
/// <summary> /// <summary>
@ -327,9 +337,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int3 Divide(Int3 value, int scale) public static Int3 Divide( Int3 value, int scale )
{ {
return new Int3(value.X / scale, value.Y / scale, value.Z / scale); return new Int3( value.X / scale, value.Y / scale, value.Z / scale );
} }
/// <summary> /// <summary>
@ -337,9 +347,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <param name="result">When the method completes, contains a vector facing in the opposite direction.</param> /// <param name="result">When the method completes, contains a vector facing in the opposite direction.</param>
public static void Negate(ref Int3 value, out Int3 result) public static void Negate( ref Int3 value, out Int3 result )
{ {
result = new Int3(-value.X, -value.Y, -value.Z); result = new Int3( -value.X, -value.Y, -value.Z );
} }
/// <summary> /// <summary>
@ -347,9 +357,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int3 Negate(Int3 value) public static Int3 Negate( Int3 value )
{ {
return new Int3(-value.X, -value.Y, -value.Z); return new Int3( -value.X, -value.Y, -value.Z );
} }
/// <summary> /// <summary>
@ -359,21 +369,21 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <param name="result">When the method completes, contains the clamped value.</param> /// <param name="result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref Int3 value, ref Int3 min, ref Int3 max, out Int3 result) public static void Clamp( ref Int3 value, ref Int3 min, ref Int3 max, out Int3 result )
{ {
int x = value.X; int x = value.X;
x = (x > max.X) ? max.X : x; x = ( x > max.X ) ? max.X : x;
x = (x < min.X) ? min.X : x; x = ( x < min.X ) ? min.X : x;
int y = value.Y; int y = value.Y;
y = (y > max.Y) ? max.Y : y; y = ( y > max.Y ) ? max.Y : y;
y = (y < min.Y) ? min.Y : y; y = ( y < min.Y ) ? min.Y : y;
int z = value.Z; int z = value.Z;
z = (z > max.Z) ? max.Z : z; z = ( z > max.Z ) ? max.Z : z;
z = (z < min.Z) ? min.Z : z; z = ( z < min.Z ) ? min.Z : z;
result = new Int3(x, y, z); result = new Int3( x, y, z );
} }
/// <summary> /// <summary>
@ -383,10 +393,10 @@ namespace math
/// <param name="min">The minimum value.</param> /// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param> /// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static Int3 Clamp(Int3 value, Int3 min, Int3 max) public static Int3 Clamp( Int3 value, Int3 min, Int3 max )
{ {
Int3 result; Int3 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -396,9 +406,9 @@ namespace math
/// <param name="left">First source vector.</param> /// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param> /// <param name="right">Second source vector.</param>
/// <param name="result">When the method completes, contains the dot product of the two vectors.</param> /// <param name="result">When the method completes, contains the dot product of the two vectors.</param>
public static void Dot(ref Int3 left, ref Int3 right, out int result) public static void Dot( ref Int3 left, ref Int3 right, out int result )
{ {
result = (left.X * right.X) + (left.Y * right.Y) + (left.Z * right.Z); result = ( left.X * right.X ) + ( left.Y * right.Y ) + ( left.Z * right.Z );
} }
/// <summary> /// <summary>
@ -407,9 +417,9 @@ namespace math
/// <param name="left">First source vector.</param> /// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param> /// <param name="right">Second source vector.</param>
/// <returns>The dot product of the two vectors.</returns> /// <returns>The dot product of the two vectors.</returns>
public static int Dot(Int3 left, Int3 right) public static int Dot( Int3 left, Int3 right )
{ {
return (left.X * right.X) + (left.Y * right.Y) + (left.Z * right.Z); return ( left.X * right.X ) + ( left.Y * right.Y ) + ( left.Z * right.Z );
} }
/// <summary> /// <summary>
@ -424,11 +434,11 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static void Lerp(ref Int3 start, ref Int3 end, float amount, out Int3 result) public static void Lerp( ref Int3 start, ref Int3 end, float amount, out Int3 result )
{ {
result.X = (int)(start.X + ((end.X - start.X) * amount)); result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount)); result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
result.Z = (int)(start.Z + ((end.Z - start.Z) * amount)); result.Z = (int)( start.Z + ( ( end.Z - start.Z ) * amount ) );
} }
/// <summary> /// <summary>
@ -443,10 +453,10 @@ namespace math
/// <code>start + (end - start) * amount</code> /// <code>start + (end - start) * amount</code>
/// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned. /// Passing <paramref name="amount"/> a value of 0 will cause <paramref name="start"/> to be returned; a value of 1 will cause <paramref name="end"/> to be returned.
/// </remarks> /// </remarks>
public static Int3 Lerp(Int3 start, Int3 end, float amount) public static Int3 Lerp( Int3 start, Int3 end, float amount )
{ {
Int3 result; Int3 result;
Lerp(ref start, ref end, amount, out result); Lerp( ref start, ref end, amount, out result );
return result; return result;
} }
@ -457,14 +467,14 @@ namespace math
/// <param name="end">End vector.</param> /// <param name="end">End vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <param name="result">When the method completes, contains the cubic interpolation of the two vectors.</param> /// <param name="result">When the method completes, contains the cubic interpolation of the two vectors.</param>
public static void SmoothStep(ref Int3 start, ref Int3 end, float amount, out Int3 result) public static void SmoothStep( ref Int3 start, ref Int3 end, float amount, out Int3 result )
{ {
amount = (amount > 1) ? 1 : ((amount < 0) ? 0 : amount); amount = ( amount > 1 ) ? 1 : ( ( amount < 0 ) ? 0 : amount );
amount = (amount * amount) * (3 - (2 * amount)); amount = ( amount * amount ) * ( 3 - ( 2 * amount ) );
result.X = (int)(start.X + ((end.X - start.X) * amount)); result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount)); result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
result.Z = (int)(start.Z + ((end.Z - start.Z) * amount)); result.Z = (int)( start.Z + ( ( end.Z - start.Z ) * amount ) );
} }
/// <summary> /// <summary>
@ -474,10 +484,10 @@ namespace math
/// <param name="end">End vector.</param> /// <param name="end">End vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <returns>The cubic interpolation of the two vectors.</returns> /// <returns>The cubic interpolation of the two vectors.</returns>
public static Int3 SmoothStep(Int3 start, Int3 end, float amount) public static Int3 SmoothStep( Int3 start, Int3 end, float amount )
{ {
Int3 result; Int3 result;
SmoothStep(ref start, ref end, amount, out result); SmoothStep( ref start, ref end, amount, out result );
return result; return result;
} }
@ -487,11 +497,11 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <param name="result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param> /// <param name="result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param>
public static void Max(ref Int3 left, ref Int3 right, out Int3 result) public static void Max( ref Int3 left, ref Int3 right, out Int3 result )
{ {
result.X = (left.X > right.X) ? left.X : right.X; result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = (left.Y > right.Y) ? left.Y : right.Y; result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z; result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
} }
/// <summary> /// <summary>
@ -500,10 +510,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <returns>A vector containing the largest components of the source vectors.</returns> /// <returns>A vector containing the largest components of the source vectors.</returns>
public static Int3 Max(Int3 left, Int3 right) public static Int3 Max( Int3 left, Int3 right )
{ {
Int3 result; Int3 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -513,11 +523,11 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <param name="result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param> /// <param name="result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param>
public static void Min(ref Int3 left, ref Int3 right, out Int3 result) public static void Min( ref Int3 left, ref Int3 right, out Int3 result )
{ {
result.X = (left.X < right.X) ? left.X : right.X; result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = (left.Y < right.Y) ? left.Y : right.Y; result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z; result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
} }
/// <summary> /// <summary>
@ -526,10 +536,10 @@ namespace math
/// <param name="left">The first source vector.</param> /// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param> /// <param name="right">The second source vector.</param>
/// <returns>A vector containing the smallest components of the source vectors.</returns> /// <returns>A vector containing the smallest components of the source vectors.</returns>
public static Int3 Min(Int3 left, Int3 right) public static Int3 Min( Int3 left, Int3 right )
{ {
Int3 result; Int3 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -539,9 +549,9 @@ namespace math
/// <param name="left">The first vector to add.</param> /// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param> /// <param name="right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int3 operator +(Int3 left, Int3 right) public static Int3 operator +( Int3 left, Int3 right )
{ {
return new Int3(left.X + right.X, left.Y + right.Y, left.Z + right.Z); return new Int3( left.X + right.X, left.Y + right.Y, left.Z + right.Z );
} }
/// <summary> /// <summary>
@ -549,7 +559,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to assert (unchange).</param> /// <param name="value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns> /// <returns>The asserted (unchanged) vector.</returns>
public static Int3 operator +(Int3 value) public static Int3 operator +( Int3 value )
{ {
return value; return value;
} }
@ -560,9 +570,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param> /// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param> /// <param name="right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int3 operator -(Int3 left, Int3 right) public static Int3 operator -( Int3 left, Int3 right )
{ {
return new Int3(left.X - right.X, left.Y - right.Y, left.Z - right.Z); return new Int3( left.X - right.X, left.Y - right.Y, left.Z - right.Z );
} }
/// <summary> /// <summary>
@ -570,9 +580,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The vector to negate.</param> /// <param name="value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int3 operator -(Int3 value) public static Int3 operator -( Int3 value )
{ {
return new Int3(-value.X, -value.Y, -value.Z); return new Int3( -value.X, -value.Y, -value.Z );
} }
/// <summary> /// <summary>
@ -581,9 +591,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int3 operator *(float scale, Int3 value) public static Int3 operator *( float scale, Int3 value )
{ {
return new Int3((int)(value.X * scale), (int)(value.Y * scale), (int)(value.Z * scale)); return new Int3( (int)( value.X * scale ), (int)( value.Y * scale ), (int)( value.Z * scale ) );
} }
/// <summary> /// <summary>
@ -592,9 +602,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int3 operator *(Int3 value, float scale) public static Int3 operator *( Int3 value, float scale )
{ {
return new Int3((int)(value.X * scale), (int)(value.Y * scale), (int)(value.Z * scale)); return new Int3( (int)( value.X * scale ), (int)( value.Y * scale ), (int)( value.Z * scale ) );
} }
/// <summary> /// <summary>
@ -603,9 +613,9 @@ namespace math
/// <param name="value">The vector to scale.</param> /// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param> /// <param name="scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int3 operator /(Int3 value, float scale) public static Int3 operator /( Int3 value, float scale )
{ {
return new Int3((int)(value.X / scale), (int)(value.Y / scale), (int)(value.Z / scale)); return new Int3( (int)( value.X / scale ), (int)( value.Y / scale ), (int)( value.Z / scale ) );
} }
/// <summary> /// <summary>
@ -614,9 +624,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Int3 left, Int3 right) public static bool operator ==( Int3 left, Int3 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -625,9 +635,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Int3 left, Int3 right) public static bool operator !=( Int3 left, Int3 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -635,9 +645,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec2(Int3 value) public static explicit operator Vec2( Int3 value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
/// <summary> /// <summary>
@ -645,9 +655,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(Int3 value) public static explicit operator Vec3( Int3 value )
{ {
return new Vec3(value.X, value.Y, value.Z); return new Vec3( value.X, value.Y, value.Z );
} }
/// <summary> /// <summary>
@ -655,9 +665,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec4(Int3 value) public static explicit operator Vec4( Int3 value )
{ {
return new Vec4(value.X, value.Y, value.Z, 0); return new Vec4( value.X, value.Y, value.Z, 0 );
} }
/// <summary> /// <summary>
@ -668,7 +678,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2}", X, Y, Z); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2}", X, Y, Z );
} }
/// <summary> /// <summary>
@ -678,13 +688,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2}", X.ToString(format, CultureInfo.CurrentCulture), return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2}", X.ToString( format, CultureInfo.CurrentCulture ),
Y.ToString(format, CultureInfo.CurrentCulture), Z.ToString(format, CultureInfo.CurrentCulture)); Y.ToString( format, CultureInfo.CurrentCulture ), Z.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -694,9 +704,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2}", X, Y, Z); return string.Format( formatProvider, "X:{0} Y:{1} Z:{2}", X, Y, Z );
} }
/// <summary> /// <summary>
@ -707,13 +717,13 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
return ToString(formatProvider); return ToString( formatProvider );
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2}", X.ToString(format, formatProvider), return string.Format( formatProvider, "X:{0} Y:{1} Z:{2}", X.ToString( format, formatProvider ),
Y.ToString(format, formatProvider), Z.ToString(format, formatProvider)); Y.ToString( format, formatProvider ), Z.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -734,11 +744,11 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="Int3"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="Int3"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Int3 other) public bool Equals( Int3 other )
{ {
return ((float)Math.Abs(other.X - X) < MathUtil.ZeroTolerance && return ( (float)Math.Abs( other.X - X ) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Y - Y) < MathUtil.ZeroTolerance && (float)Math.Abs( other.Y - Y ) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Z - Z) < MathUtil.ZeroTolerance); (float)Math.Abs( other.Z - Z ) < MathUtil.ZeroTolerance );
} }
/// <summary> /// <summary>
@ -748,15 +758,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Int3)value); return Equals( (Int3)value );
} }
#if WPFInterop #if WPFInterop
/// <summary> /// <summary>

View File

@ -30,9 +30,9 @@ namespace math
/// <summary> /// <summary>
/// Represents a four dimensional mathematical vector. /// Represents a four dimensional mathematical vector.
/// </summary> /// </summary>
[DataContract( Name = "Int4")] [DataContract( Name = "Int4" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int4 : IEquatable<Int4>, IFormattable public struct Int4 : IEquatable<Int4>, IFormattable
{ {
/// <summary> /// <summary>
@ -48,27 +48,27 @@ namespace math
/// <summary> /// <summary>
/// The X unit <see cref = "Int4" /> (1, 0, 0, 0). /// The X unit <see cref = "Int4" /> (1, 0, 0, 0).
/// </summary> /// </summary>
public static readonly Int4 UnitX = new Int4(1, 0, 0, 0); public static readonly Int4 UnitX = new Int4( 1, 0, 0, 0 );
/// <summary> /// <summary>
/// The Y unit <see cref = "Int4" /> (0, 1, 0, 0). /// The Y unit <see cref = "Int4" /> (0, 1, 0, 0).
/// </summary> /// </summary>
public static readonly Int4 UnitY = new Int4(0, 1, 0, 0); public static readonly Int4 UnitY = new Int4( 0, 1, 0, 0 );
/// <summary> /// <summary>
/// The Z unit <see cref = "Int4" /> (0, 0, 1, 0). /// The Z unit <see cref = "Int4" /> (0, 0, 1, 0).
/// </summary> /// </summary>
public static readonly Int4 UnitZ = new Int4(0, 0, 1, 0); public static readonly Int4 UnitZ = new Int4( 0, 0, 1, 0 );
/// <summary> /// <summary>
/// The W unit <see cref = "Int4" /> (0, 0, 0, 1). /// The W unit <see cref = "Int4" /> (0, 0, 0, 1).
/// </summary> /// </summary>
public static readonly Int4 UnitW = new Int4(0, 0, 0, 1); public static readonly Int4 UnitW = new Int4( 0, 0, 0, 1 );
/// <summary> /// <summary>
/// A <see cref = "Int4" /> with all of its components set to one. /// A <see cref = "Int4" /> with all of its components set to one.
/// </summary> /// </summary>
public static readonly Int4 One = new Int4(1, 1, 1, 1); public static readonly Int4 One = new Int4( 1, 1, 1, 1 );
/// <summary> /// <summary>
/// The X component of the vector. /// The X component of the vector.
@ -98,7 +98,7 @@ namespace math
/// Initializes a new instance of the <see cref = "Int4" /> struct. /// Initializes a new instance of the <see cref = "Int4" /> struct.
/// </summary> /// </summary>
/// <param name = "value">The value that will be assigned to all components.</param> /// <param name = "value">The value that will be assigned to all components.</param>
public Int4(int value) public Int4( int value )
{ {
X = value; X = value;
Y = value; Y = value;
@ -113,7 +113,7 @@ namespace math
/// <param name = "y">Initial value for the Y component of the vector.</param> /// <param name = "y">Initial value for the Y component of the vector.</param>
/// <param name = "z">Initial value for the Z component of the vector.</param> /// <param name = "z">Initial value for the Z component of the vector.</param>
/// <param name = "w">Initial value for the W component of the vector.</param> /// <param name = "w">Initial value for the W component of the vector.</param>
public Int4(int x, int y, int z, int w) public Int4( int x, int y, int z, int w )
{ {
X = x; X = x;
Y = y; Y = y;
@ -127,12 +127,12 @@ namespace math
/// <param name = "values">The values to assign to the X, Y, Z, and W components of the vector. This must be an array with four elements.</param> /// <param name = "values">The values to assign to the X, Y, Z, and W components of the vector. This must be an array with four elements.</param>
/// <exception cref = "ArgumentNullException">Thrown when <paramref name = "values" /> is <c>null</c>.</exception> /// <exception cref = "ArgumentNullException">Thrown when <paramref name = "values" /> is <c>null</c>.</exception>
/// <exception cref = "ArgumentOutOfRangeException">Thrown when <paramref name = "values" /> contains more or less than four elements.</exception> /// <exception cref = "ArgumentOutOfRangeException">Thrown when <paramref name = "values" /> contains more or less than four elements.</exception>
public Int4(int[] values) public Int4( int[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException("values"); throw new ArgumentNullException( "values" );
if (values.Length != 4) if( values.Length != 4 )
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for Int4."); throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for Int4." );
X = values[0]; X = values[0];
Y = values[1]; Y = values[1];
@ -151,7 +151,7 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: case 0:
return X; return X;
@ -163,12 +163,12 @@ namespace math
return W; return W;
} }
throw new ArgumentOutOfRangeException("index", "Indices for Int4 run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for Int4 run from 0 to 3, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: case 0:
X = value; X = value;
@ -183,7 +183,7 @@ namespace math
W = value; W = value;
break; break;
default: default:
throw new ArgumentOutOfRangeException("index", "Indices for Int4 run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for Int4 run from 0 to 3, inclusive." );
} }
} }
} }
@ -198,7 +198,7 @@ namespace math
/// </remarks> /// </remarks>
public int Length() public int Length()
{ {
return (int)Math.Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); return (int)Math.Sqrt( ( X * X ) + ( Y * Y ) + ( Z * Z ) + ( W * W ) );
} }
/// <summary> /// <summary>
@ -211,7 +211,7 @@ namespace math
/// </remarks> /// </remarks>
public int LengthSquared() public int LengthSquared()
{ {
return (X * X) + (Y * Y) + (Z * Z) + (W * W); return ( X * X ) + ( Y * Y ) + ( Z * Z ) + ( W * W );
} }
/// <summary> /// <summary>
@ -229,9 +229,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <param name = "result">When the method completes, contains the sum of the two vectors.</param> /// <param name = "result">When the method completes, contains the sum of the two vectors.</param>
public static void Add(ref Int4 left, ref Int4 right, out Int4 result) public static void Add( ref Int4 left, ref Int4 right, out Int4 result )
{ {
result = new Int4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); result = new Int4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -240,9 +240,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int4 Add(Int4 left, Int4 right) public static Int4 Add( Int4 left, Int4 right )
{ {
return new Int4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); return new Int4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -251,9 +251,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <param name = "result">When the method completes, contains the difference of the two vectors.</param> /// <param name = "result">When the method completes, contains the difference of the two vectors.</param>
public static void Subtract(ref Int4 left, ref Int4 right, out Int4 result) public static void Subtract( ref Int4 left, ref Int4 right, out Int4 result )
{ {
result = new Int4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); result = new Int4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -262,9 +262,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int4 Subtract(Int4 left, Int4 right) public static Int4 Subtract( Int4 left, Int4 right )
{ {
return new Int4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); return new Int4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -273,9 +273,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <param name = "result">When the method completes, contains the scaled vector.</param> /// <param name = "result">When the method completes, contains the scaled vector.</param>
public static void Multiply(ref Int4 value, int scale, out Int4 result) public static void Multiply( ref Int4 value, int scale, out Int4 result )
{ {
result = new Int4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); result = new Int4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -284,9 +284,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int4 Multiply(Int4 value, int scale) public static Int4 Multiply( Int4 value, int scale )
{ {
return new Int4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new Int4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -295,9 +295,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param> /// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param> /// <param name = "right">The second vector to modulate.</param>
/// <param name = "result">When the method completes, contains the modulated vector.</param> /// <param name = "result">When the method completes, contains the modulated vector.</param>
public static void Modulate(ref Int4 left, ref Int4 right, out Int4 result) public static void Modulate( ref Int4 left, ref Int4 right, out Int4 result )
{ {
result = new Int4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); result = new Int4( left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W );
} }
/// <summary> /// <summary>
@ -306,9 +306,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param> /// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param> /// <param name = "right">The second vector to modulate.</param>
/// <returns>The modulated vector.</returns> /// <returns>The modulated vector.</returns>
public static Int4 Modulate(Int4 left, Int4 right) public static Int4 Modulate( Int4 left, Int4 right )
{ {
return new Int4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); return new Int4( left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W );
} }
/// <summary> /// <summary>
@ -317,9 +317,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <param name = "result">When the method completes, contains the scaled vector.</param> /// <param name = "result">When the method completes, contains the scaled vector.</param>
public static void Divide(ref Int4 value, int scale, out Int4 result) public static void Divide( ref Int4 value, int scale, out Int4 result )
{ {
result = new Int4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); result = new Int4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -328,9 +328,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int4 Divide(Int4 value, int scale) public static Int4 Divide( Int4 value, int scale )
{ {
return new Int4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); return new Int4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -338,9 +338,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The vector to negate.</param> /// <param name = "value">The vector to negate.</param>
/// <param name = "result">When the method completes, contains a vector facing in the opposite direction.</param> /// <param name = "result">When the method completes, contains a vector facing in the opposite direction.</param>
public static void Negate(ref Int4 value, out Int4 result) public static void Negate( ref Int4 value, out Int4 result )
{ {
result = new Int4(-value.X, -value.Y, -value.Z, -value.W); result = new Int4( -value.X, -value.Y, -value.Z, -value.W );
} }
/// <summary> /// <summary>
@ -348,9 +348,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The vector to negate.</param> /// <param name = "value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int4 Negate(Int4 value) public static Int4 Negate( Int4 value )
{ {
return new Int4(-value.X, -value.Y, -value.Z, -value.W); return new Int4( -value.X, -value.Y, -value.Z, -value.W );
} }
/// <summary> /// <summary>
@ -360,25 +360,25 @@ namespace math
/// <param name = "min">The minimum value.</param> /// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param> /// <param name = "max">The maximum value.</param>
/// <param name = "result">When the method completes, contains the clamped value.</param> /// <param name = "result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref Int4 value, ref Int4 min, ref Int4 max, out Int4 result) public static void Clamp( ref Int4 value, ref Int4 min, ref Int4 max, out Int4 result )
{ {
int x = value.X; int x = value.X;
x = (x > max.X) ? max.X : x; x = ( x > max.X ) ? max.X : x;
x = (x < min.X) ? min.X : x; x = ( x < min.X ) ? min.X : x;
int y = value.Y; int y = value.Y;
y = (y > max.Y) ? max.Y : y; y = ( y > max.Y ) ? max.Y : y;
y = (y < min.Y) ? min.Y : y; y = ( y < min.Y ) ? min.Y : y;
int z = value.Z; int z = value.Z;
z = (z > max.Z) ? max.Z : z; z = ( z > max.Z ) ? max.Z : z;
z = (z < min.Z) ? min.Z : z; z = ( z < min.Z ) ? min.Z : z;
int w = value.W; int w = value.W;
w = (w > max.W) ? max.W : w; w = ( w > max.W ) ? max.W : w;
w = (w < min.W) ? min.W : w; w = ( w < min.W ) ? min.W : w;
result = new Int4(x, y, z, w); result = new Int4( x, y, z, w );
} }
/// <summary> /// <summary>
@ -388,10 +388,10 @@ namespace math
/// <param name = "min">The minimum value.</param> /// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param> /// <param name = "max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static Int4 Clamp(Int4 value, Int4 min, Int4 max) public static Int4 Clamp( Int4 value, Int4 min, Int4 max )
{ {
Int4 result; Int4 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -401,12 +401,12 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <param name = "result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param> /// <param name = "result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param>
public static void Max(ref Int4 left, ref Int4 right, out Int4 result) public static void Max( ref Int4 left, ref Int4 right, out Int4 result )
{ {
result.X = (left.X > right.X) ? left.X : right.X; result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = (left.Y > right.Y) ? left.Y : right.Y; result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z; result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
result.W = (left.W > right.W) ? left.W : right.W; result.W = ( left.W > right.W ) ? left.W : right.W;
} }
/// <summary> /// <summary>
@ -415,10 +415,10 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <returns>A vector containing the largest components of the source vectors.</returns> /// <returns>A vector containing the largest components of the source vectors.</returns>
public static Int4 Max(Int4 left, Int4 right) public static Int4 Max( Int4 left, Int4 right )
{ {
Int4 result; Int4 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -428,12 +428,12 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <param name = "result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param> /// <param name = "result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param>
public static void Min(ref Int4 left, ref Int4 right, out Int4 result) public static void Min( ref Int4 left, ref Int4 right, out Int4 result )
{ {
result.X = (left.X < right.X) ? left.X : right.X; result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = (left.Y < right.Y) ? left.Y : right.Y; result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z; result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
result.W = (left.W < right.W) ? left.W : right.W; result.W = ( left.W < right.W ) ? left.W : right.W;
} }
/// <summary> /// <summary>
@ -442,10 +442,10 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <returns>A vector containing the smallest components of the source vectors.</returns> /// <returns>A vector containing the smallest components of the source vectors.</returns>
public static Int4 Min(Int4 left, Int4 right) public static Int4 Min( Int4 left, Int4 right )
{ {
Int4 result; Int4 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -455,9 +455,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static Int4 operator +(Int4 left, Int4 right) public static Int4 operator +( Int4 left, Int4 right )
{ {
return new Int4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); return new Int4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -465,7 +465,7 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The vector to assert (unchange).</param> /// <param name = "value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns> /// <returns>The asserted (unchanged) vector.</returns>
public static Int4 operator +(Int4 value) public static Int4 operator +( Int4 value )
{ {
return value; return value;
} }
@ -476,9 +476,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static Int4 operator -(Int4 left, Int4 right) public static Int4 operator -( Int4 left, Int4 right )
{ {
return new Int4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); return new Int4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -486,9 +486,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The vector to negate.</param> /// <param name = "value">The vector to negate.</param>
/// <returns>A vector facing in the opposite direction.</returns> /// <returns>A vector facing in the opposite direction.</returns>
public static Int4 operator -(Int4 value) public static Int4 operator -( Int4 value )
{ {
return new Int4(-value.X, -value.Y, -value.Z, -value.W); return new Int4( -value.X, -value.Y, -value.Z, -value.W );
} }
/// <summary> /// <summary>
@ -497,9 +497,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int4 operator *(int scale, Int4 value) public static Int4 operator *( int scale, Int4 value )
{ {
return new Int4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new Int4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -508,9 +508,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int4 operator *(Int4 value, int scale) public static Int4 operator *( Int4 value, int scale )
{ {
return new Int4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new Int4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -519,9 +519,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static Int4 operator /(Int4 value, int scale) public static Int4 operator /( Int4 value, int scale )
{ {
return new Int4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); return new Int4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -530,9 +530,9 @@ namespace math
/// <param name = "left">The first value to compare.</param> /// <param name = "left">The first value to compare.</param>
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Int4 left, Int4 right) public static bool operator ==( Int4 left, Int4 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -541,9 +541,9 @@ namespace math
/// <param name = "left">The first value to compare.</param> /// <param name = "left">The first value to compare.</param>
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator !=(Int4 left, Int4 right) public static bool operator !=( Int4 left, Int4 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -551,9 +551,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec2(Int4 value) public static explicit operator Vec2( Int4 value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
/// <summary> /// <summary>
@ -561,9 +561,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(Int4 value) public static explicit operator Vec3( Int4 value )
{ {
return new Vec3(value.X, value.Y, value.Z); return new Vec3( value.X, value.Y, value.Z );
} }
/// <summary> /// <summary>
@ -571,9 +571,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec4(Int4 value) public static explicit operator Vec4( Int4 value )
{ {
return new Vec4(value.X, value.Y, value.Z, value.W); return new Vec4( value.X, value.Y, value.Z, value.W );
} }
/// <summary> /// <summary>
@ -584,7 +584,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W );
} }
/// <summary> /// <summary>
@ -594,16 +594,16 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString(format, CultureInfo.CurrentCulture), X.ToString( format, CultureInfo.CurrentCulture ),
Y.ToString(format, CultureInfo.CurrentCulture), Y.ToString( format, CultureInfo.CurrentCulture ),
Z.ToString(format, CultureInfo.CurrentCulture), Z.ToString( format, CultureInfo.CurrentCulture ),
W.ToString(format, CultureInfo.CurrentCulture)); W.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -613,9 +613,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W); return string.Format( formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W );
} }
/// <summary> /// <summary>
@ -626,14 +626,14 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
ToString(formatProvider); ToString( formatProvider );
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X.ToString(format, formatProvider), return string.Format( formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X.ToString( format, formatProvider ),
Y.ToString(format, formatProvider), Z.ToString(format, formatProvider), Y.ToString( format, formatProvider ), Z.ToString( format, formatProvider ),
W.ToString(format, formatProvider)); W.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -654,7 +654,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref = "Int4" /> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref = "Int4" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Int4 other) public bool Equals( Int4 other )
{ {
return other.X == X && other.Y == Y && other.Z == Z && other.W == W; return other.X == X && other.Y == Y && other.Z == Z && other.W == W;
} }
@ -666,15 +666,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Int4)value); return Equals( (Int4)value );
} }
/// <summary> /// <summary>
@ -682,9 +682,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="input">The input.</param> /// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator Int4(int[] input) public static implicit operator Int4( int[] input )
{ {
return new Int4(input); return new Int4( input );
} }
/// <summary> /// <summary>
@ -692,7 +692,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="input">The input.</param> /// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator int[](Int4 input) public static implicit operator int[]( Int4 input )
{ {
return input.ToArray(); return input.ToArray();
} }

View File

@ -56,17 +56,17 @@ namespace math
/// <summary> /// <summary>
/// A value specifying the approximation of 2π which is 360 degrees. /// A value specifying the approximation of 2π which is 360 degrees.
/// </summary> /// </summary>
public const float TwoPi = (float)(2 * Math.PI); public const float TwoPi = (float)( 2 * Math.PI );
/// <summary> /// <summary>
/// A value specifying the approximation of π/2 which is 90 degrees. /// A value specifying the approximation of π/2 which is 90 degrees.
/// </summary> /// </summary>
public const float PiOverTwo = (float)(Math.PI / 2); public const float PiOverTwo = (float)( Math.PI / 2 );
/// <summary> /// <summary>
/// A value specifying the approximation of π/4 which is 45 degrees. /// A value specifying the approximation of π/4 which is 45 degrees.
/// </summary> /// </summary>
public const float PiOverFour = (float)(Math.PI / 4); public const float PiOverFour = (float)( Math.PI / 4 );
/// <summary> /// <summary>
/// Checks if a and b are almost equals, taking into account the magnitude of floating point numbers (unlike <see cref="WithinEpsilon"/> method). See Remarks. /// Checks if a and b are almost equals, taking into account the magnitude of floating point numbers (unlike <see cref="WithinEpsilon"/> method). See Remarks.
@ -79,11 +79,11 @@ namespace math
/// The code is using the technique described by Bruce Dawson in /// The code is using the technique described by Bruce Dawson in
/// <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">Comparing Floating point numbers 2012 edition</a>. /// <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">Comparing Floating point numbers 2012 edition</a>.
/// </remarks> /// </remarks>
public static unsafe bool NearEqual(float a, float b) public static unsafe bool NearEqual( float a, float b )
{ {
// Check if the numbers are really close -- needed // Check if the numbers are really close -- needed
// when comparing numbers near zero. // when comparing numbers near zero.
if (IsZero(a - b)) if( IsZero( a - b ) )
return true; return true;
// Original from Bruce Dawson: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ // Original from Bruce Dawson: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
@ -91,16 +91,16 @@ namespace math
int bInt = *(int*)&b; int bInt = *(int*)&b;
// Different signs means they do not match. // Different signs means they do not match.
if ((aInt < 0) != (bInt < 0)) if( ( aInt < 0 ) != ( bInt < 0 ) )
return false; return false;
// Find the difference in ULPs. // Find the difference in ULPs.
int ulp = Math.Abs(aInt - bInt); int ulp = Math.Abs( aInt - bInt );
// Choose of maxUlp = 4 // Choose of maxUlp = 4
// according to http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h // according to http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h
const int maxUlp = 4; const int maxUlp = 4;
return (ulp <= maxUlp); return ( ulp <= maxUlp );
} }
/// <summary> /// <summary>
@ -108,9 +108,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="a">The floating value.</param> /// <param name="a">The floating value.</param>
/// <returns><c>true</c> if the specified value is close to zero (0.0f); otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified value is close to zero (0.0f); otherwise, <c>false</c>.</returns>
public static bool IsZero(float a) public static bool IsZero( float a )
{ {
return Math.Abs(a) < ZeroTolerance; return Math.Abs( a ) < ZeroTolerance;
} }
/// <summary> /// <summary>
@ -118,9 +118,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="a">The floating value.</param> /// <param name="a">The floating value.</param>
/// <returns><c>true</c> if the specified value is close to zero (0.0f); otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified value is close to zero (0.0f); otherwise, <c>false</c>.</returns>
public static bool IsZero(double a) public static bool IsZero( double a )
{ {
return Math.Abs(a) < ZeroToleranceDouble; return Math.Abs( a ) < ZeroToleranceDouble;
} }
/// <summary> /// <summary>
@ -128,9 +128,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="a">The floating value.</param> /// <param name="a">The floating value.</param>
/// <returns><c>true</c> if the specified value is close to one (1.0f); otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified value is close to one (1.0f); otherwise, <c>false</c>.</returns>
public static bool IsOne(float a) public static bool IsOne( float a )
{ {
return IsZero(a - 1.0f); return IsZero( a - 1.0f );
} }
/// <summary> /// <summary>
@ -140,10 +140,10 @@ namespace math
/// <param name="b">The right value to compare.</param> /// <param name="b">The right value to compare.</param>
/// <param name="epsilon">Epsilon value</param> /// <param name="epsilon">Epsilon value</param>
/// <returns><c>true</c> if a almost equal to b within a float epsilon, <c>false</c> otherwise</returns> /// <returns><c>true</c> if a almost equal to b within a float epsilon, <c>false</c> otherwise</returns>
public static bool WithinEpsilon(float a, float b, float epsilon) public static bool WithinEpsilon( float a, float b, float epsilon )
{ {
float num = a - b; float num = a - b;
return ((-epsilon <= num) && (num <= epsilon)); return ( ( -epsilon <= num ) && ( num <= epsilon ) );
} }
/// <summary> /// <summary>
@ -153,10 +153,10 @@ namespace math
/// <param name="value">The value to fill the array with.</param> /// <param name="value">The value to fill the array with.</param>
/// <param name="length">The size of the array to create.</param> /// <param name="length">The size of the array to create.</param>
/// <returns>A new one-dimensional array of the specified type with the specified length and filled with the specified value.</returns> /// <returns>A new one-dimensional array of the specified type with the specified length and filled with the specified value.</returns>
public static T[] Array<T>(T value, int length) public static T[] Array<T>( T value, int length )
{ {
var result = new T[length]; var result = new T[length];
for (var i = 0; i < length; i++) for( var i = 0; i < length; i++ )
result[i] = value; result[i] = value;
return result; return result;
@ -167,7 +167,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="revolution">The value to convert.</param> /// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RevolutionsToDegrees(float revolution) public static float RevolutionsToDegrees( float revolution )
{ {
return revolution * 360.0f; return revolution * 360.0f;
} }
@ -177,7 +177,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="revolution">The value to convert.</param> /// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RevolutionsToRadians(float revolution) public static float RevolutionsToRadians( float revolution )
{ {
return revolution * TwoPi; return revolution * TwoPi;
} }
@ -187,7 +187,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="revolution">The value to convert.</param> /// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RevolutionsToGradians(float revolution) public static float RevolutionsToGradians( float revolution )
{ {
return revolution * 400.0f; return revolution * 400.0f;
} }
@ -197,7 +197,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="degree">The value to convert.</param> /// <param name="degree">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float DegreesToRevolutions(float degree) public static float DegreesToRevolutions( float degree )
{ {
return degree / 360.0f; return degree / 360.0f;
} }
@ -207,9 +207,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="degree">The value to convert.</param> /// <param name="degree">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float DegreesToRadians(float degree) public static float DegreesToRadians( float degree )
{ {
return degree * (Pi / 180.0f); return degree * ( Pi / 180.0f );
} }
/// <summary> /// <summary>
@ -217,7 +217,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="radian">The value to convert.</param> /// <param name="radian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RadiansToRevolutions(float radian) public static float RadiansToRevolutions( float radian )
{ {
return radian / TwoPi; return radian / TwoPi;
} }
@ -227,9 +227,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="radian">The value to convert.</param> /// <param name="radian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RadiansToGradians(float radian) public static float RadiansToGradians( float radian )
{ {
return radian * (200.0f / Pi); return radian * ( 200.0f / Pi );
} }
/// <summary> /// <summary>
@ -237,7 +237,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="gradian">The value to convert.</param> /// <param name="gradian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float GradiansToRevolutions(float gradian) public static float GradiansToRevolutions( float gradian )
{ {
return gradian / 400.0f; return gradian / 400.0f;
} }
@ -247,9 +247,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="gradian">The value to convert.</param> /// <param name="gradian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float GradiansToDegrees(float gradian) public static float GradiansToDegrees( float gradian )
{ {
return gradian * (9.0f / 10.0f); return gradian * ( 9.0f / 10.0f );
} }
/// <summary> /// <summary>
@ -257,9 +257,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="gradian">The value to convert.</param> /// <param name="gradian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float GradiansToRadians(float gradian) public static float GradiansToRadians( float gradian )
{ {
return gradian * (Pi / 200.0f); return gradian * ( Pi / 200.0f );
} }
/// <summary> /// <summary>
@ -267,9 +267,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="radian">The value to convert.</param> /// <param name="radian">The value to convert.</param>
/// <returns>The converted value.</returns> /// <returns>The converted value.</returns>
public static float RadiansToDegrees(float radian) public static float RadiansToDegrees( float radian )
{ {
return radian * (180.0f / Pi); return radian * ( 180.0f / Pi );
} }
/// <summary> /// <summary>
@ -279,7 +279,7 @@ namespace math
/// <param name="min">The min.</param> /// <param name="min">The min.</param>
/// <param name="max">The max.</param> /// <param name="max">The max.</param>
/// <returns>The result of clamping a value between min and max</returns> /// <returns>The result of clamping a value between min and max</returns>
public static float Clamp(float value, float min, float max) public static float Clamp( float value, float min, float max )
{ {
return value < min ? min : value > max ? max : value; return value < min ? min : value > max ? max : value;
} }
@ -291,7 +291,7 @@ namespace math
/// <param name="min">The min.</param> /// <param name="min">The min.</param>
/// <param name="max">The max.</param> /// <param name="max">The max.</param>
/// <returns>The result of clamping a value between min and max</returns> /// <returns>The result of clamping a value between min and max</returns>
public static double Clamp(double value, double min, double max) public static double Clamp( double value, double min, double max )
{ {
return value < min ? min : value > max ? max : value; return value < min ? min : value > max ? max : value;
} }
@ -303,7 +303,7 @@ namespace math
/// <param name="min">The min.</param> /// <param name="min">The min.</param>
/// <param name="max">The max.</param> /// <param name="max">The max.</param>
/// <returns>The result of clamping a value between min and max</returns> /// <returns>The result of clamping a value between min and max</returns>
public static int Clamp(int value, int min, int max) public static int Clamp( int value, int min, int max )
{ {
return value < min ? min : value > max ? max : value; return value < min ? min : value > max ? max : value;
} }
@ -315,11 +315,11 @@ namespace math
/// <param name="max">Maximum value that takes place in inverse-interpolation.</param> /// <param name="max">Maximum value that takes place in inverse-interpolation.</param>
/// <param name="value">Value to get inverse interpolation.</param> /// <param name="value">Value to get inverse interpolation.</param>
/// <returns>Returns an inverse-linearly interpolated coeficient.</returns> /// <returns>Returns an inverse-linearly interpolated coeficient.</returns>
public static float InverseLerp(float min, float max, float value) public static float InverseLerp( float min, float max, float value )
{ {
if (IsZero(Math.Abs(max - min))) if( IsZero( Math.Abs( max - min ) ) )
return float.NaN; return float.NaN;
return (value - min) / (max - min); return ( value - min ) / ( max - min );
} }
/// <summary> /// <summary>
@ -329,11 +329,11 @@ namespace math
/// <param name="max">Maximum value that takes place in inverse-interpolation.</param> /// <param name="max">Maximum value that takes place in inverse-interpolation.</param>
/// <param name="value">Value to get inverse interpolation.</param> /// <param name="value">Value to get inverse interpolation.</param>
/// <returns>Returns an inverse-linearly interpolated coeficient.</returns> /// <returns>Returns an inverse-linearly interpolated coeficient.</returns>
public static double InverseLerp(double min, double max, double value) public static double InverseLerp( double min, double max, double value )
{ {
if (IsZero(Math.Abs(max - min))) if( IsZero( Math.Abs( max - min ) ) )
return double.NaN; return double.NaN;
return (value - min) / (max - min); return ( value - min ) / ( max - min );
} }
/// <summary> /// <summary>
@ -347,9 +347,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param> /// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param> /// <param name="amount">Interpolation amount.</param>
/// <returns>The result of linear interpolation of values based on the amount.</returns> /// <returns>The result of linear interpolation of values based on the amount.</returns>
public static double Lerp(double from, double to, double amount) public static double Lerp( double from, double to, double amount )
{ {
return (1 - amount) * from + amount * to; return ( 1 - amount ) * from + amount * to;
} }
/// <summary> /// <summary>
@ -363,9 +363,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param> /// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param> /// <param name="amount">Interpolation amount.</param>
/// <returns>The result of linear interpolation of values based on the amount.</returns> /// <returns>The result of linear interpolation of values based on the amount.</returns>
public static float Lerp(float from, float to, float amount) public static float Lerp( float from, float to, float amount )
{ {
return (1 - amount) * from + amount * to; return ( 1 - amount ) * from + amount * to;
} }
/// <summary> /// <summary>
@ -379,9 +379,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param> /// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param> /// <param name="amount">Interpolation amount.</param>
/// <returns>The result of linear interpolation of values based on the amount.</returns> /// <returns>The result of linear interpolation of values based on the amount.</returns>
public static byte Lerp(byte from, byte to, float amount) public static byte Lerp( byte from, byte to, float amount )
{ {
return (byte)Lerp((float)from, (float)to, amount); return (byte)Lerp( (float)from, (float)to, amount );
} }
/// <summary> /// <summary>
@ -391,11 +391,11 @@ namespace math
/// See https://en.wikipedia.org/wiki/Smoothstep /// See https://en.wikipedia.org/wiki/Smoothstep
/// </remarks> /// </remarks>
/// <param name="amount">Value between 0 and 1 indicating interpolation amount.</param> /// <param name="amount">Value between 0 and 1 indicating interpolation amount.</param>
public static float SmoothStep(float amount) public static float SmoothStep( float amount )
{ {
return (amount <= 0) ? 0 return ( amount <= 0 ) ? 0
: (amount >= 1) ? 1 : ( amount >= 1 ) ? 1
: amount * amount * (3 - (2 * amount)); : amount * amount * ( 3 - ( 2 * amount ) );
} }
/// <summary> /// <summary>
@ -405,11 +405,11 @@ namespace math
/// See https://en.wikipedia.org/wiki/Smoothstep /// See https://en.wikipedia.org/wiki/Smoothstep
/// </remarks> /// </remarks>
/// <param name="amount">Value between 0 and 1 indicating interpolation amount.</param> /// <param name="amount">Value between 0 and 1 indicating interpolation amount.</param>
public static float SmootherStep(float amount) public static float SmootherStep( float amount )
{ {
return (amount <= 0) ? 0 return ( amount <= 0 ) ? 0
: (amount >= 1) ? 1 : ( amount >= 1 ) ? 1
: amount * amount * amount * (amount * ((amount * 6) - 15) + 10); : amount * amount * amount * ( amount * ( ( amount * 6 ) - 15 ) + 10 );
} }
/// <summary> /// <summary>
@ -419,7 +419,7 @@ namespace math
/// <param name="min">The minimum value of the range.</param> /// <param name="min">The minimum value of the range.</param>
/// <param name="max">The maximum value of the range.</param> /// <param name="max">The maximum value of the range.</param>
/// <returns><c>true</c> if value is inside the specified range; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if value is inside the specified range; otherwise, <c>false</c>.</returns>
public static bool IsInRange(float value, float min, float max) public static bool IsInRange( float value, float min, float max )
{ {
return min <= value && value <= max; return min <= value && value <= max;
} }
@ -431,7 +431,7 @@ namespace math
/// <param name="min">The minimum value of the range.</param> /// <param name="min">The minimum value of the range.</param>
/// <param name="max">The maximum value of the range.</param> /// <param name="max">The maximum value of the range.</param>
/// <returns><c>true</c> if value is inside the specified range; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if value is inside the specified range; otherwise, <c>false</c>.</returns>
public static bool IsInRange(int value, int min, int max) public static bool IsInRange( int value, int min, int max )
{ {
return min <= value && value <= max; return min <= value && value <= max;
} }
@ -441,9 +441,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="x">The x.</param> /// <param name="x">The x.</param>
/// <returns><c>true</c> if the specified x is pow2; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified x is pow2; otherwise, <c>false</c>.</returns>
public static bool IsPow2(int x) public static bool IsPow2( int x )
{ {
return ((x != 0) && (x & (x - 1)) == 0); return ( ( x != 0 ) && ( x & ( x - 1 ) ) == 0 );
} }
/// <summary> /// <summary>
@ -451,10 +451,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="sRgbValue">The sRGB value.</param> /// <param name="sRgbValue">The sRGB value.</param>
/// <returns>A linear value.</returns> /// <returns>A linear value.</returns>
public static float SRgbToLinear(float sRgbValue) public static float SRgbToLinear( float sRgbValue )
{ {
if (sRgbValue < 0.04045f) return sRgbValue / 12.92f; if( sRgbValue < 0.04045f )
return (float)Math.Pow((sRgbValue + 0.055) / 1.055, 2.4); return sRgbValue / 12.92f;
return (float)Math.Pow( ( sRgbValue + 0.055 ) / 1.055, 2.4 );
} }
/// <summary> /// <summary>
@ -462,10 +463,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="linearValue">The linear value.</param> /// <param name="linearValue">The linear value.</param>
/// <returns>The encoded sRGB value.</returns> /// <returns>The encoded sRGB value.</returns>
public static float LinearToSRgb(float linearValue) public static float LinearToSRgb( float linearValue )
{ {
if (linearValue < 0.0031308f) return linearValue * 12.92f; if( linearValue < 0.0031308f )
return (float)(1.055 * Math.Pow(linearValue, 1 / 2.4) - 0.055); return linearValue * 12.92f;
return (float)( 1.055 * Math.Pow( linearValue, 1 / 2.4 ) - 0.055 );
} }
/// <summary> /// <summary>
@ -473,9 +475,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="x">The input float</param> /// <param name="x">The input float</param>
/// <returns><value>Log2(x)</value></returns> /// <returns><value>Log2(x)</value></returns>
public static float Log2(float x) public static float Log2( float x )
{ {
return (float)Math.Log(x) / 0.6931471805599453f; return (float)Math.Log( x ) / 0.6931471805599453f;
} }
/// <summary> /// <summary>
@ -483,11 +485,11 @@ namespace math
/// </summary> /// </summary>
/// <param name="i">The input integer</param> /// <param name="i">The input integer</param>
/// <returns><value>the log2(i) rounded to lower integer</value></returns> /// <returns><value>the log2(i) rounded to lower integer</value></returns>
public static int Log2(int i) public static int Log2( int i )
{ {
var r = 0; var r = 0;
while ((i >>= 1) != 0) while( ( i >>= 1 ) != 0 )
++r; ++r;
return r; return r;
@ -499,9 +501,9 @@ namespace math
/// <param name="x">The size.</param> /// <param name="x">The size.</param>
/// <returns>System.Int32.</returns> /// <returns>System.Int32.</returns>
/// <remarks>https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2</remarks> /// <remarks>https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2</remarks>
public static int NextPowerOfTwo(int x) public static int NextPowerOfTwo( int x )
{ {
if (x < 0) if( x < 0 )
return 0; return 0;
x--; x--;
@ -518,27 +520,27 @@ namespace math
/// </summary> /// </summary>
/// <param name="size">The size.</param> /// <param name="size">The size.</param>
/// <returns>System.Int32.</returns> /// <returns>System.Int32.</returns>
public static float NextPowerOfTwo(float size) public static float NextPowerOfTwo( float size )
{ {
return (float)Math.Pow(2, Math.Ceiling(Math.Log(size, 2))); return (float)Math.Pow( 2, Math.Ceiling( Math.Log( size, 2 ) ) );
} }
/// <summary> /// <summary>
/// Get the previous power of two of the provided integer. /// Get the previous power of two of the provided integer.
/// </summary> /// </summary>
/// <param name="size">The value</param> /// <param name="size">The value</param>
public static int PreviousPowerOfTwo(int size) public static int PreviousPowerOfTwo( int size )
{ {
return 1 << (int)Math.Floor(Math.Log(size, 2)); return 1 << (int)Math.Floor( Math.Log( size, 2 ) );
} }
/// <summary> /// <summary>
/// Get the previous power of two of the provided float. /// Get the previous power of two of the provided float.
/// </summary> /// </summary>
/// <param name="size">The value</param> /// <param name="size">The value</param>
public static float PreviousPowerOfTwo(float size) public static float PreviousPowerOfTwo( float size )
{ {
return (float)Math.Pow(2, Math.Floor(Math.Log(size, 2))); return (float)Math.Pow( 2, Math.Floor( Math.Log( size, 2 ) ) );
} }
/// <summary> /// <summary>
@ -547,11 +549,11 @@ namespace math
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param> /// <param name="alignment">The alignment.</param>
/// <returns>Aligned value (multiple of alignment).</returns> /// <returns>Aligned value (multiple of alignment).</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int AlignUp(int value, int alignment) public static int AlignUp( int value, int alignment )
{ {
int mask = alignment - 1; int mask = alignment - 1;
return (value + mask) & ~mask; return ( value + mask ) & ~mask;
} }
/// <summary> /// <summary>
@ -560,8 +562,8 @@ namespace math
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param> /// <param name="alignment">The alignment.</param>
/// <returns>Aligned value (multiple of alignment).</returns> /// <returns>Aligned value (multiple of alignment).</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int AlignDown(int value, int alignment) public static int AlignDown( int value, int alignment )
{ {
int mask = alignment - 1; int mask = alignment - 1;
return value & ~mask; return value & ~mask;
@ -573,10 +575,10 @@ namespace math
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param> /// <param name="alignment">The alignment.</param>
/// <returns><c>true</c> if the specified value is aligned; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified value is aligned; otherwise, <c>false</c>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool IsAligned(int value, int alignment) public static bool IsAligned( int value, int alignment )
{ {
return (value & (alignment - 1)) == 0; return ( value & ( alignment - 1 ) ) == 0;
} }
/// <summary> /// <summary>
@ -585,11 +587,11 @@ namespace math
/// <param name="value">The value to snap.</param> /// <param name="value">The value to snap.</param>
/// <param name="gap">The interval gap.</param> /// <param name="gap">The interval gap.</param>
/// <returns>The nearest interval to the provided value.</returns> /// <returns>The nearest interval to the provided value.</returns>
public static float Snap(float value, float gap) public static float Snap( float value, float gap )
{ {
if (gap == 0) if( gap == 0 )
return value; return value;
return (float)Math.Round((value / gap), MidpointRounding.AwayFromZero) * gap; return (float)Math.Round( ( value / gap ), MidpointRounding.AwayFromZero ) * gap;
} }
/// <summary> /// <summary>
@ -598,11 +600,11 @@ namespace math
/// <param name="value">The value to snap.</param> /// <param name="value">The value to snap.</param>
/// <param name="gap">The interval gap.</param> /// <param name="gap">The interval gap.</param>
/// <returns>The nearest interval to the provided value.</returns> /// <returns>The nearest interval to the provided value.</returns>
public static double Snap(double value, double gap) public static double Snap( double value, double gap )
{ {
if (gap == 0) if( gap == 0 )
return value; return value;
return Math.Round((value / gap), MidpointRounding.AwayFromZero) * gap; return Math.Round( ( value / gap ), MidpointRounding.AwayFromZero ) * gap;
} }
/// <summary> /// <summary>
@ -611,13 +613,13 @@ namespace math
/// <param name="value">The vector to snap.</param> /// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param> /// <param name="gap">The interval gap.</param>
/// <returns>A vector which components are snapped to the nearest interval.</returns> /// <returns>A vector which components are snapped to the nearest interval.</returns>
public static Vec2 Snap(Vec2 value, float gap) public static Vec2 Snap( Vec2 value, float gap )
{ {
if (gap == 0) if( gap == 0 )
return value; return value;
return new Vec2( return new Vec2(
(float)Math.Round((value.X / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.X / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.Y / gap), MidpointRounding.AwayFromZero) * gap); (float)Math.Round( ( value.Y / gap ), MidpointRounding.AwayFromZero ) * gap );
} }
/// <summary> /// <summary>
@ -626,14 +628,14 @@ namespace math
/// <param name="value">The vector to snap.</param> /// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param> /// <param name="gap">The interval gap.</param>
/// <returns>A vector which components are snapped to the nearest interval.</returns> /// <returns>A vector which components are snapped to the nearest interval.</returns>
public static Vec3 Snap(Vec3 value, float gap) public static Vec3 Snap( Vec3 value, float gap )
{ {
if (gap == 0) if( gap == 0 )
return value; return value;
return new Vec3( return new Vec3(
(float)Math.Round((value.X / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.X / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.Y / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.Y / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.Z / gap), MidpointRounding.AwayFromZero) * gap); (float)Math.Round( ( value.Z / gap ), MidpointRounding.AwayFromZero ) * gap );
} }
/// <summary> /// <summary>
@ -642,15 +644,15 @@ namespace math
/// <param name="value">The vector to snap.</param> /// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param> /// <param name="gap">The interval gap.</param>
/// <returns>A vector which components are snapped to the nearest interval.</returns> /// <returns>A vector which components are snapped to the nearest interval.</returns>
public static Vec4 Snap(Vec4 value, float gap) public static Vec4 Snap( Vec4 value, float gap )
{ {
if (gap == 0) if( gap == 0 )
return value; return value;
return new Vec4( return new Vec4(
(float)Math.Round((value.X / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.X / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.Y / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.Y / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.Z / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round( ( value.Z / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round((value.W / gap), MidpointRounding.AwayFromZero) * gap); (float)Math.Round( ( value.W / gap ), MidpointRounding.AwayFromZero ) * gap );
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,7 @@ namespace math
/// Represents a plane in three dimensional space. /// Represents a plane in three dimensional space.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Plane : IEquatable<Plane>, IFormattable public struct Plane : IEquatable<Plane>, IFormattable
{ {
/// <summary> /// <summary>
@ -54,7 +54,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Plane"/> struct. /// Initializes a new instance of the <see cref="math.Plane"/> struct.
/// </summary> /// </summary>
/// <param name="value">The value that will be assigned to all components.</param> /// <param name="value">The value that will be assigned to all components.</param>
public Plane(float value) public Plane( float value )
{ {
Normal.X = Normal.Y = Normal.Z = D = value; Normal.X = Normal.Y = Normal.Z = D = value;
} }
@ -66,7 +66,7 @@ namespace math
/// <param name="b">The Y component of the normal.</param> /// <param name="b">The Y component of the normal.</param>
/// <param name="c">The Z component of the normal.</param> /// <param name="c">The Z component of the normal.</param>
/// <param name="d">The distance of the plane along its normal from the origin.</param> /// <param name="d">The distance of the plane along its normal from the origin.</param>
public Plane(float a, float b, float c, float d) public Plane( float a, float b, float c, float d )
{ {
Normal.X = a; Normal.X = a;
Normal.Y = b; Normal.Y = b;
@ -79,10 +79,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">Any point that lies along the plane.</param> /// <param name="point">Any point that lies along the plane.</param>
/// <param name="normal">The normal vector to the plane.</param> /// <param name="normal">The normal vector to the plane.</param>
public Plane(Vec3 point, Vec3 normal) public Plane( Vec3 point, Vec3 normal )
{ {
this.Normal = normal; this.Normal = normal;
this.D = Vec3.Dot(normal, point); this.D = Vec3.Dot( normal, point );
} }
/// <summary> /// <summary>
@ -90,7 +90,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The normal of the plane.</param> /// <param name="value">The normal of the plane.</param>
/// <param name="d">The distance of the plane along its normal from the origin</param> /// <param name="d">The distance of the plane along its normal from the origin</param>
public Plane(Vec3 value, float d) public Plane( Vec3 value, float d )
{ {
Normal = value; Normal = value;
D = d; D = d;
@ -102,7 +102,7 @@ namespace math
/// <param name="point1">First point of a triangle defining the plane.</param> /// <param name="point1">First point of a triangle defining the plane.</param>
/// <param name="point2">Second point of a triangle defining the plane.</param> /// <param name="point2">Second point of a triangle defining the plane.</param>
/// <param name="point3">Third point of a triangle defining the plane.</param> /// <param name="point3">Third point of a triangle defining the plane.</param>
public Plane(Vec3 point1, Vec3 point2, Vec3 point3) public Plane( Vec3 point1, Vec3 point2, Vec3 point3 )
{ {
float x1 = point2.X - point1.X; float x1 = point2.X - point1.X;
float y1 = point2.Y - point1.Y; float y1 = point2.Y - point1.Y;
@ -110,15 +110,15 @@ namespace math
float x2 = point3.X - point1.X; float x2 = point3.X - point1.X;
float y2 = point3.Y - point1.Y; float y2 = point3.Y - point1.Y;
float z2 = point3.Z - point1.Z; float z2 = point3.Z - point1.Z;
float yz = (y1 * z2) - (z1 * y2); float yz = ( y1 * z2 ) - ( z1 * y2 );
float xz = (z1 * x2) - (x1 * z2); float xz = ( z1 * x2 ) - ( x1 * z2 );
float xy = (x1 * y2) - (y1 * x2); float xy = ( x1 * y2 ) - ( y1 * x2 );
float invPyth = 1.0f / (float)(Math.Sqrt((yz * yz) + (xz * xz) + (xy * xy))); float invPyth = 1.0f / (float)( Math.Sqrt( ( yz * yz ) + ( xz * xz ) + ( xy * xy ) ) );
Normal.X = yz * invPyth; Normal.X = yz * invPyth;
Normal.Y = xz * invPyth; Normal.Y = xz * invPyth;
Normal.Z = xy * invPyth; Normal.Z = xy * invPyth;
D = -((Normal.X * point1.X) + (Normal.Y * point1.Y) + (Normal.Z * point1.Z)); D = -( ( Normal.X * point1.X ) + ( Normal.Y * point1.Y ) + ( Normal.Z * point1.Z ) );
} }
/// <summary> /// <summary>
@ -127,12 +127,12 @@ namespace math
/// <param name="values">The values to assign to the A, B, C, and D components of the plane. This must be an array with four elements.</param> /// <param name="values">The values to assign to the A, B, C, and D components of the plane. This must be an array with four elements.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="values"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="values"/> contains more or less than four elements.</exception>
public Plane(float[] values) public Plane( float[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException("values"); throw new ArgumentNullException( "values" );
if (values.Length != 4) if( values.Length != 4 )
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for Plane."); throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for Plane." );
Normal.X = values[0]; Normal.X = values[0];
Normal.Y = values[1]; Normal.Y = values[1];
@ -151,26 +151,39 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: return Normal.X; case 0:
case 1: return Normal.Y; return Normal.X;
case 2: return Normal.Z; case 1:
case 3: return D; return Normal.Y;
case 2:
return Normal.Z;
case 3:
return D;
} }
throw new ArgumentOutOfRangeException("index", "Indices for Plane run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for Plane run from 0 to 3, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: Normal.X = value; break; case 0:
case 1: Normal.Y = value; break; Normal.X = value;
case 2: Normal.Z = value; break; break;
case 3: D = value; break; case 1:
default: throw new ArgumentOutOfRangeException("index", "Indices for Plane run from 0 to 3, inclusive."); Normal.Y = value;
break;
case 2:
Normal.Z = value;
break;
case 3:
D = value;
break;
default:
throw new ArgumentOutOfRangeException( "index", "Indices for Plane run from 0 to 3, inclusive." );
} }
} }
} }
@ -191,7 +204,7 @@ namespace math
/// </summary> /// </summary>
public void Normalize() public void Normalize()
{ {
float magnitude = 1.0f / (float)(Math.Sqrt((Normal.X * Normal.X) + (Normal.Y * Normal.Y) + (Normal.Z * Normal.Z))); float magnitude = 1.0f / (float)( Math.Sqrt( ( Normal.X * Normal.X ) + ( Normal.Y * Normal.Y ) + ( Normal.Z * Normal.Z ) ) );
Normal.X *= magnitude; Normal.X *= magnitude;
Normal.Y *= magnitude; Normal.Y *= magnitude;
@ -213,9 +226,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">The point to test.</param> /// <param name="point">The point to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref Vec3 point) public PlaneIntersectionType Intersects( ref Vec3 point )
{ {
return CollisionHelper.PlaneIntersectsPoint(ref this, ref point); return CollisionHelper.PlaneIntersectsPoint( ref this, ref point );
} }
/// <summary> /// <summary>
@ -223,10 +236,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="ray">The ray to test.</param> /// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray) public bool Intersects( ref Ray ray )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsPlane(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsPlane( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -236,9 +249,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out float distance) public bool Intersects( ref Ray ray, out float distance )
{ {
return CollisionHelper.RayIntersectsPlane(ref ray, ref this, out distance); return CollisionHelper.RayIntersectsPlane( ref ray, ref this, out distance );
} }
/// <summary> /// <summary>
@ -248,9 +261,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out Vec3 point) public bool Intersects( ref Ray ray, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsPlane(ref ray, ref this, out point); return CollisionHelper.RayIntersectsPlane( ref ray, ref this, out point );
} }
/// <summary> /// <summary>
@ -258,9 +271,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The plane to test.</param> /// <param name="plane">The plane to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane) public bool Intersects( ref Plane plane )
{ {
return CollisionHelper.PlaneIntersectsPlane(ref this, ref plane); return CollisionHelper.PlaneIntersectsPlane( ref this, ref plane );
} }
/// <summary> /// <summary>
@ -270,9 +283,9 @@ namespace math
/// <param name="line">When the method completes, contains the line of intersection /// <param name="line">When the method completes, contains the line of intersection
/// as a <see cref="math.Ray"/>, or a zero ray if there was no intersection.</param> /// as a <see cref="math.Ray"/>, or a zero ray if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane, out Ray line) public bool Intersects( ref Plane plane, out Ray line )
{ {
return CollisionHelper.PlaneIntersectsPlane(ref this, ref plane, out line); return CollisionHelper.PlaneIntersectsPlane( ref this, ref plane, out line );
} }
/// <summary> /// <summary>
@ -282,9 +295,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle to test.</param> /// <param name="vertex2">The second vertex of the triagnle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param> /// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3) public PlaneIntersectionType Intersects( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3 )
{ {
return CollisionHelper.PlaneIntersectsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3); return CollisionHelper.PlaneIntersectsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3 );
} }
/// <summary> /// <summary>
@ -292,9 +305,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref BoundingBox box) public PlaneIntersectionType Intersects( ref BoundingBox box )
{ {
return CollisionHelper.PlaneIntersectsBox(ref this, ref box); return CollisionHelper.PlaneIntersectsBox( ref this, ref box );
} }
/// <summary> /// <summary>
@ -302,9 +315,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public PlaneIntersectionType Intersects(ref BoundingSphere sphere) public PlaneIntersectionType Intersects( ref BoundingSphere sphere )
{ {
return CollisionHelper.PlaneIntersectsSphere(ref this, ref sphere); return CollisionHelper.PlaneIntersectsSphere( ref this, ref sphere );
} }
/// <summary> /// <summary>
@ -313,7 +326,7 @@ namespace math
/// <param name="value">The plane to scale.</param> /// <param name="value">The plane to scale.</param>
/// <param name="scale">The amount by which to scale the plane.</param> /// <param name="scale">The amount by which to scale the plane.</param>
/// <param name="result">When the method completes, contains the scaled plane.</param> /// <param name="result">When the method completes, contains the scaled plane.</param>
public static void Multiply(ref Plane value, float scale, out Plane result) public static void Multiply( ref Plane value, float scale, out Plane result )
{ {
result.Normal.X = value.Normal.X * scale; result.Normal.X = value.Normal.X * scale;
result.Normal.Y = value.Normal.Y * scale; result.Normal.Y = value.Normal.Y * scale;
@ -327,9 +340,9 @@ namespace math
/// <param name="value">The plane to scale.</param> /// <param name="value">The plane to scale.</param>
/// <param name="scale">The amount by which to scale the plane.</param> /// <param name="scale">The amount by which to scale the plane.</param>
/// <returns>The scaled plane.</returns> /// <returns>The scaled plane.</returns>
public static Plane Multiply(Plane value, float scale) public static Plane Multiply( Plane value, float scale )
{ {
return new Plane(value.Normal.X * scale, value.Normal.Y * scale, value.Normal.Z * scale, value.D * scale); return new Plane( value.Normal.X * scale, value.Normal.Y * scale, value.Normal.Z * scale, value.D * scale );
} }
/// <summary> /// <summary>
@ -338,9 +351,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <param name="result">When the method completes, contains the dot product of the specified plane and vector.</param> /// <param name="result">When the method completes, contains the dot product of the specified plane and vector.</param>
public static void Dot(ref Plane left, ref Vec4 right, out float result) public static void Dot( ref Plane left, ref Vec4 right, out float result )
{ {
result = (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z) + (left.D * right.W); result = ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z ) + ( left.D * right.W );
} }
/// <summary> /// <summary>
@ -349,9 +362,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <returns>The dot product of the specified plane and vector.</returns> /// <returns>The dot product of the specified plane and vector.</returns>
public static float Dot(Plane left, Vec4 right) public static float Dot( Plane left, Vec4 right )
{ {
return (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z) + (left.D * right.W); return ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z ) + ( left.D * right.W );
} }
/// <summary> /// <summary>
@ -360,9 +373,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <param name="result">When the method completes, contains the dot product of a specified vector and the normal of the Plane plus the distance value of the plane.</param> /// <param name="result">When the method completes, contains the dot product of a specified vector and the normal of the Plane plus the distance value of the plane.</param>
public static void DotCoordinate(ref Plane left, ref Vec3 right, out float result) public static void DotCoordinate( ref Plane left, ref Vec3 right, out float result )
{ {
result = (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z) + left.D; result = ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z ) + left.D;
} }
/// <summary> /// <summary>
@ -371,9 +384,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <returns>The dot product of a specified vector and the normal of the Plane plus the distance value of the plane.</returns> /// <returns>The dot product of a specified vector and the normal of the Plane plus the distance value of the plane.</returns>
public static float DotCoordinate(Plane left, Vec3 right) public static float DotCoordinate( Plane left, Vec3 right )
{ {
return (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z) + left.D; return ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z ) + left.D;
} }
/// <summary> /// <summary>
@ -382,9 +395,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <param name="result">When the method completes, contains the dot product of the specified vector and the normal of the plane.</param> /// <param name="result">When the method completes, contains the dot product of the specified vector and the normal of the plane.</param>
public static void DotNormal(ref Plane left, ref Vec3 right, out float result) public static void DotNormal( ref Plane left, ref Vec3 right, out float result )
{ {
result = (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z); result = ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z );
} }
/// <summary> /// <summary>
@ -393,9 +406,9 @@ namespace math
/// <param name="left">The source plane.</param> /// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param> /// <param name="right">The source vector.</param>
/// <returns>The dot product of the specified vector and the normal of the plane.</returns> /// <returns>The dot product of the specified vector and the normal of the plane.</returns>
public static float DotNormal(Plane left, Vec3 right) public static float DotNormal( Plane left, Vec3 right )
{ {
return (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z); return ( left.Normal.X * right.X ) + ( left.Normal.Y * right.Y ) + ( left.Normal.Z * right.Z );
} }
/// <summary> /// <summary>
@ -404,14 +417,14 @@ namespace math
/// <param name="plane">The plane to project the point to.</param> /// <param name="plane">The plane to project the point to.</param>
/// <param name="point">The point to project.</param> /// <param name="point">The point to project.</param>
/// <param name="result">The projected point.</param> /// <param name="result">The projected point.</param>
public static void Project(ref Plane plane, ref Vec3 point, out Vec3 result) public static void Project( ref Plane plane, ref Vec3 point, out Vec3 result )
{ {
float distance; float distance;
DotCoordinate(ref plane, ref point, out distance); DotCoordinate( ref plane, ref point, out distance );
// compute: point - distance * plane.Normal // compute: point - distance * plane.Normal
Vec3.Multiply(ref plane.Normal, distance, out result); Vec3.Multiply( ref plane.Normal, distance, out result );
Vec3.Subtract(ref point, ref result, out result); Vec3.Subtract( ref point, ref result, out result );
} }
/// <summary> /// <summary>
@ -420,10 +433,10 @@ namespace math
/// <param name="plane">The plane to project the point to.</param> /// <param name="plane">The plane to project the point to.</param>
/// <param name="point">The point to project.</param> /// <param name="point">The point to project.</param>
/// <returns>The projected point.</returns> /// <returns>The projected point.</returns>
public static Vec3 Project(Plane plane, Vec3 point) public static Vec3 Project( Plane plane, Vec3 point )
{ {
Vec3 result; Vec3 result;
Project(ref plane, ref point, out result); Project( ref plane, ref point, out result );
return result; return result;
} }
@ -432,9 +445,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The source plane.</param> /// <param name="plane">The source plane.</param>
/// <param name="result">When the method completes, contains the normalized plane.</param> /// <param name="result">When the method completes, contains the normalized plane.</param>
public static void Normalize(ref Plane plane, out Plane result) public static void Normalize( ref Plane plane, out Plane result )
{ {
float magnitude = 1.0f / (float)(Math.Sqrt((plane.Normal.X * plane.Normal.X) + (plane.Normal.Y * plane.Normal.Y) + (plane.Normal.Z * plane.Normal.Z))); float magnitude = 1.0f / (float)( Math.Sqrt( ( plane.Normal.X * plane.Normal.X ) + ( plane.Normal.Y * plane.Normal.Y ) + ( plane.Normal.Z * plane.Normal.Z ) ) );
result.Normal.X = plane.Normal.X * magnitude; result.Normal.X = plane.Normal.X * magnitude;
result.Normal.Y = plane.Normal.Y * magnitude; result.Normal.Y = plane.Normal.Y * magnitude;
@ -447,10 +460,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The source plane.</param> /// <param name="plane">The source plane.</param>
/// <returns>The normalized plane.</returns> /// <returns>The normalized plane.</returns>
public static Plane Normalize(Plane plane) public static Plane Normalize( Plane plane )
{ {
float magnitude = 1.0f / (float)(Math.Sqrt((plane.Normal.X * plane.Normal.X) + (plane.Normal.Y * plane.Normal.Y) + (plane.Normal.Z * plane.Normal.Z))); float magnitude = 1.0f / (float)( Math.Sqrt( ( plane.Normal.X * plane.Normal.X ) + ( plane.Normal.Y * plane.Normal.Y ) + ( plane.Normal.Z * plane.Normal.Z ) ) );
return new Plane(plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude); return new Plane( plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude );
} }
/// <summary> /// <summary>
@ -458,7 +471,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The source plane.</param> /// <param name="plane">The source plane.</param>
/// <param name="result">When the method completes, contains the flipped plane.</param> /// <param name="result">When the method completes, contains the flipped plane.</param>
public static void Negate(ref Plane plane, out Plane result) public static void Negate( ref Plane plane, out Plane result )
{ {
result.Normal.X = -plane.Normal.X; result.Normal.X = -plane.Normal.X;
result.Normal.Y = -plane.Normal.Y; result.Normal.Y = -plane.Normal.Y;
@ -471,10 +484,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The source plane.</param> /// <param name="plane">The source plane.</param>
/// <returns>The flipped plane.</returns> /// <returns>The flipped plane.</returns>
public static Plane Negate(Plane plane) public static Plane Negate( Plane plane )
{ {
float magnitude = 1.0f / (float)(Math.Sqrt((plane.Normal.X * plane.Normal.X) + (plane.Normal.Y * plane.Normal.Y) + (plane.Normal.Z * plane.Normal.Z))); float magnitude = 1.0f / (float)( Math.Sqrt( ( plane.Normal.X * plane.Normal.X ) + ( plane.Normal.Y * plane.Normal.Y ) + ( plane.Normal.Z * plane.Normal.Z ) ) );
return new Plane(plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude); return new Plane( plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude );
} }
/// <summary> /// <summary>
@ -483,7 +496,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param> /// <param name="plane">The normalized source plane.</param>
/// <param name="rotation">The quaternion rotation.</param> /// <param name="rotation">The quaternion rotation.</param>
/// <param name="result">When the method completes, contains the transformed plane.</param> /// <param name="result">When the method completes, contains the transformed plane.</param>
public static void Transform(ref Plane plane, ref Quaternion rotation, out Plane result) public static void Transform( ref Plane plane, ref Quaternion rotation, out Plane result )
{ {
float x2 = rotation.X + rotation.X; float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y; float y2 = rotation.Y + rotation.Y;
@ -502,9 +515,9 @@ namespace math
float y = plane.Normal.Y; float y = plane.Normal.Y;
float z = plane.Normal.Z; float z = plane.Normal.Z;
result.Normal.X = ((x * ((1.0f - yy) - zz)) + (y * (xy - wz))) + (z * (xz + wy)); result.Normal.X = ( ( x * ( ( 1.0f - yy ) - zz ) ) + ( y * ( xy - wz ) ) ) + ( z * ( xz + wy ) );
result.Normal.Y = ((x * (xy + wz)) + (y * ((1.0f - xx) - zz))) + (z * (yz - wx)); result.Normal.Y = ( ( x * ( xy + wz ) ) + ( y * ( ( 1.0f - xx ) - zz ) ) ) + ( z * ( yz - wx ) );
result.Normal.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy)); result.Normal.Z = ( ( x * ( xz - wy ) ) + ( y * ( yz + wx ) ) ) + ( z * ( ( 1.0f - xx ) - yy ) );
result.D = plane.D; result.D = plane.D;
} }
@ -514,7 +527,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param> /// <param name="plane">The normalized source plane.</param>
/// <param name="rotation">The quaternion rotation.</param> /// <param name="rotation">The quaternion rotation.</param>
/// <returns>The transformed plane.</returns> /// <returns>The transformed plane.</returns>
public static Plane Transform(Plane plane, Quaternion rotation) public static Plane Transform( Plane plane, Quaternion rotation )
{ {
Plane result; Plane result;
float x2 = rotation.X + rotation.X; float x2 = rotation.X + rotation.X;
@ -534,9 +547,9 @@ namespace math
float y = plane.Normal.Y; float y = plane.Normal.Y;
float z = plane.Normal.Z; float z = plane.Normal.Z;
result.Normal.X = ((x * ((1.0f - yy) - zz)) + (y * (xy - wz))) + (z * (xz + wy)); result.Normal.X = ( ( x * ( ( 1.0f - yy ) - zz ) ) + ( y * ( xy - wz ) ) ) + ( z * ( xz + wy ) );
result.Normal.Y = ((x * (xy + wz)) + (y * ((1.0f - xx) - zz))) + (z * (yz - wx)); result.Normal.Y = ( ( x * ( xy + wz ) ) + ( y * ( ( 1.0f - xx ) - zz ) ) ) + ( z * ( yz - wx ) );
result.Normal.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy)); result.Normal.Z = ( ( x * ( xz - wy ) ) + ( y * ( yz + wx ) ) ) + ( z * ( ( 1.0f - xx ) - yy ) );
result.D = plane.D; result.D = plane.D;
return result; return result;
@ -548,10 +561,10 @@ namespace math
/// <param name="planes">The array of normalized planes to transform.</param> /// <param name="planes">The array of normalized planes to transform.</param>
/// <param name="rotation">The quaternion rotation.</param> /// <param name="rotation">The quaternion rotation.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="planes"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="planes"/> is <c>null</c>.</exception>
public static void Transform(Plane[] planes, ref Quaternion rotation) public static void Transform( Plane[] planes, ref Quaternion rotation )
{ {
if (planes == null) if( planes == null )
throw new ArgumentNullException("planes"); throw new ArgumentNullException( "planes" );
float x2 = rotation.X + rotation.X; float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y; float y2 = rotation.Y + rotation.Y;
@ -566,7 +579,7 @@ namespace math
float yz = rotation.Y * z2; float yz = rotation.Y * z2;
float zz = rotation.Z * z2; float zz = rotation.Z * z2;
for (int i = 0; i < planes.Length; ++i) for( int i = 0; i < planes.Length; ++i )
{ {
float x = planes[i].Normal.X; float x = planes[i].Normal.X;
float y = planes[i].Normal.Y; float y = planes[i].Normal.Y;
@ -576,9 +589,9 @@ namespace math
* Note: * Note:
* Factor common arithmetic out of loop. * Factor common arithmetic out of loop.
*/ */
planes[i].Normal.X = ((x * ((1.0f - yy) - zz)) + (y * (xy - wz))) + (z * (xz + wy)); planes[i].Normal.X = ( ( x * ( ( 1.0f - yy ) - zz ) ) + ( y * ( xy - wz ) ) ) + ( z * ( xz + wy ) );
planes[i].Normal.Y = ((x * (xy + wz)) + (y * ((1.0f - xx) - zz))) + (z * (yz - wx)); planes[i].Normal.Y = ( ( x * ( xy + wz ) ) + ( y * ( ( 1.0f - xx ) - zz ) ) ) + ( z * ( yz - wx ) );
planes[i].Normal.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy)); planes[i].Normal.Z = ( ( x * ( xz - wy ) ) + ( y * ( yz + wx ) ) ) + ( z * ( ( 1.0f - xx ) - yy ) );
} }
} }
@ -588,7 +601,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param> /// <param name="plane">The normalized source plane.</param>
/// <param name="transformation">The transformation matrix.</param> /// <param name="transformation">The transformation matrix.</param>
/// <param name="result">When the method completes, contains the transformed plane.</param> /// <param name="result">When the method completes, contains the transformed plane.</param>
public static void Transform(ref Plane plane, ref Matrix transformation, out Plane result) public static void Transform( ref Plane plane, ref Matrix transformation, out Plane result )
{ {
float x = plane.Normal.X; float x = plane.Normal.X;
float y = plane.Normal.Y; float y = plane.Normal.Y;
@ -596,12 +609,12 @@ namespace math
float d = plane.D; float d = plane.D;
Matrix inverse; Matrix inverse;
Matrix.Invert(ref transformation, out inverse); Matrix.Invert( ref transformation, out inverse );
result.Normal.X = (((x * inverse.M11) + (y * inverse.M12)) + (z * inverse.M13)) + (d * inverse.M14); result.Normal.X = ( ( ( x * inverse.M11 ) + ( y * inverse.M12 ) ) + ( z * inverse.M13 ) ) + ( d * inverse.M14 );
result.Normal.Y = (((x * inverse.M21) + (y * inverse.M22)) + (z * inverse.M23)) + (d * inverse.M24); result.Normal.Y = ( ( ( x * inverse.M21 ) + ( y * inverse.M22 ) ) + ( z * inverse.M23 ) ) + ( d * inverse.M24 );
result.Normal.Z = (((x * inverse.M31) + (y * inverse.M32)) + (z * inverse.M33)) + (d * inverse.M34); result.Normal.Z = ( ( ( x * inverse.M31 ) + ( y * inverse.M32 ) ) + ( z * inverse.M33 ) ) + ( d * inverse.M34 );
result.D = (((x * inverse.M41) + (y * inverse.M42)) + (z * inverse.M43)) + (d * inverse.M44); result.D = ( ( ( x * inverse.M41 ) + ( y * inverse.M42 ) ) + ( z * inverse.M43 ) ) + ( d * inverse.M44 );
} }
/// <summary> /// <summary>
@ -610,7 +623,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param> /// <param name="plane">The normalized source plane.</param>
/// <param name="transformation">The transformation matrix.</param> /// <param name="transformation">The transformation matrix.</param>
/// <returns>When the method completes, contains the transformed plane.</returns> /// <returns>When the method completes, contains the transformed plane.</returns>
public static Plane Transform(Plane plane, Matrix transformation) public static Plane Transform( Plane plane, Matrix transformation )
{ {
Plane result; Plane result;
float x = plane.Normal.X; float x = plane.Normal.X;
@ -619,10 +632,10 @@ namespace math
float d = plane.D; float d = plane.D;
transformation.Invert(); transformation.Invert();
result.Normal.X = (((x * transformation.M11) + (y * transformation.M12)) + (z * transformation.M13)) + (d * transformation.M14); result.Normal.X = ( ( ( x * transformation.M11 ) + ( y * transformation.M12 ) ) + ( z * transformation.M13 ) ) + ( d * transformation.M14 );
result.Normal.Y = (((x * transformation.M21) + (y * transformation.M22)) + (z * transformation.M23)) + (d * transformation.M24); result.Normal.Y = ( ( ( x * transformation.M21 ) + ( y * transformation.M22 ) ) + ( z * transformation.M23 ) ) + ( d * transformation.M24 );
result.Normal.Z = (((x * transformation.M31) + (y * transformation.M32)) + (z * transformation.M33)) + (d * transformation.M34); result.Normal.Z = ( ( ( x * transformation.M31 ) + ( y * transformation.M32 ) ) + ( z * transformation.M33 ) ) + ( d * transformation.M34 );
result.D = (((x * transformation.M41) + (y * transformation.M42)) + (z * transformation.M43)) + (d * transformation.M44); result.D = ( ( ( x * transformation.M41 ) + ( y * transformation.M42 ) ) + ( z * transformation.M43 ) ) + ( d * transformation.M44 );
return result; return result;
} }
@ -633,17 +646,17 @@ namespace math
/// <param name="planes">The array of normalized planes to transform.</param> /// <param name="planes">The array of normalized planes to transform.</param>
/// <param name="transformation">The transformation matrix.</param> /// <param name="transformation">The transformation matrix.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="planes"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="planes"/> is <c>null</c>.</exception>
public static void Transform(Plane[] planes, ref Matrix transformation) public static void Transform( Plane[] planes, ref Matrix transformation )
{ {
if (planes == null) if( planes == null )
throw new ArgumentNullException("planes"); throw new ArgumentNullException( "planes" );
Matrix inverse; Matrix inverse;
Matrix.Invert(ref transformation, out inverse); Matrix.Invert( ref transformation, out inverse );
for (int i = 0; i < planes.Length; ++i) for( int i = 0; i < planes.Length; ++i )
{ {
Transform(ref planes[i], ref transformation, out planes[i]); Transform( ref planes[i], ref transformation, out planes[i] );
} }
} }
@ -653,9 +666,9 @@ namespace math
/// <param name="scale">The amount by which to scale the plane.</param> /// <param name="scale">The amount by which to scale the plane.</param>
/// <param name="plane">The plane to scale.</param> /// <param name="plane">The plane to scale.</param>
/// <returns>The scaled plane.</returns> /// <returns>The scaled plane.</returns>
public static Plane operator *(float scale, Plane plane) public static Plane operator *( float scale, Plane plane )
{ {
return new Plane(plane.Normal.X * scale, plane.Normal.Y * scale, plane.Normal.Z * scale, plane.D * scale); return new Plane( plane.Normal.X * scale, plane.Normal.Y * scale, plane.Normal.Z * scale, plane.D * scale );
} }
/// <summary> /// <summary>
@ -664,18 +677,18 @@ namespace math
/// <param name="plane">The plane to scale.</param> /// <param name="plane">The plane to scale.</param>
/// <param name="scale">The amount by which to scale the plane.</param> /// <param name="scale">The amount by which to scale the plane.</param>
/// <returns>The scaled plane.</returns> /// <returns>The scaled plane.</returns>
public static Plane operator *(Plane plane, float scale) public static Plane operator *( Plane plane, float scale )
{ {
return new Plane(plane.Normal.X * scale, plane.Normal.Y * scale, plane.Normal.Z * scale, plane.D * scale); return new Plane( plane.Normal.X * scale, plane.Normal.Y * scale, plane.Normal.Z * scale, plane.D * scale );
} }
/// <summary> /// <summary>
/// Negates a plane by negating all its coefficients, which result in a plane in opposite direction. /// Negates a plane by negating all its coefficients, which result in a plane in opposite direction.
/// </summary> /// </summary>
/// <returns>The negated plane.</returns> /// <returns>The negated plane.</returns>
public static Plane operator -(Plane plane) public static Plane operator -( Plane plane )
{ {
return new Plane(-plane.Normal.X, -plane.Normal.Y, -plane.Normal.Z, -plane.D); return new Plane( -plane.Normal.X, -plane.Normal.Y, -plane.Normal.Z, -plane.D );
} }
/// <summary> /// <summary>
@ -684,9 +697,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Plane left, Plane right) public static bool operator ==( Plane left, Plane right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -695,9 +708,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Plane left, Plane right) public static bool operator !=( Plane left, Plane right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -708,7 +721,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "A:{0} B:{1} C:{2} D:{3}", Normal.X, Normal.Y, Normal.Z, D); return string.Format( CultureInfo.CurrentCulture, "A:{0} B:{1} C:{2} D:{3}", Normal.X, Normal.Y, Normal.Z, D );
} }
/// <summary> /// <summary>
@ -718,10 +731,10 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
return string.Format(CultureInfo.CurrentCulture, "A:{0} B:{1} C:{2} D:{3}", Normal.X.ToString(format, CultureInfo.CurrentCulture), return string.Format( CultureInfo.CurrentCulture, "A:{0} B:{1} C:{2} D:{3}", Normal.X.ToString( format, CultureInfo.CurrentCulture ),
Normal.Y.ToString(format, CultureInfo.CurrentCulture), Normal.Z.ToString(format, CultureInfo.CurrentCulture), D.ToString(format, CultureInfo.CurrentCulture)); Normal.Y.ToString( format, CultureInfo.CurrentCulture ), Normal.Z.ToString( format, CultureInfo.CurrentCulture ), D.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -731,9 +744,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "A:{0} B:{1} C:{2} D:{3}", Normal.X, Normal.Y, Normal.Z, D); return string.Format( formatProvider, "A:{0} B:{1} C:{2} D:{3}", Normal.X, Normal.Y, Normal.Z, D );
} }
/// <summary> /// <summary>
@ -744,10 +757,10 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "A:{0} B:{1} C:{2} D:{3}", Normal.X.ToString(format, formatProvider), return string.Format( formatProvider, "A:{0} B:{1} C:{2} D:{3}", Normal.X.ToString( format, formatProvider ),
Normal.Y.ToString(format, formatProvider), Normal.Z.ToString(format, formatProvider), D.ToString(format, formatProvider)); Normal.Y.ToString( format, formatProvider ), Normal.Z.ToString( format, formatProvider ), D.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -768,7 +781,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Plane value) public bool Equals( Plane value )
{ {
return Normal == value.Normal && D == value.D; return Normal == value.Normal && D == value.D;
} }
@ -780,15 +793,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Plane)value); return Equals( (Plane)value );
} }
#if SlimDX1xInterop #if SlimDX1xInterop

View File

@ -32,20 +32,20 @@ namespace math
/// A 2D point. /// A 2D point.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Point : IEquatable<Point> public struct Point : IEquatable<Point>
{ {
/// <summary> /// <summary>
/// A point with (0,0) coordinates. /// A point with (0,0) coordinates.
/// </summary> /// </summary>
public static readonly Point Zero = new Point(0, 0); public static readonly Point Zero = new Point( 0, 0 );
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Point"/> struct. /// Initializes a new instance of the <see cref="Point"/> struct.
/// </summary> /// </summary>
/// <param name="x">The x.</param> /// <param name="x">The x.</param>
/// <param name="y">The y.</param> /// <param name="y">The y.</param>
public Point(int x, int y) public Point( int x, int y )
{ {
X = x; X = x;
Y = y; Y = y;
@ -70,17 +70,19 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Point other) public bool Equals( Point other )
{ {
return other.X == X && other.Y == Y; return other.X == X && other.Y == Y;
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(Point)) return false; return false;
return Equals((Point)obj); if( obj.GetType() != typeof( Point ) )
return false;
return Equals( (Point)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -88,7 +90,7 @@ namespace math
{ {
unchecked unchecked
{ {
return (X * 397) ^ Y; return ( X * 397 ) ^ Y;
} }
} }
@ -100,9 +102,9 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator ==(Point left, Point right) public static bool operator ==( Point left, Point right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -113,15 +115,15 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator !=(Point left, Point right) public static bool operator !=( Point left, Point right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format("({0},{1})", X, Y); return string.Format( "({0},{1})", X, Y );
} }
/// <summary> /// <summary>
@ -129,9 +131,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Point(Vec2 value) public static explicit operator Point( Vec2 value )
{ {
return new Point((int)value.X, (int)value.Y); return new Point( (int)value.X, (int)value.Y );
} }
/// <summary> /// <summary>
@ -139,9 +141,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator Vec2(Point value) public static implicit operator Vec2( Point value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -31,24 +31,24 @@ namespace math
/// Initializes a new instance of the <see cref="RandomSeed"/> struct from a target uint. /// Initializes a new instance of the <see cref="RandomSeed"/> struct from a target uint.
/// </summary> /// </summary>
/// <param name="seed">The seed value to initialize the deterministic random generator.</param> /// <param name="seed">The seed value to initialize the deterministic random generator.</param>
public RandomSeed(uint seed) public RandomSeed( uint seed )
{ {
this.seed = (seed & UnderflowGuard); this.seed = ( seed & UnderflowGuard );
} }
/// <summary> /// <summary>
/// Get a deterministic double value between 0 and 1 based on the seed /// Get a deterministic double value between 0 and 1 based on the seed
/// </summary> /// </summary>
/// <returns>Deterministic pseudo-random value between 0 and 1</returns> /// <returns>Deterministic pseudo-random value between 0 and 1</returns>
public double GetDouble(uint offset) public double GetDouble( uint offset )
{ {
var dRand = (double)(unchecked(seed + offset)); // We want it to overflow var dRand = (double)( unchecked(seed + offset) ); // We want it to overflow
var dotProduct = Math.Cos(dRand) * GelfondConst + Math.Sin(dRand) * GelfondSchneiderConst; var dotProduct = Math.Cos( dRand ) * GelfondConst + Math.Sin( dRand ) * GelfondSchneiderConst;
var denominator = 1e-7 + 256 * dotProduct; var denominator = 1e-7 + 256 * dotProduct;
var remainder = Numerator % denominator; var remainder = Numerator % denominator;
return (remainder - Math.Floor(remainder)); return ( remainder - Math.Floor( remainder ) );
} }
/// <summary> /// <summary>
@ -56,6 +56,6 @@ namespace math
/// The calculations are still made as doubles to prevent underflow errors. /// The calculations are still made as doubles to prevent underflow errors.
/// </summary> /// </summary>
/// <returns>Deterministic pseudo-random value between 0 and 1</returns> /// <returns>Deterministic pseudo-random value between 0 and 1</returns>
public float GetFloat(uint offset) => (float)GetDouble(offset); public float GetFloat( uint offset ) => (float)GetDouble( offset );
} }
} }

View File

@ -37,7 +37,7 @@ namespace math
/// Represents a three dimensional line based on a point in space and a direction. /// Represents a three dimensional line based on a point in space and a direction.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Ray : IEquatable<Ray>, IFormattable public struct Ray : IEquatable<Ray>, IFormattable
{ {
/// <summary> /// <summary>
@ -55,7 +55,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="position">The position in three dimensional space of the origin of the ray.</param> /// <param name="position">The position in three dimensional space of the origin of the ray.</param>
/// <param name="direction">The normalized direction of the ray.</param> /// <param name="direction">The normalized direction of the ray.</param>
public Ray(Vec3 position, Vec3 direction) public Ray( Vec3 position, Vec3 direction )
{ {
this.Position = position; this.Position = position;
this.Direction = direction; this.Direction = direction;
@ -66,9 +66,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">The point to test.</param> /// <param name="point">The point to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Vec3 point) public bool Intersects( ref Vec3 point )
{ {
return CollisionHelper.RayIntersectsPoint(ref this, ref point); return CollisionHelper.RayIntersectsPoint( ref this, ref point );
} }
/// <summary> /// <summary>
@ -76,10 +76,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="ray">The ray to test.</param> /// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray) public bool Intersects( ref Ray ray )
{ {
Vec3 point; Vec3 point;
return CollisionHelper.RayIntersectsRay(ref this, ref ray, out point); return CollisionHelper.RayIntersectsRay( ref this, ref ray, out point );
} }
/// <summary> /// <summary>
@ -89,9 +89,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray, out Vec3 point) public bool Intersects( ref Ray ray, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsRay(ref this, ref ray, out point); return CollisionHelper.RayIntersectsRay( ref this, ref ray, out point );
} }
/// <summary> /// <summary>
@ -99,10 +99,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="plane">The plane to test</param> /// <param name="plane">The plane to test</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane) public bool Intersects( ref Plane plane )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsPlane(ref this, ref plane, out distance); return CollisionHelper.RayIntersectsPlane( ref this, ref plane, out distance );
} }
/// <summary> /// <summary>
@ -112,9 +112,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane, out float distance) public bool Intersects( ref Plane plane, out float distance )
{ {
return CollisionHelper.RayIntersectsPlane(ref this, ref plane, out distance); return CollisionHelper.RayIntersectsPlane( ref this, ref plane, out distance );
} }
/// <summary> /// <summary>
@ -124,9 +124,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane, out Vec3 point) public bool Intersects( ref Plane plane, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsPlane(ref this, ref plane, out point); return CollisionHelper.RayIntersectsPlane( ref this, ref plane, out point );
} }
/// <summary> /// <summary>
@ -136,10 +136,10 @@ namespace math
/// <param name="vertex2">The second vertex of the triangle to test.</param> /// <param name="vertex2">The second vertex of the triangle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param> /// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3) public bool Intersects( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3 )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3, out distance); return CollisionHelper.RayIntersectsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3, out distance );
} }
/// <summary> /// <summary>
@ -151,9 +151,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3, out float distance) public bool Intersects( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3, out float distance )
{ {
return CollisionHelper.RayIntersectsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3, out distance); return CollisionHelper.RayIntersectsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3, out distance );
} }
/// <summary> /// <summary>
@ -165,9 +165,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3, out Vec3 point) public bool Intersects( ref Vec3 vertex1, ref Vec3 vertex2, ref Vec3 vertex3, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsTriangle(ref this, ref vertex1, ref vertex2, ref vertex3, out point); return CollisionHelper.RayIntersectsTriangle( ref this, ref vertex1, ref vertex2, ref vertex3, out point );
} }
/// <summary> /// <summary>
@ -175,10 +175,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="box">The box to test.</param> /// <param name="box">The box to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box) public bool Intersects( ref BoundingBox box )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsBox(ref this, ref box, out distance); return CollisionHelper.RayIntersectsBox( ref this, ref box, out distance );
} }
/// <summary> /// <summary>
@ -188,9 +188,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box, out float distance) public bool Intersects( ref BoundingBox box, out float distance )
{ {
return CollisionHelper.RayIntersectsBox(ref this, ref box, out distance); return CollisionHelper.RayIntersectsBox( ref this, ref box, out distance );
} }
/// <summary> /// <summary>
@ -200,9 +200,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box, out Vec3 point) public bool Intersects( ref BoundingBox box, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsBox(ref this, ref box, out point); return CollisionHelper.RayIntersectsBox( ref this, ref box, out point );
} }
/// <summary> /// <summary>
@ -210,10 +210,10 @@ namespace math
/// </summary> /// </summary>
/// <param name="sphere">The sphere to test.</param> /// <param name="sphere">The sphere to test.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere) public bool Intersects( ref BoundingSphere sphere )
{ {
float distance; float distance;
return CollisionHelper.RayIntersectsSphere(ref this, ref sphere, out distance); return CollisionHelper.RayIntersectsSphere( ref this, ref sphere, out distance );
} }
/// <summary> /// <summary>
@ -223,9 +223,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection, /// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param> /// or 0 if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere, out float distance) public bool Intersects( ref BoundingSphere sphere, out float distance )
{ {
return CollisionHelper.RayIntersectsSphere(ref this, ref sphere, out distance); return CollisionHelper.RayIntersectsSphere( ref this, ref sphere, out distance );
} }
/// <summary> /// <summary>
@ -235,9 +235,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection, /// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param> /// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <returns>Whether the two objects intersected.</returns> /// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere, out Vec3 point) public bool Intersects( ref BoundingSphere sphere, out Vec3 point )
{ {
return CollisionHelper.RayIntersectsSphere(ref this, ref sphere, out point); return CollisionHelper.RayIntersectsSphere( ref this, ref sphere, out point );
} }
/// <summary> /// <summary>
@ -246,9 +246,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(Ray left, Ray right) public static bool operator ==( Ray left, Ray right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -257,9 +257,9 @@ namespace math
/// <param name="left">The first value to compare.</param> /// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param> /// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(Ray left, Ray right) public static bool operator !=( Ray left, Ray right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -270,7 +270,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "Position:{0} Direction:{1}", Position.ToString(), Direction.ToString()); return string.Format( CultureInfo.CurrentCulture, "Position:{0} Direction:{1}", Position.ToString(), Direction.ToString() );
} }
/// <summary> /// <summary>
@ -280,10 +280,10 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
return string.Format(CultureInfo.CurrentCulture, "Position:{0} Direction:{1}", Position.ToString(format, CultureInfo.CurrentCulture), return string.Format( CultureInfo.CurrentCulture, "Position:{0} Direction:{1}", Position.ToString( format, CultureInfo.CurrentCulture ),
Direction.ToString(format, CultureInfo.CurrentCulture)); Direction.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -293,9 +293,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "Position:{0} Direction:{1}", Position.ToString(), Direction.ToString()); return string.Format( formatProvider, "Position:{0} Direction:{1}", Position.ToString(), Direction.ToString() );
} }
/// <summary> /// <summary>
@ -306,10 +306,10 @@ namespace math
/// <returns> /// <returns>
/// A <see cref="string"/> that represents this instance. /// A <see cref="string"/> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "Position:{0} Direction:{1}", Position.ToString(format, formatProvider), return string.Format( formatProvider, "Position:{0} Direction:{1}", Position.ToString( format, formatProvider ),
Direction.ToString(format, formatProvider)); Direction.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -330,7 +330,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Ray value) public bool Equals( Ray value )
{ {
return Position == value.Position && Direction == value.Direction; return Position == value.Position && Direction == value.Direction;
} }
@ -342,15 +342,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((Ray)value); return Equals( (Ray)value );
} }
#if SlimDX1xInterop #if SlimDX1xInterop

View File

@ -31,9 +31,9 @@ namespace math
/// <summary> /// <summary>
/// A rectangle structure defining X,Y,Width,Height. /// A rectangle structure defining X,Y,Width,Height.
/// </summary> /// </summary>
[DataContract( Name = "Rectangle")] [DataContract( Name = "Rectangle" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Rectangle : IEquatable<Rectangle> public struct Rectangle : IEquatable<Rectangle>
{ {
/// <summary> /// <summary>
@ -53,7 +53,7 @@ namespace math
/// <param name="y">The top.</param> /// <param name="y">The top.</param>
/// <param name="width">The width.</param> /// <param name="width">The width.</param>
/// <param name="height">The height.</param> /// <param name="height">The height.</param>
public Rectangle(int x, int y, int width, int height) public Rectangle( int x, int y, int width, int height )
{ {
this.X = x; this.X = x;
this.Y = y; this.Y = y;
@ -142,7 +142,7 @@ namespace math
{ {
get get
{ {
return new Point(X, Y); return new Point( X, Y );
} }
set set
{ {
@ -162,7 +162,7 @@ namespace math
{ {
get get
{ {
return new Point(X + (Width / 2), Y + (Height / 2)); return new Point( X + ( Width / 2 ), Y + ( Height / 2 ) );
} }
} }
@ -176,7 +176,7 @@ namespace math
{ {
get get
{ {
return (Width == 0) && (Height == 0) && (X == 0) && (Y == 0); return ( Width == 0 ) && ( Height == 0 ) && ( X == 0 ) && ( Y == 0 );
} }
} }
@ -189,7 +189,7 @@ namespace math
{ {
get get
{ {
return new Size2(Width, Height); return new Size2( Width, Height );
} }
set set
{ {
@ -202,37 +202,37 @@ namespace math
/// Gets the position of the top-left corner of the rectangle. /// Gets the position of the top-left corner of the rectangle.
/// </summary> /// </summary>
/// <value>The top-left corner of the rectangle.</value> /// <value>The top-left corner of the rectangle.</value>
public Point TopLeft { get { return new Point(Left, Top); } } public Point TopLeft { get { return new Point( Left, Top ); } }
/// <summary> /// <summary>
/// Gets the position of the top-right corner of the rectangle. /// Gets the position of the top-right corner of the rectangle.
/// </summary> /// </summary>
/// <value>The top-right corner of the rectangle.</value> /// <value>The top-right corner of the rectangle.</value>
public Point TopRight { get { return new Point(Right, Top); } } public Point TopRight { get { return new Point( Right, Top ); } }
/// <summary> /// <summary>
/// Gets the position of the bottom-left corner of the rectangle. /// Gets the position of the bottom-left corner of the rectangle.
/// </summary> /// </summary>
/// <value>The bottom-left corner of the rectangle.</value> /// <value>The bottom-left corner of the rectangle.</value>
public Point BottomLeft { get { return new Point(Left, Bottom); } } public Point BottomLeft { get { return new Point( Left, Bottom ); } }
/// <summary> /// <summary>
/// Gets the position of the bottom-right corner of the rectangle. /// Gets the position of the bottom-right corner of the rectangle.
/// </summary> /// </summary>
/// <value>The bottom-right corner of the rectangle.</value> /// <value>The bottom-right corner of the rectangle.</value>
public Point BottomRight { get { return new Point(Right, Bottom); } } public Point BottomRight { get { return new Point( Right, Bottom ); } }
/// <summary>Changes the position of the rectangle.</summary> /// <summary>Changes the position of the rectangle.</summary>
/// <param name="amount">The values to adjust the position of the rectangle by.</param> /// <param name="amount">The values to adjust the position of the rectangle by.</param>
public void Offset(Point amount) public void Offset( Point amount )
{ {
Offset(amount.X, amount.Y); Offset( amount.X, amount.Y );
} }
/// <summary>Changes the position of the rectangle.</summary> /// <summary>Changes the position of the rectangle.</summary>
/// <param name="offsetX">Change in the x-position.</param> /// <param name="offsetX">Change in the x-position.</param>
/// <param name="offsetY">Change in the y-position.</param> /// <param name="offsetY">Change in the y-position.</param>
public void Offset(int offsetX, int offsetY) public void Offset( int offsetX, int offsetY )
{ {
X += offsetX; X += offsetX;
Y += offsetY; Y += offsetY;
@ -241,7 +241,7 @@ namespace math
/// <summary>Pushes the edges of the rectangle out by the horizontal and vertical values specified.</summary> /// <summary>Pushes the edges of the rectangle out by the horizontal and vertical values specified.</summary>
/// <param name="horizontalAmount">Value to push the sides out by.</param> /// <param name="horizontalAmount">Value to push the sides out by.</param>
/// <param name="verticalAmount">Value to push the top and bottom out by.</param> /// <param name="verticalAmount">Value to push the top and bottom out by.</param>
public void Inflate(int horizontalAmount, int verticalAmount) public void Inflate( int horizontalAmount, int verticalAmount )
{ {
X -= horizontalAmount; X -= horizontalAmount;
Y -= verticalAmount; Y -= verticalAmount;
@ -252,43 +252,43 @@ namespace math
/// <summary>Determines whether this rectangle contains a specified point represented by its x- and y-coordinates.</summary> /// <summary>Determines whether this rectangle contains a specified point represented by its x- and y-coordinates.</summary>
/// <param name="x">The x-coordinate of the specified point.</param> /// <param name="x">The x-coordinate of the specified point.</param>
/// <param name="y">The y-coordinate of the specified point.</param> /// <param name="y">The y-coordinate of the specified point.</param>
public bool Contains(int x, int y) public bool Contains( int x, int y )
{ {
return (X <= x) && (x < Right) && (Y <= y) && (y < Bottom); return ( X <= x ) && ( x < Right ) && ( Y <= y ) && ( y < Bottom );
} }
/// <summary>Determines whether this rectangle contains a specified Point.</summary> /// <summary>Determines whether this rectangle contains a specified Point.</summary>
/// <param name="value">The Point to evaluate.</param> /// <param name="value">The Point to evaluate.</param>
public bool Contains(Point value) public bool Contains( Point value )
{ {
bool result; bool result;
Contains(ref value, out result); Contains( ref value, out result );
return result; return result;
} }
/// <summary>Determines whether this rectangle contains a specified Point.</summary> /// <summary>Determines whether this rectangle contains a specified Point.</summary>
/// <param name="value">The Point to evaluate.</param> /// <param name="value">The Point to evaluate.</param>
/// <param name="result">[OutAttribute] true if the specified Point is contained within this rectangle; false otherwise.</param> /// <param name="result">[OutAttribute] true if the specified Point is contained within this rectangle; false otherwise.</param>
public void Contains(ref Point value, out bool result) public void Contains( ref Point value, out bool result )
{ {
result = (X <= value.X) && (value.X < Right) && (Y <= value.Y) && (value.Y < Bottom); result = ( X <= value.X ) && ( value.X < Right ) && ( Y <= value.Y ) && ( value.Y < Bottom );
} }
/// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary> /// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
public bool Contains(Rectangle value) public bool Contains( Rectangle value )
{ {
bool result; bool result;
Contains(ref value, out result); Contains( ref value, out result );
return result; return result;
} }
/// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary> /// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
/// <param name="result">[OutAttribute] On exit, is true if this rectangle entirely contains the specified rectangle, or false if not.</param> /// <param name="result">[OutAttribute] On exit, is true if this rectangle entirely contains the specified rectangle, or false if not.</param>
public void Contains(ref Rectangle value, out bool result) public void Contains( ref Rectangle value, out bool result )
{ {
result = (X <= value.X) && (value.Right <= Right) && (Y <= value.Y) && (value.Bottom <= Bottom); result = ( X <= value.X ) && ( value.Right <= Right ) && ( Y <= value.Y ) && ( value.Bottom <= Bottom );
} }
/// <summary> /// <summary>
@ -297,9 +297,9 @@ namespace math
/// <param name="x">X point coordinate.</param> /// <param name="x">X point coordinate.</param>
/// <param name="y">Y point coordinate.</param> /// <param name="y">Y point coordinate.</param>
/// <returns><c>true</c> if point is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if point is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns>
public bool Contains(float x, float y) public bool Contains( float x, float y )
{ {
return (x >= this.X && x <= Right && y >= this.Y && y <= Bottom); return ( x >= this.X && x <= Right && y >= this.Y && y <= Bottom );
} }
/// <summary> /// <summary>
@ -307,9 +307,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="vector2D">Coordinate <see cref="Vec2"/>.</param> /// <param name="vector2D">Coordinate <see cref="Vec2"/>.</param>
/// <returns><c>true</c> if <see cref="Vec2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if <see cref="Vec2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns>
public bool Contains(Vec2 vector2D) public bool Contains( Vec2 vector2D )
{ {
return Contains(vector2D.X, vector2D.Y); return Contains( vector2D.X, vector2D.Y );
} }
/// <summary> /// <summary>
@ -317,17 +317,17 @@ namespace math
/// </summary> /// </summary>
/// <param name="int2">Coordinate <see cref="Int2"/>.</param> /// <param name="int2">Coordinate <see cref="Int2"/>.</param>
/// <returns><c>true</c> if <see cref="Int2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if <see cref="Int2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns>
public bool Contains(Int2 int2) public bool Contains( Int2 int2 )
{ {
return Contains(int2.X, int2.Y); return Contains( int2.X, int2.Y );
} }
/// <summary>Determines whether a specified rectangle intersects with this rectangle.</summary> /// <summary>Determines whether a specified rectangle intersects with this rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
public bool Intersects(Rectangle value) public bool Intersects( Rectangle value )
{ {
bool result; bool result;
Intersects(ref value, out result); Intersects( ref value, out result );
return result; return result;
} }
@ -336,9 +336,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The rectangle to evaluate</param> /// <param name="value">The rectangle to evaluate</param>
/// <param name="result">[OutAttribute] true if the specified rectangle intersects with this one; false otherwise.</param> /// <param name="result">[OutAttribute] true if the specified rectangle intersects with this one; false otherwise.</param>
public void Intersects(ref Rectangle value, out bool result) public void Intersects( ref Rectangle value, out bool result )
{ {
result = (value.X < Right) && (X < value.Right) && (value.Y < Bottom) && (Y < value.Bottom); result = ( value.X < Right ) && ( X < value.Right ) && ( value.Y < Bottom ) && ( Y < value.Bottom );
} }
/// <summary> /// <summary>
@ -347,10 +347,10 @@ namespace math
/// <param name="value1">The first rectangle to compare.</param> /// <param name="value1">The first rectangle to compare.</param>
/// <param name="value2">The second rectangle to compare.</param> /// <param name="value2">The second rectangle to compare.</param>
/// <returns>The intersection rectangle.</returns> /// <returns>The intersection rectangle.</returns>
public static Rectangle Intersect(Rectangle value1, Rectangle value2) public static Rectangle Intersect( Rectangle value1, Rectangle value2 )
{ {
Rectangle result; Rectangle result;
Intersect(ref value1, ref value2, out result); Intersect( ref value1, ref value2, out result );
return result; return result;
} }
@ -358,15 +358,15 @@ namespace math
/// <param name="value1">The first rectangle to compare.</param> /// <param name="value1">The first rectangle to compare.</param>
/// <param name="value2">The second rectangle to compare.</param> /// <param name="value2">The second rectangle to compare.</param>
/// <param name="result">[OutAttribute] The area where the two first parameters overlap.</param> /// <param name="result">[OutAttribute] The area where the two first parameters overlap.</param>
public static void Intersect(ref Rectangle value1, ref Rectangle value2, out Rectangle result) public static void Intersect( ref Rectangle value1, ref Rectangle value2, out Rectangle result )
{ {
int newLeft = (value1.X > value2.X) ? value1.X : value2.X; int newLeft = ( value1.X > value2.X ) ? value1.X : value2.X;
int newTop = (value1.Y > value2.Y) ? value1.Y : value2.Y; int newTop = ( value1.Y > value2.Y ) ? value1.Y : value2.Y;
int newRight = (value1.Right < value2.Right) ? value1.Right : value2.Right; int newRight = ( value1.Right < value2.Right ) ? value1.Right : value2.Right;
int newBottom = (value1.Bottom < value2.Bottom) ? value1.Bottom : value2.Bottom; int newBottom = ( value1.Bottom < value2.Bottom ) ? value1.Bottom : value2.Bottom;
if ((newRight > newLeft) && (newBottom > newTop)) if( ( newRight > newLeft ) && ( newBottom > newTop ) )
{ {
result = new Rectangle(newLeft, newTop, newRight - newLeft, newBottom - newTop); result = new Rectangle( newLeft, newTop, newRight - newLeft, newBottom - newTop );
} }
else else
{ {
@ -380,11 +380,11 @@ namespace math
/// <param name="rectangle">The original rectangle.</param> /// <param name="rectangle">The original rectangle.</param>
/// <param name="point">The point to incorporate.</param> /// <param name="point">The point to incorporate.</param>
/// <returns>The union rectangle.</returns> /// <returns>The union rectangle.</returns>
public static Rectangle Union(Rectangle rectangle, Int2 point) public static Rectangle Union( Rectangle rectangle, Int2 point )
{ {
Rectangle result; Rectangle result;
var rect = new Rectangle(point.X, point.Y, 1, 1); var rect = new Rectangle( point.X, point.Y, 1, 1 );
Union(ref rectangle, ref rect, out result); Union( ref rectangle, ref rect, out result );
return result; return result;
} }
@ -394,10 +394,10 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param> /// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param> /// <param name="value2">The second rectangle to contain.</param>
/// <returns>The union rectangle.</returns> /// <returns>The union rectangle.</returns>
public static Rectangle Union(Rectangle value1, Rectangle value2) public static Rectangle Union( Rectangle value1, Rectangle value2 )
{ {
Rectangle result; Rectangle result;
Union(ref value1, ref value2, out result); Union( ref value1, ref value2, out result );
return result; return result;
} }
@ -407,13 +407,13 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param> /// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param> /// <param name="value2">The second rectangle to contain.</param>
/// <param name="result">[OutAttribute] The rectangle that must be the union of the first two rectangles.</param> /// <param name="result">[OutAttribute] The rectangle that must be the union of the first two rectangles.</param>
public static void Union(ref Rectangle value1, ref Rectangle value2, out Rectangle result) public static void Union( ref Rectangle value1, ref Rectangle value2, out Rectangle result )
{ {
var left = Math.Min(value1.Left, value2.Left); var left = Math.Min( value1.Left, value2.Left );
var right = Math.Max(value1.Right, value2.Right); var right = Math.Max( value1.Right, value2.Right );
var top = Math.Min(value1.Top, value2.Top); var top = Math.Min( value1.Top, value2.Top );
var bottom = Math.Max(value1.Bottom, value2.Bottom); var bottom = Math.Max( value1.Bottom, value2.Bottom );
result = new Rectangle(left, top, right - left, bottom - top); result = new Rectangle( left, top, right - left, bottom - top );
} }
/// <summary> /// <summary>
@ -423,11 +423,13 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(Rectangle)) return false; return false;
return Equals((Rectangle)obj); if( obj.GetType() != typeof( Rectangle ) )
return false;
return Equals( (Rectangle)obj );
} }
/// <summary> /// <summary>
@ -437,7 +439,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="Rectangle"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="Rectangle"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Rectangle other) public bool Equals( Rectangle other )
{ {
return other.X == this.X && other.Y == this.Y && other.Width == Width && other.Height == Height; return other.X == this.X && other.Y == this.Y && other.Width == Width && other.Height == Height;
} }
@ -453,9 +455,9 @@ namespace math
unchecked unchecked
{ {
int result = X; int result = X;
result = (result * 397) ^ Y; result = ( result * 397 ) ^ Y;
result = (result * 397) ^ Width; result = ( result * 397 ) ^ Width;
result = (result * 397) ^ Height; result = ( result * 397 ) ^ Height;
return result; return result;
} }
} }
@ -466,9 +468,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator ==(Rectangle left, Rectangle right) public static bool operator ==( Rectangle left, Rectangle right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -477,9 +479,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator !=(Rectangle left, Rectangle right) public static bool operator !=( Rectangle left, Rectangle right )
{ {
return !(left == right); return !( left == right );
} }
/// <summary> /// <summary>
@ -488,15 +490,15 @@ namespace math
/// <remarks>Performs direct converstion from int to float.</remarks> /// <remarks>Performs direct converstion from int to float.</remarks>
/// <param name="value">The source <see cref="Rectangle"/> value.</param> /// <param name="value">The source <see cref="Rectangle"/> value.</param>
/// <returns>The converted structure.</returns> /// <returns>The converted structure.</returns>
public static implicit operator RectangleF(Rectangle value) public static implicit operator RectangleF( Rectangle value )
{ {
return new RectangleF(value.X, value.Y, value.Width, value.Height); return new RectangleF( value.X, value.Y, value.Width, value.Height );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Width:{2} Height:{3}", X, Y, Width, Height); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Width:{2} Height:{3}", X, Y, Width, Height );
} }
} }
} }

View File

@ -31,9 +31,9 @@ namespace math
/// <summary> /// <summary>
/// Define a RectangleF. /// Define a RectangleF.
/// </summary> /// </summary>
[DataContract( Name = "RectangleF")] [DataContract( Name = "RectangleF" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct RectangleF : IEquatable<RectangleF> public struct RectangleF : IEquatable<RectangleF>
{ {
/// <summary> /// <summary>
@ -53,7 +53,7 @@ namespace math
/// <param name="y">The top.</param> /// <param name="y">The top.</param>
/// <param name="width">The width.</param> /// <param name="width">The width.</param>
/// <param name="height">The height.</param> /// <param name="height">The height.</param>
public RectangleF(float x, float y, float width, float height) public RectangleF( float x, float y, float width, float height )
{ {
this.X = x; this.X = x;
this.Y = y; this.Y = y;
@ -151,7 +151,7 @@ namespace math
{ {
get get
{ {
return new Vec2(X, Y); return new Vec2( X, Y );
} }
set set
{ {
@ -171,7 +171,7 @@ namespace math
{ {
get get
{ {
return new Vec2(X + (Width / 2), Y + (Height / 2)); return new Vec2( X + ( Width / 2 ), Y + ( Height / 2 ) );
} }
} }
@ -185,7 +185,7 @@ namespace math
{ {
get get
{ {
return (Width == 0.0f) && (Height == 0.0f) && (X == 0.0f) && (Y == 0.0f); return ( Width == 0.0f ) && ( Height == 0.0f ) && ( X == 0.0f ) && ( Y == 0.0f );
} }
} }
@ -198,7 +198,7 @@ namespace math
{ {
get get
{ {
return new Size2F(Width, Height); return new Size2F( Width, Height );
} }
set set
{ {
@ -211,44 +211,44 @@ namespace math
/// Gets the position of the top-left corner of the rectangle. /// Gets the position of the top-left corner of the rectangle.
/// </summary> /// </summary>
/// <value>The top-left corner of the rectangle.</value> /// <value>The top-left corner of the rectangle.</value>
public Vec2 TopLeft { get { return new Vec2(X, Y); } } public Vec2 TopLeft { get { return new Vec2( X, Y ); } }
/// <summary> /// <summary>
/// Gets the position of the top-right corner of the rectangle. /// Gets the position of the top-right corner of the rectangle.
/// </summary> /// </summary>
/// <value>The top-right corner of the rectangle.</value> /// <value>The top-right corner of the rectangle.</value>
public Vec2 TopRight { get { return new Vec2(Right, Y); } } public Vec2 TopRight { get { return new Vec2( Right, Y ); } }
/// <summary> /// <summary>
/// Gets the position of the bottom-left corner of the rectangle. /// Gets the position of the bottom-left corner of the rectangle.
/// </summary> /// </summary>
/// <value>The bottom-left corner of the rectangle.</value> /// <value>The bottom-left corner of the rectangle.</value>
public Vec2 BottomLeft { get { return new Vec2(X, Bottom); } } public Vec2 BottomLeft { get { return new Vec2( X, Bottom ); } }
/// <summary> /// <summary>
/// Gets the position of the bottom-right corner of the rectangle. /// Gets the position of the bottom-right corner of the rectangle.
/// </summary> /// </summary>
/// <value>The bottom-right corner of the rectangle.</value> /// <value>The bottom-right corner of the rectangle.</value>
public Vec2 BottomRight { get { return new Vec2(Right, Bottom); } } public Vec2 BottomRight { get { return new Vec2( Right, Bottom ); } }
/// <summary>Changes the position of the rectangle.</summary> /// <summary>Changes the position of the rectangle.</summary>
/// <param name="amount">The values to adjust the position of the rectangle by.</param> /// <param name="amount">The values to adjust the position of the rectangle by.</param>
public void Offset(Point amount) public void Offset( Point amount )
{ {
Offset(amount.X, amount.Y); Offset( amount.X, amount.Y );
} }
/// <summary>Changes the position of the rectangle.</summary> /// <summary>Changes the position of the rectangle.</summary>
/// <param name="amount">The values to adjust the position of the rectangle by.</param> /// <param name="amount">The values to adjust the position of the rectangle by.</param>
public void Offset(Vec2 amount) public void Offset( Vec2 amount )
{ {
Offset(amount.X, amount.Y); Offset( amount.X, amount.Y );
} }
/// <summary>Changes the position of the rectangle.</summary> /// <summary>Changes the position of the rectangle.</summary>
/// <param name="offsetX">Change in the x-position.</param> /// <param name="offsetX">Change in the x-position.</param>
/// <param name="offsetY">Change in the y-position.</param> /// <param name="offsetY">Change in the y-position.</param>
public void Offset(float offsetX, float offsetY) public void Offset( float offsetX, float offsetY )
{ {
X += offsetX; X += offsetX;
Y += offsetY; Y += offsetY;
@ -257,7 +257,7 @@ namespace math
/// <summary>Pushes the edges of the rectangle out by the horizontal and vertical values specified.</summary> /// <summary>Pushes the edges of the rectangle out by the horizontal and vertical values specified.</summary>
/// <param name="horizontalAmount">Value to push the sides out by.</param> /// <param name="horizontalAmount">Value to push the sides out by.</param>
/// <param name="verticalAmount">Value to push the top and bottom out by.</param> /// <param name="verticalAmount">Value to push the top and bottom out by.</param>
public void Inflate(float horizontalAmount, float verticalAmount) public void Inflate( float horizontalAmount, float verticalAmount )
{ {
X -= horizontalAmount; X -= horizontalAmount;
Y -= verticalAmount; Y -= verticalAmount;
@ -268,24 +268,24 @@ namespace math
/// <summary>Determines whether this rectangle contains a specified Point.</summary> /// <summary>Determines whether this rectangle contains a specified Point.</summary>
/// <param name="value">The Point to evaluate.</param> /// <param name="value">The Point to evaluate.</param>
/// <param name="result">[OutAttribute] true if the specified Point is contained within this rectangle; false otherwise.</param> /// <param name="result">[OutAttribute] true if the specified Point is contained within this rectangle; false otherwise.</param>
public void Contains(ref Vec2 value, out bool result) public void Contains( ref Vec2 value, out bool result )
{ {
result = (X <= value.X) && (value.X < Right) && (Y <= value.Y) && (value.Y < Bottom); result = ( X <= value.X ) && ( value.X < Right ) && ( Y <= value.Y ) && ( value.Y < Bottom );
} }
/// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary> /// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
public bool Contains(Rectangle value) public bool Contains( Rectangle value )
{ {
return (X <= value.X) && (value.Right <= Right) && (Y <= value.Y) && (value.Bottom <= Bottom); return ( X <= value.X ) && ( value.Right <= Right ) && ( Y <= value.Y ) && ( value.Bottom <= Bottom );
} }
/// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary> /// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
/// <param name="result">[OutAttribute] On exit, is true if this rectangle entirely contains the specified rectangle, or false if not.</param> /// <param name="result">[OutAttribute] On exit, is true if this rectangle entirely contains the specified rectangle, or false if not.</param>
public void Contains(ref RectangleF value, out bool result) public void Contains( ref RectangleF value, out bool result )
{ {
result = (X <= value.X) && (value.Right <= Right) && (Y <= value.Y) && (value.Bottom <= Bottom); result = ( X <= value.X ) && ( value.Right <= Right ) && ( Y <= value.Y ) && ( value.Bottom <= Bottom );
} }
/// <summary> /// <summary>
@ -294,9 +294,9 @@ namespace math
/// <param name="x">X point coordinate.</param> /// <param name="x">X point coordinate.</param>
/// <param name="y">Y point coordinate.</param> /// <param name="y">Y point coordinate.</param>
/// <returns><c>true</c> if point is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if point is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns>
public bool Contains(float x, float y) public bool Contains( float x, float y )
{ {
return (x >= this.X && x <= Right && y >= this.Y && y <= Bottom); return ( x >= this.X && x <= Right && y >= this.Y && y <= Bottom );
} }
/// <summary> /// <summary>
@ -304,9 +304,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="vector2D">Coordinate <see cref="Vec2"/>.</param> /// <param name="vector2D">Coordinate <see cref="Vec2"/>.</param>
/// <returns><c>true</c> if <see cref="Vec2"/> is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if <see cref="Vec2"/> is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns>
public bool Contains(Vec2 vector2D) public bool Contains( Vec2 vector2D )
{ {
return Contains(vector2D.X, vector2D.Y); return Contains( vector2D.X, vector2D.Y );
} }
/// <summary> /// <summary>
@ -314,9 +314,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="int2">Coordinate <see cref="Int2"/>.</param> /// <param name="int2">Coordinate <see cref="Int2"/>.</param>
/// <returns><c>true</c> if <see cref="Int2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if <see cref="Int2"/> is inside <see cref="Rectangle"/>, otherwise <c>false</c>.</returns>
public bool Contains(Int2 int2) public bool Contains( Int2 int2 )
{ {
return Contains(int2.X, int2.Y); return Contains( int2.X, int2.Y );
} }
/// <summary> /// <summary>
@ -324,17 +324,17 @@ namespace math
/// </summary> /// </summary>
/// <param name="point">Coordinate <see cref="Point"/>.</param> /// <param name="point">Coordinate <see cref="Point"/>.</param>
/// <returns><c>true</c> if <see cref="Point"/> is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns> /// <returns><c>true</c> if <see cref="Point"/> is inside <see cref="RectangleF"/>, otherwise <c>false</c>.</returns>
public bool Contains(Point point) public bool Contains( Point point )
{ {
return Contains(point.X, point.Y); return Contains( point.X, point.Y );
} }
/// <summary>Determines whether a specified rectangle intersects with this rectangle.</summary> /// <summary>Determines whether a specified rectangle intersects with this rectangle.</summary>
/// <param name="value">The rectangle to evaluate.</param> /// <param name="value">The rectangle to evaluate.</param>
public bool Intersects(RectangleF value) public bool Intersects( RectangleF value )
{ {
bool result; bool result;
Intersects(ref value, out result); Intersects( ref value, out result );
return result; return result;
} }
@ -343,9 +343,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="value">The rectangle to evaluate</param> /// <param name="value">The rectangle to evaluate</param>
/// <param name="result">[OutAttribute] true if the specified rectangle intersects with this one; false otherwise.</param> /// <param name="result">[OutAttribute] true if the specified rectangle intersects with this one; false otherwise.</param>
public void Intersects(ref RectangleF value, out bool result) public void Intersects( ref RectangleF value, out bool result )
{ {
result = (value.X < Right) && (X < value.Right) && (value.Y < Bottom) && (Y < value.Bottom); result = ( value.X < Right ) && ( X < value.Right ) && ( value.Y < Bottom ) && ( Y < value.Bottom );
} }
/// <summary> /// <summary>
@ -354,10 +354,10 @@ namespace math
/// <param name="value1">The first Rectangle to compare.</param> /// <param name="value1">The first Rectangle to compare.</param>
/// <param name="value2">The second Rectangle to compare.</param> /// <param name="value2">The second Rectangle to compare.</param>
/// <returns>The intersection rectangle.</returns> /// <returns>The intersection rectangle.</returns>
public static RectangleF Intersect(RectangleF value1, RectangleF value2) public static RectangleF Intersect( RectangleF value1, RectangleF value2 )
{ {
RectangleF result; RectangleF result;
Intersect(ref value1, ref value2, out result); Intersect( ref value1, ref value2, out result );
return result; return result;
} }
@ -365,15 +365,15 @@ namespace math
/// <param name="value1">The first rectangle to compare.</param> /// <param name="value1">The first rectangle to compare.</param>
/// <param name="value2">The second rectangle to compare.</param> /// <param name="value2">The second rectangle to compare.</param>
/// <param name="result">[OutAttribute] The area where the two first parameters overlap.</param> /// <param name="result">[OutAttribute] The area where the two first parameters overlap.</param>
public static void Intersect(ref RectangleF value1, ref RectangleF value2, out RectangleF result) public static void Intersect( ref RectangleF value1, ref RectangleF value2, out RectangleF result )
{ {
float newLeft = (value1.X > value2.X) ? value1.X : value2.X; float newLeft = ( value1.X > value2.X ) ? value1.X : value2.X;
float newTop = (value1.Y > value2.Y) ? value1.Y : value2.Y; float newTop = ( value1.Y > value2.Y ) ? value1.Y : value2.Y;
float newRight = (value1.Right < value2.Right) ? value1.Right : value2.Right; float newRight = ( value1.Right < value2.Right ) ? value1.Right : value2.Right;
float newBottom = (value1.Bottom < value2.Bottom) ? value1.Bottom : value2.Bottom; float newBottom = ( value1.Bottom < value2.Bottom ) ? value1.Bottom : value2.Bottom;
if ((newRight > newLeft) && (newBottom > newTop)) if( ( newRight > newLeft ) && ( newBottom > newTop ) )
{ {
result = new RectangleF(newLeft, newTop, newRight - newLeft, newBottom - newTop); result = new RectangleF( newLeft, newTop, newRight - newLeft, newBottom - newTop );
} }
else else
{ {
@ -387,10 +387,10 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param> /// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param> /// <param name="value2">The second rectangle to contain.</param>
/// <returns>The union rectangle.</returns> /// <returns>The union rectangle.</returns>
public static RectangleF Union(RectangleF value1, RectangleF value2) public static RectangleF Union( RectangleF value1, RectangleF value2 )
{ {
RectangleF result; RectangleF result;
Union(ref value1, ref value2, out result); Union( ref value1, ref value2, out result );
return result; return result;
} }
@ -400,13 +400,13 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param> /// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param> /// <param name="value2">The second rectangle to contain.</param>
/// <param name="result">[OutAttribute] The rectangle that must be the union of the first two rectangles.</param> /// <param name="result">[OutAttribute] The rectangle that must be the union of the first two rectangles.</param>
public static void Union(ref RectangleF value1, ref RectangleF value2, out RectangleF result) public static void Union( ref RectangleF value1, ref RectangleF value2, out RectangleF result )
{ {
var left = Math.Min(value1.Left, value2.Left); var left = Math.Min( value1.Left, value2.Left );
var right = Math.Max(value1.Right, value2.Right); var right = Math.Max( value1.Right, value2.Right );
var top = Math.Min(value1.Top, value2.Top); var top = Math.Min( value1.Top, value2.Top );
var bottom = Math.Max(value1.Bottom, value2.Bottom); var bottom = Math.Max( value1.Bottom, value2.Bottom );
result = new RectangleF(left, top, right - left, bottom - top); result = new RectangleF( left, top, right - left, bottom - top );
} }
/// <summary> /// <summary>
@ -416,20 +416,22 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(RectangleF)) return false; return false;
return Equals((RectangleF)obj); if( obj.GetType() != typeof( RectangleF ) )
return false;
return Equals( (RectangleF)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool Equals(RectangleF other) public bool Equals( RectangleF other )
{ {
return MathUtil.NearEqual(other.Left, Left) && return MathUtil.NearEqual( other.Left, Left ) &&
MathUtil.NearEqual(other.Right, Right) && MathUtil.NearEqual( other.Right, Right ) &&
MathUtil.NearEqual(other.Top, Top) && MathUtil.NearEqual( other.Top, Top ) &&
MathUtil.NearEqual(other.Bottom, Bottom); MathUtil.NearEqual( other.Bottom, Bottom );
} }
/// <summary> /// <summary>
@ -443,9 +445,9 @@ namespace math
unchecked unchecked
{ {
int result = X.GetHashCode(); int result = X.GetHashCode();
result = (result * 397) ^ Y.GetHashCode(); result = ( result * 397 ) ^ Y.GetHashCode();
result = (result * 397) ^ Width.GetHashCode(); result = ( result * 397 ) ^ Width.GetHashCode();
result = (result * 397) ^ Height.GetHashCode(); result = ( result * 397 ) ^ Height.GetHashCode();
return result; return result;
} }
} }
@ -456,9 +458,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator ==(RectangleF left, RectangleF right) public static bool operator ==( RectangleF left, RectangleF right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -467,9 +469,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator !=(RectangleF left, RectangleF right) public static bool operator !=( RectangleF left, RectangleF right )
{ {
return !(left == right); return !( left == right );
} }
/// <summary> /// <summary>
@ -478,15 +480,15 @@ namespace math
/// <remarks>Performs direct float to int conversion, any fractional data is truncated.</remarks> /// <remarks>Performs direct float to int conversion, any fractional data is truncated.</remarks>
/// <param name="value">The source <see cref="RectangleF"/> value.</param> /// <param name="value">The source <see cref="RectangleF"/> value.</param>
/// <returns>A converted <see cref="Rectangle"/> structure.</returns> /// <returns>A converted <see cref="Rectangle"/> structure.</returns>
public static explicit operator Rectangle(RectangleF value) public static explicit operator Rectangle( RectangleF value )
{ {
return new Rectangle((int)value.X, (int)value.Y, (int)value.Width, (int)value.Height); return new Rectangle( (int)value.X, (int)value.Y, (int)value.Width, (int)value.Height );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Width:{2} Height:{3}", X, Y, Width, Height); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Width:{2} Height:{3}", X, Y, Width, Height );
} }
} }
} }

View File

@ -30,15 +30,15 @@ namespace math
/// <summary> /// <summary>
/// Defines a 2D rectangular size (width,height). /// Defines a 2D rectangular size (width,height).
/// </summary> /// </summary>
[DataContract( Name = "!Size2")] [DataContract( Name = "!Size2" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Size2 : IEquatable<Size2> public struct Size2 : IEquatable<Size2>
{ {
/// <summary> /// <summary>
/// A zero size with (width, height) = (0,0) /// A zero size with (width, height) = (0,0)
/// </summary> /// </summary>
public static readonly Size2 Zero = new Size2(0, 0); public static readonly Size2 Zero = new Size2( 0, 0 );
/// <summary> /// <summary>
/// A zero size with (width, height) = (0,0) /// A zero size with (width, height) = (0,0)
@ -50,7 +50,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="width">The x.</param> /// <param name="width">The x.</param>
/// <param name="height">The y.</param> /// <param name="height">The y.</param>
public Size2(int width, int height) public Size2( int width, int height )
{ {
Width = width; Width = width;
Height = height; Height = height;
@ -75,17 +75,19 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Size2 other) public bool Equals( Size2 other )
{ {
return other.Width == Width && other.Height == Height; return other.Width == Width && other.Height == Height;
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(Size2)) return false; return false;
return Equals((Size2)obj); if( obj.GetType() != typeof( Size2 ) )
return false;
return Equals( (Size2)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -93,7 +95,7 @@ namespace math
{ {
unchecked unchecked
{ {
return (Width * 397) ^ Height; return ( Width * 397 ) ^ Height;
} }
} }
@ -105,9 +107,9 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator ==(Size2 left, Size2 right) public static bool operator ==( Size2 left, Size2 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -118,15 +120,15 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator !=(Size2 left, Size2 right) public static bool operator !=( Size2 left, Size2 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format("({0},{1})", Width, Height); return string.Format( "({0},{1})", Width, Height );
} }
} }
} }

View File

@ -30,15 +30,15 @@ namespace math
/// <summary> /// <summary>
/// Defines a 2D rectangular size (width,height). /// Defines a 2D rectangular size (width,height).
/// </summary> /// </summary>
[DataContract( Name = "Size2F")] [DataContract( Name = "Size2F" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Size2F : IEquatable<Size2F> public struct Size2F : IEquatable<Size2F>
{ {
/// <summary> /// <summary>
/// A zero size with (width, height) = (0,0) /// A zero size with (width, height) = (0,0)
/// </summary> /// </summary>
public static readonly Size2F Zero = new Size2F(0, 0); public static readonly Size2F Zero = new Size2F( 0, 0 );
/// <summary> /// <summary>
/// A zero size with (width, height) = (0,0) /// A zero size with (width, height) = (0,0)
@ -50,7 +50,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="width">The x.</param> /// <param name="width">The x.</param>
/// <param name="height">The y.</param> /// <param name="height">The y.</param>
public Size2F(float width, float height) public Size2F( float width, float height )
{ {
Width = width; Width = width;
Height = height; Height = height;
@ -75,17 +75,19 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(Size2F other) public bool Equals( Size2F other )
{ {
return other.Width == Width && other.Height == Height; return other.Width == Width && other.Height == Height;
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
if (obj.GetType() != typeof(Size2F)) return false; return false;
return Equals((Size2F)obj); if( obj.GetType() != typeof( Size2F ) )
return false;
return Equals( (Size2F)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -93,7 +95,7 @@ namespace math
{ {
unchecked unchecked
{ {
return (Width.GetHashCode() * 397) ^ Height.GetHashCode(); return ( Width.GetHashCode() * 397 ) ^ Height.GetHashCode();
} }
} }
@ -105,9 +107,9 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator ==(Size2F left, Size2F right) public static bool operator ==( Size2F left, Size2F right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -118,15 +120,15 @@ namespace math
/// <returns> /// <returns>
/// The result of the operator. /// The result of the operator.
/// </returns> /// </returns>
public static bool operator !=(Size2F left, Size2F right) public static bool operator !=( Size2F left, Size2F right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format("({0},{1})", Width, Height); return string.Format( "({0},{1})", Width, Height );
} }
} }
} }

View File

@ -30,20 +30,20 @@ namespace math
/// <summary> /// <summary>
/// Structure providing Width, Height and Depth. /// Structure providing Width, Height and Depth.
/// </summary> /// </summary>
[DataContract( Name = "!Size3")] [DataContract( Name = "!Size3" )]
[DataStyle(DataStyle.Compact)] [DataStyle( DataStyle.Compact )]
[StructLayout(LayoutKind.Sequential)] [StructLayout( LayoutKind.Sequential )]
public struct Size3 : IEquatable<Size3>, IComparable<Size3> public struct Size3 : IEquatable<Size3>, IComparable<Size3>
{ {
/// <summary> /// <summary>
/// A zero size with (width, height, depth) = (0,0,0) /// A zero size with (width, height, depth) = (0,0,0)
/// </summary> /// </summary>
public static readonly Size3 Zero = new Size3(0, 0, 0); public static readonly Size3 Zero = new Size3( 0, 0, 0 );
/// <summary> /// <summary>
/// A one size with (width, height, depth) = (1,1,1) /// A one size with (width, height, depth) = (1,1,1)
/// </summary> /// </summary>
public static readonly Size3 One = new Size3(1, 1, 1); public static readonly Size3 One = new Size3( 1, 1, 1 );
/// <summary> /// <summary>
/// A zero size with (width, height, depth) = (0,0,0) /// A zero size with (width, height, depth) = (0,0,0)
@ -56,7 +56,7 @@ namespace math
/// <param name="width">The x.</param> /// <param name="width">The x.</param>
/// <param name="height">The y.</param> /// <param name="height">The y.</param>
/// <param name="depth">The depth.</param> /// <param name="depth">The depth.</param>
public Size3(int width, int height, int depth) public Size3( int width, int height, int depth )
{ {
Width = width; Width = width;
Height = height; Height = height;
@ -93,16 +93,17 @@ namespace math
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool Equals(Size3 other) public bool Equals( Size3 other )
{ {
return Width == other.Width && Height == other.Height && Depth == other.Depth; return Width == other.Width && Height == other.Height && Depth == other.Depth;
} }
/// <inheritdoc/> /// <inheritdoc/>
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (ReferenceEquals(null, obj)) return false; if( ReferenceEquals( null, obj ) )
return obj is Size3 && Equals((Size3)obj); return false;
return obj is Size3 && Equals( (Size3)obj );
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -111,22 +112,22 @@ namespace math
unchecked unchecked
{ {
int hashCode = Width; int hashCode = Width;
hashCode = (hashCode * 397) ^ Height; hashCode = ( hashCode * 397 ) ^ Height;
hashCode = (hashCode * 397) ^ Depth; hashCode = ( hashCode * 397 ) ^ Depth;
return hashCode; return hashCode;
} }
} }
/// <inheritdoc/> /// <inheritdoc/>
public int CompareTo(Size3 other) public int CompareTo( Size3 other )
{ {
return Math.Sign(this.VolumeSize - other.VolumeSize); return Math.Sign( this.VolumeSize - other.VolumeSize );
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return string.Format("({0},{1},{2})", Width, Height, Depth); return string.Format( "({0},{1},{2})", Width, Height, Depth );
} }
/// <summary> /// <summary>
@ -135,9 +136,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator <(Size3 left, Size3 right) public static bool operator <( Size3 left, Size3 right )
{ {
return left.CompareTo(right) < 0; return left.CompareTo( right ) < 0;
} }
/// <summary> /// <summary>
@ -146,9 +147,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator <=(Size3 left, Size3 right) public static bool operator <=( Size3 left, Size3 right )
{ {
return left.CompareTo(right) <= 0; return left.CompareTo( right ) <= 0;
} }
/// <summary> /// <summary>
@ -157,9 +158,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator >(Size3 left, Size3 right) public static bool operator >( Size3 left, Size3 right )
{ {
return left.CompareTo(right) > 0; return left.CompareTo( right ) > 0;
} }
/// <summary> /// <summary>
@ -168,9 +169,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator >=(Size3 left, Size3 right) public static bool operator >=( Size3 left, Size3 right )
{ {
return left.CompareTo(right) >= 0; return left.CompareTo( right ) >= 0;
} }
/// <summary> /// <summary>
@ -179,9 +180,9 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator ==(Size3 left, Size3 right) public static bool operator ==( Size3 left, Size3 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -190,23 +191,23 @@ namespace math
/// <param name="left">The left.</param> /// <param name="left">The left.</param>
/// <param name="right">The right.</param> /// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns> /// <returns>The result of the operator.</returns>
public static bool operator !=(Size3 left, Size3 right) public static bool operator !=( Size3 left, Size3 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
/// Calculates the next up mip-level (*2) of this size. /// Calculates the next up mip-level (*2) of this size.
/// </summary> /// </summary>
/// <returns>A next up mip-level Size3.</returns> /// <returns>A next up mip-level Size3.</returns>
public Size3 Up2(int count = 1) public Size3 Up2( int count = 1 )
{ {
if (count < 0) if( count < 0 )
{ {
throw new ArgumentOutOfRangeException("count", "Must be >= 0"); throw new ArgumentOutOfRangeException( "count", "Must be >= 0" );
} }
return new Size3(Math.Max(1, Width << count), Math.Max(1, Height << count), Math.Max(1, Depth << count)); return new Size3( Math.Max( 1, Width << count ), Math.Max( 1, Height << count ), Math.Max( 1, Depth << count ) );
} }
/// <summary> /// <summary>
@ -214,14 +215,14 @@ namespace math
/// </summary> /// </summary>
/// <param name="count">The count.</param> /// <param name="count">The count.</param>
/// <returns>A next down mip-level Size3.</returns> /// <returns>A next down mip-level Size3.</returns>
public Size3 Down2(int count = 1) public Size3 Down2( int count = 1 )
{ {
if (count < 0) if( count < 0 )
{ {
throw new ArgumentOutOfRangeException("count", "Must be >= 0"); throw new ArgumentOutOfRangeException( "count", "Must be >= 0" );
} }
return new Size3(Math.Max(1, Width >> count), Math.Max(1, Height >> count), Math.Max(1, Depth >> count)); return new Size3( Math.Max( 1, Width >> count ), Math.Max( 1, Height >> count ), Math.Max( 1, Depth >> count ) );
} }
/// <summary> /// <summary>
@ -229,7 +230,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="direction">The direction &lt; 0 then <see cref="Down2"/>, &gt; 0 then <see cref="Up2"/>, else this unchanged.</param> /// <param name="direction">The direction &lt; 0 then <see cref="Down2"/>, &gt; 0 then <see cref="Up2"/>, else this unchanged.</param>
/// <returns>Size3.</returns> /// <returns>Size3.</returns>
public Size3 Mip(int direction) public Size3 Mip( int direction )
{ {
return direction == 0 ? this : direction < 0 ? Down2() : Up2(); return direction == 0 ? this : direction < 0 ? Down2() : Up2();
} }

View File

@ -16,7 +16,7 @@ namespace math
/// A representation of a sphere of values via Spherical Harmonics (SH). /// A representation of a sphere of values via Spherical Harmonics (SH).
/// </summary> /// </summary>
/// <typeparam name="TDataType">The type of data contained by the sphere</typeparam> /// <typeparam name="TDataType">The type of data contained by the sphere</typeparam>
[DataContract( Name = "SphericalHarmonicsGeneric")] [DataContract( Name = "SphericalHarmonicsGeneric" )]
public abstract class SphericalHarmonics<TDataType> public abstract class SphericalHarmonics<TDataType>
{ {
/// <summary> /// <summary>
@ -35,10 +35,10 @@ namespace math
get { return order; } get { return order; }
internal set internal set
{ {
if (order>5) if( order > 5 )
throw new NotSupportedException("Only orders inferior or equal to 5 are supported"); throw new NotSupportedException( "Only orders inferior or equal to 5 are supported" );
order = Math.Max(1, value); order = Math.Max( 1, value );
} }
} }
@ -59,7 +59,7 @@ namespace math
/// Initializes a new instance of the <see cref="SphericalHarmonics{TDataType}"/> class. /// Initializes a new instance of the <see cref="SphericalHarmonics{TDataType}"/> class.
/// </summary> /// </summary>
/// <param name="order">The order of the harmonics</param> /// <param name="order">The order of the harmonics</param>
protected SphericalHarmonics(int order) protected SphericalHarmonics( int order )
{ {
this.order = order; this.order = order;
Coefficients = new TDataType[order * order]; Coefficients = new TDataType[order * order];
@ -70,7 +70,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="direction">The direction</param> /// <param name="direction">The direction</param>
/// <returns>The value of the spherical harmonics in the direction</returns> /// <returns>The value of the spherical harmonics in the direction</returns>
public abstract TDataType Evaluate(Vec3 direction); public abstract TDataType Evaluate( Vec3 direction );
/// <summary> /// <summary>
/// Returns the coefficient x{l,m} of the spherical harmonics (the {l,m} spherical coordinate corresponding to the spherical base Y{l,m}). /// Returns the coefficient x{l,m} of the spherical harmonics (the {l,m} spherical coordinate corresponding to the spherical base Y{l,m}).
@ -82,28 +82,28 @@ namespace math
{ {
get get
{ {
CheckIndicesValidity(l, m, order); CheckIndicesValidity( l, m, order );
return Coefficients[LmToCoefficientIndex(l, m)]; return Coefficients[LmToCoefficientIndex( l, m )];
} }
set set
{ {
CheckIndicesValidity(l, m, order); CheckIndicesValidity( l, m, order );
Coefficients[LmToCoefficientIndex(l, m)] = value; Coefficients[LmToCoefficientIndex( l, m )] = value;
} }
} }
// ReSharper disable UnusedParameter.Local // ReSharper disable UnusedParameter.Local
private static void CheckIndicesValidity(int l, int m, int maxOrder) private static void CheckIndicesValidity( int l, int m, int maxOrder )
// ReSharper restore UnusedParameter.Local // ReSharper restore UnusedParameter.Local
{ {
if (l > maxOrder - 1) if( l > maxOrder - 1 )
throw new IndexOutOfRangeException($"'l' parameter should be between '0' and '{maxOrder-1}' (order-1)."); throw new IndexOutOfRangeException( $"'l' parameter should be between '0' and '{maxOrder - 1}' (order-1)." );
if (Math.Abs(m) > l) if( Math.Abs( m ) > l )
throw new IndexOutOfRangeException("'m' parameter should be between '-l' and '+l'."); throw new IndexOutOfRangeException( "'m' parameter should be between '-l' and '+l'." );
} }
private static int LmToCoefficientIndex(int l, int m) private static int LmToCoefficientIndex( int l, int m )
{ {
return l * l + l + m; return l * l + l + m;
} }
@ -112,7 +112,7 @@ namespace math
/// <summary> /// <summary>
/// A spherical harmonics representation of a cubemap. /// A spherical harmonics representation of a cubemap.
/// </summary> /// </summary>
[DataContract( Name = "SphericalHarmonics")] [DataContract( Name = "SphericalHarmonics" )]
public class SphericalHarmonics : SphericalHarmonics<Color3> public class SphericalHarmonics : SphericalHarmonics<Color3>
{ {
private readonly float[] baseValues; private readonly float[] baseValues;
@ -120,7 +120,7 @@ namespace math
private const float Pi4 = 4 * MathUtil.Pi; private const float Pi4 = 4 * MathUtil.Pi;
private const float Pi16 = 16 * MathUtil.Pi; private const float Pi16 = 16 * MathUtil.Pi;
private const float Pi64 = 64 * MathUtil.Pi; private const float Pi64 = 64 * MathUtil.Pi;
private static readonly float SqrtPi = (float)Math.Sqrt(MathUtil.Pi); private static readonly float SqrtPi = (float)Math.Sqrt( MathUtil.Pi );
/// <summary> /// <summary>
/// Base coefficients for SH. /// Base coefficients for SH.
@ -169,8 +169,8 @@ namespace math
/// Initializes a new instance of the <see cref="SphericalHarmonics"/> class. /// Initializes a new instance of the <see cref="SphericalHarmonics"/> class.
/// </summary> /// </summary>
/// <param name="order">The order of the harmonics</param> /// <param name="order">The order of the harmonics</param>
public SphericalHarmonics(int order) public SphericalHarmonics( int order )
: base(order) : base( order )
{ {
baseValues = new float[order * order]; baseValues = new float[order * order];
} }
@ -180,60 +180,60 @@ namespace math
/// </summary> /// </summary>
/// <param name="direction">The direction to evaluate.</param> /// <param name="direction">The direction to evaluate.</param>
/// <returns>The color computed for this direction.</returns> /// <returns>The color computed for this direction.</returns>
public override Color3 Evaluate(Vec3 direction) public override Color3 Evaluate( Vec3 direction )
{ {
var x = direction.X; var x = direction.X;
var y = direction.Y; var y = direction.Y;
var z = direction.Z; var z = direction.Z;
var x2 = x*x; var x2 = x * x;
var y2 = y*y; var y2 = y * y;
var z2 = z*z; var z2 = z * z;
var z3 = (float)Math.Pow(z, 3.0); var z3 = (float)Math.Pow( z, 3.0 );
var x4 = (float)Math.Pow(x, 4.0); var x4 = (float)Math.Pow( x, 4.0 );
var y4 = (float)Math.Pow(y, 4.0); var y4 = (float)Math.Pow( y, 4.0 );
var z4 = (float)Math.Pow(z, 4.0); var z4 = (float)Math.Pow( z, 4.0 );
//Equations based on data from: http://ppsloan.org/publications/StupidSH36.pdf //Equations based on data from: http://ppsloan.org/publications/StupidSH36.pdf
baseValues[ 0] = 1/(2*SqrtPi); baseValues[0] = 1 / ( 2 * SqrtPi );
if (Order > 1) if( Order > 1 )
{ {
baseValues[ 1] = -(float)Math.Sqrt(3/Pi4)*y; baseValues[1] = -(float)Math.Sqrt( 3 / Pi4 ) * y;
baseValues[ 2] = (float)Math.Sqrt(3/Pi4)*z; baseValues[2] = (float)Math.Sqrt( 3 / Pi4 ) * z;
baseValues[ 3] = -(float)Math.Sqrt(3/Pi4)*x; baseValues[3] = -(float)Math.Sqrt( 3 / Pi4 ) * x;
if (Order > 2) if( Order > 2 )
{ {
baseValues[ 4] = (float)Math.Sqrt(15/Pi4)*y*x; baseValues[4] = (float)Math.Sqrt( 15 / Pi4 ) * y * x;
baseValues[ 5] = -(float)Math.Sqrt(15/Pi4)*y*z; baseValues[5] = -(float)Math.Sqrt( 15 / Pi4 ) * y * z;
baseValues[ 6] = (float)Math.Sqrt(5/Pi16)*(3*z2-1); baseValues[6] = (float)Math.Sqrt( 5 / Pi16 ) * ( 3 * z2 - 1 );
baseValues[ 7] = -(float)Math.Sqrt(15/Pi4)*x*z; baseValues[7] = -(float)Math.Sqrt( 15 / Pi4 ) * x * z;
baseValues[ 8] = (float)Math.Sqrt(15/Pi16)*(x2-y2); baseValues[8] = (float)Math.Sqrt( 15 / Pi16 ) * ( x2 - y2 );
if (Order > 3) if( Order > 3 )
{ {
baseValues[ 9] = -(float)Math.Sqrt( 70/Pi64)*y*(3*x2-y2); baseValues[9] = -(float)Math.Sqrt( 70 / Pi64 ) * y * ( 3 * x2 - y2 );
baseValues[10] = (float)Math.Sqrt(105/ Pi4)*y*x*z; baseValues[10] = (float)Math.Sqrt( 105 / Pi4 ) * y * x * z;
baseValues[11] = -(float)Math.Sqrt( 42/Pi64)*y*(-1+5*z2); baseValues[11] = -(float)Math.Sqrt( 42 / Pi64 ) * y * ( -1 + 5 * z2 );
baseValues[12] = (float)Math.Sqrt( 7/Pi16)*(5*z3-3*z); baseValues[12] = (float)Math.Sqrt( 7 / Pi16 ) * ( 5 * z3 - 3 * z );
baseValues[13] = -(float)Math.Sqrt( 42/Pi64)*x*(-1+5*z2); baseValues[13] = -(float)Math.Sqrt( 42 / Pi64 ) * x * ( -1 + 5 * z2 );
baseValues[14] = (float)Math.Sqrt(105/Pi16)*(x2-y2)*z; baseValues[14] = (float)Math.Sqrt( 105 / Pi16 ) * ( x2 - y2 ) * z;
baseValues[15] = -(float)Math.Sqrt( 70/Pi64)*x*(x2-3*y2); baseValues[15] = -(float)Math.Sqrt( 70 / Pi64 ) * x * ( x2 - 3 * y2 );
if (Order > 4) if( Order > 4 )
{ {
baseValues[16] = 3*(float)Math.Sqrt(35/Pi16)*x*y*(x2-y2); baseValues[16] = 3 * (float)Math.Sqrt( 35 / Pi16 ) * x * y * ( x2 - y2 );
baseValues[17] = -3*(float)Math.Sqrt(70/Pi64)*y*z*(3*x2-y2); baseValues[17] = -3 * (float)Math.Sqrt( 70 / Pi64 ) * y * z * ( 3 * x2 - y2 );
baseValues[18] = 3*(float)Math.Sqrt( 5/Pi16)*y*x*(-1+7*z2); baseValues[18] = 3 * (float)Math.Sqrt( 5 / Pi16 ) * y * x * ( -1 + 7 * z2 );
baseValues[19] = -3*(float)Math.Sqrt(10/Pi64)*y*z*(-3+7*z2); baseValues[19] = -3 * (float)Math.Sqrt( 10 / Pi64 ) * y * z * ( -3 + 7 * z2 );
baseValues[20] = (105*z4-90*z2+9)/(16*SqrtPi); baseValues[20] = ( 105 * z4 - 90 * z2 + 9 ) / ( 16 * SqrtPi );
baseValues[21] = -3*(float)Math.Sqrt(10/Pi64)*x*z*(-3+7*z2); baseValues[21] = -3 * (float)Math.Sqrt( 10 / Pi64 ) * x * z * ( -3 + 7 * z2 );
baseValues[22] = 3*(float)Math.Sqrt( 5/Pi64)*(x2-y2)*(-1+7*z2); baseValues[22] = 3 * (float)Math.Sqrt( 5 / Pi64 ) * ( x2 - y2 ) * ( -1 + 7 * z2 );
baseValues[23] = -3*(float)Math.Sqrt(70/Pi64)*x*z*(x2-3*y2); baseValues[23] = -3 * (float)Math.Sqrt( 70 / Pi64 ) * x * z * ( x2 - 3 * y2 );
baseValues[24] = 3*(float)Math.Sqrt(35/(4*Pi64))*(x4-6*y2*x2+y4); baseValues[24] = 3 * (float)Math.Sqrt( 35 / ( 4 * Pi64 ) ) * ( x4 - 6 * y2 * x2 + y4 );
} }
} }
} }
@ -241,7 +241,7 @@ namespace math
var data = new Color3(); var data = new Color3();
for (int i = 0; i < baseValues.Length; i++) for( int i = 0; i < baseValues.Length; i++ )
data += Coefficients[i] * baseValues[i]; data += Coefficients[i] * baseValues[i];
return data; return data;

View File

@ -31,7 +31,7 @@ namespace math
/// Represents a four dimensional mathematical vector. /// Represents a four dimensional mathematical vector.
/// </summary> /// </summary>
[DataContract] [DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)] [StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct UInt4 : IEquatable<UInt4>, IFormattable public struct UInt4 : IEquatable<UInt4>, IFormattable
{ {
/// <summary> /// <summary>
@ -47,27 +47,27 @@ namespace math
/// <summary> /// <summary>
/// The X unit <see cref = "UInt4" /> (1, 0, 0, 0). /// The X unit <see cref = "UInt4" /> (1, 0, 0, 0).
/// </summary> /// </summary>
public static readonly UInt4 UnitX = new UInt4(1, 0, 0, 0); public static readonly UInt4 UnitX = new UInt4( 1, 0, 0, 0 );
/// <summary> /// <summary>
/// The Y unit <see cref = "UInt4" /> (0, 1, 0, 0). /// The Y unit <see cref = "UInt4" /> (0, 1, 0, 0).
/// </summary> /// </summary>
public static readonly UInt4 UnitY = new UInt4(0, 1, 0, 0); public static readonly UInt4 UnitY = new UInt4( 0, 1, 0, 0 );
/// <summary> /// <summary>
/// The Z unit <see cref = "UInt4" /> (0, 0, 1, 0). /// The Z unit <see cref = "UInt4" /> (0, 0, 1, 0).
/// </summary> /// </summary>
public static readonly UInt4 UnitZ = new UInt4(0, 0, 1, 0); public static readonly UInt4 UnitZ = new UInt4( 0, 0, 1, 0 );
/// <summary> /// <summary>
/// The W unit <see cref = "UInt4" /> (0, 0, 0, 1). /// The W unit <see cref = "UInt4" /> (0, 0, 0, 1).
/// </summary> /// </summary>
public static readonly UInt4 UnitW = new UInt4(0, 0, 0, 1); public static readonly UInt4 UnitW = new UInt4( 0, 0, 0, 1 );
/// <summary> /// <summary>
/// A <see cref = "UInt4" /> with all of its components set to one. /// A <see cref = "UInt4" /> with all of its components set to one.
/// </summary> /// </summary>
public static readonly UInt4 One = new UInt4(1, 1, 1, 1); public static readonly UInt4 One = new UInt4( 1, 1, 1, 1 );
/// <summary> /// <summary>
/// The X component of the vector. /// The X component of the vector.
@ -93,7 +93,7 @@ namespace math
/// Initializes a new instance of the <see cref = "UInt4" /> struct. /// Initializes a new instance of the <see cref = "UInt4" /> struct.
/// </summary> /// </summary>
/// <param name = "value">The value that will be assigned to all components.</param> /// <param name = "value">The value that will be assigned to all components.</param>
public UInt4(uint value) public UInt4( uint value )
{ {
X = value; X = value;
Y = value; Y = value;
@ -108,7 +108,7 @@ namespace math
/// <param name = "y">Initial value for the Y component of the vector.</param> /// <param name = "y">Initial value for the Y component of the vector.</param>
/// <param name = "z">Initial value for the Z component of the vector.</param> /// <param name = "z">Initial value for the Z component of the vector.</param>
/// <param name = "w">Initial value for the W component of the vector.</param> /// <param name = "w">Initial value for the W component of the vector.</param>
public UInt4(uint x, uint y, uint z, uint w) public UInt4( uint x, uint y, uint z, uint w )
{ {
X = x; X = x;
Y = y; Y = y;
@ -122,12 +122,12 @@ namespace math
/// <param name = "values">The values to assign to the X, Y, Z, and W components of the vector. This must be an array with four elements.</param> /// <param name = "values">The values to assign to the X, Y, Z, and W components of the vector. This must be an array with four elements.</param>
/// <exception cref = "ArgumentNullException">Thrown when <paramref name = "values" /> is <c>null</c>.</exception> /// <exception cref = "ArgumentNullException">Thrown when <paramref name = "values" /> is <c>null</c>.</exception>
/// <exception cref = "ArgumentOutOfRangeException">Thrown when <paramref name = "values" /> contains more or less than four elements.</exception> /// <exception cref = "ArgumentOutOfRangeException">Thrown when <paramref name = "values" /> contains more or less than four elements.</exception>
public UInt4(uint[] values) public UInt4( uint[] values )
{ {
if (values == null) if( values == null )
throw new ArgumentNullException("values"); throw new ArgumentNullException( "values" );
if (values.Length != 4) if( values.Length != 4 )
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for UInt4."); throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for UInt4." );
X = values[0]; X = values[0];
Y = values[1]; Y = values[1];
@ -146,7 +146,7 @@ namespace math
{ {
get get
{ {
switch (index) switch( index )
{ {
case 0: case 0:
return X; return X;
@ -158,12 +158,12 @@ namespace math
return W; return W;
} }
throw new ArgumentOutOfRangeException("index", "Indices for UInt4 run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for UInt4 run from 0 to 3, inclusive." );
} }
set set
{ {
switch (index) switch( index )
{ {
case 0: case 0:
X = value; X = value;
@ -178,7 +178,7 @@ namespace math
W = value; W = value;
break; break;
default: default:
throw new ArgumentOutOfRangeException("index", "Indices for UInt4 run from 0 to 3, inclusive."); throw new ArgumentOutOfRangeException( "index", "Indices for UInt4 run from 0 to 3, inclusive." );
} }
} }
} }
@ -198,9 +198,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <param name = "result">When the method completes, contains the sum of the two vectors.</param> /// <param name = "result">When the method completes, contains the sum of the two vectors.</param>
public static void Add(ref UInt4 left, ref UInt4 right, out UInt4 result) public static void Add( ref UInt4 left, ref UInt4 right, out UInt4 result )
{ {
result = new UInt4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); result = new UInt4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -209,9 +209,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static UInt4 Add(UInt4 left, UInt4 right) public static UInt4 Add( UInt4 left, UInt4 right )
{ {
return new UInt4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); return new UInt4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -220,9 +220,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <param name = "result">When the method completes, contains the difference of the two vectors.</param> /// <param name = "result">When the method completes, contains the difference of the two vectors.</param>
public static void Subtract(ref UInt4 left, ref UInt4 right, out UInt4 result) public static void Subtract( ref UInt4 left, ref UInt4 right, out UInt4 result )
{ {
result = new UInt4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); result = new UInt4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -231,9 +231,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static UInt4 Subtract(UInt4 left, UInt4 right) public static UInt4 Subtract( UInt4 left, UInt4 right )
{ {
return new UInt4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); return new UInt4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -242,9 +242,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <param name = "result">When the method completes, contains the scaled vector.</param> /// <param name = "result">When the method completes, contains the scaled vector.</param>
public static void Multiply(ref UInt4 value, uint scale, out UInt4 result) public static void Multiply( ref UInt4 value, uint scale, out UInt4 result )
{ {
result = new UInt4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); result = new UInt4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -253,9 +253,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static UInt4 Multiply(UInt4 value, uint scale) public static UInt4 Multiply( UInt4 value, uint scale )
{ {
return new UInt4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new UInt4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -264,9 +264,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param> /// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param> /// <param name = "right">The second vector to modulate.</param>
/// <param name = "result">When the method completes, contains the modulated vector.</param> /// <param name = "result">When the method completes, contains the modulated vector.</param>
public static void Modulate(ref UInt4 left, ref UInt4 right, out UInt4 result) public static void Modulate( ref UInt4 left, ref UInt4 right, out UInt4 result )
{ {
result = new UInt4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); result = new UInt4( left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W );
} }
/// <summary> /// <summary>
@ -275,9 +275,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param> /// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param> /// <param name = "right">The second vector to modulate.</param>
/// <returns>The modulated vector.</returns> /// <returns>The modulated vector.</returns>
public static UInt4 Modulate(UInt4 left, UInt4 right) public static UInt4 Modulate( UInt4 left, UInt4 right )
{ {
return new UInt4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); return new UInt4( left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W );
} }
/// <summary> /// <summary>
@ -286,9 +286,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <param name = "result">When the method completes, contains the scaled vector.</param> /// <param name = "result">When the method completes, contains the scaled vector.</param>
public static void Divide(ref UInt4 value, uint scale, out UInt4 result) public static void Divide( ref UInt4 value, uint scale, out UInt4 result )
{ {
result = new UInt4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); result = new UInt4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -297,9 +297,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static UInt4 Divide(UInt4 value, uint scale) public static UInt4 Divide( UInt4 value, uint scale )
{ {
return new UInt4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); return new UInt4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -309,25 +309,25 @@ namespace math
/// <param name = "min">The minimum value.</param> /// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param> /// <param name = "max">The maximum value.</param>
/// <param name = "result">When the method completes, contains the clamped value.</param> /// <param name = "result">When the method completes, contains the clamped value.</param>
public static void Clamp(ref UInt4 value, ref UInt4 min, ref UInt4 max, out UInt4 result) public static void Clamp( ref UInt4 value, ref UInt4 min, ref UInt4 max, out UInt4 result )
{ {
uint x = value.X; uint x = value.X;
x = (x > max.X) ? max.X : x; x = ( x > max.X ) ? max.X : x;
x = (x < min.X) ? min.X : x; x = ( x < min.X ) ? min.X : x;
uint y = value.Y; uint y = value.Y;
y = (y > max.Y) ? max.Y : y; y = ( y > max.Y ) ? max.Y : y;
y = (y < min.Y) ? min.Y : y; y = ( y < min.Y ) ? min.Y : y;
uint z = value.Z; uint z = value.Z;
z = (z > max.Z) ? max.Z : z; z = ( z > max.Z ) ? max.Z : z;
z = (z < min.Z) ? min.Z : z; z = ( z < min.Z ) ? min.Z : z;
uint w = value.W; uint w = value.W;
w = (w > max.W) ? max.W : w; w = ( w > max.W ) ? max.W : w;
w = (w < min.W) ? min.W : w; w = ( w < min.W ) ? min.W : w;
result = new UInt4(x, y, z, w); result = new UInt4( x, y, z, w );
} }
/// <summary> /// <summary>
@ -337,10 +337,10 @@ namespace math
/// <param name = "min">The minimum value.</param> /// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param> /// <param name = "max">The maximum value.</param>
/// <returns>The clamped value.</returns> /// <returns>The clamped value.</returns>
public static UInt4 Clamp(UInt4 value, UInt4 min, UInt4 max) public static UInt4 Clamp( UInt4 value, UInt4 min, UInt4 max )
{ {
UInt4 result; UInt4 result;
Clamp(ref value, ref min, ref max, out result); Clamp( ref value, ref min, ref max, out result );
return result; return result;
} }
@ -350,12 +350,12 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <param name = "result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param> /// <param name = "result">When the method completes, contains an new vector composed of the largest components of the source vectors.</param>
public static void Max(ref UInt4 left, ref UInt4 right, out UInt4 result) public static void Max( ref UInt4 left, ref UInt4 right, out UInt4 result )
{ {
result.X = (left.X > right.X) ? left.X : right.X; result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = (left.Y > right.Y) ? left.Y : right.Y; result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z; result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
result.W = (left.W > right.W) ? left.W : right.W; result.W = ( left.W > right.W ) ? left.W : right.W;
} }
/// <summary> /// <summary>
@ -364,10 +364,10 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <returns>A vector containing the largest components of the source vectors.</returns> /// <returns>A vector containing the largest components of the source vectors.</returns>
public static UInt4 Max(UInt4 left, UInt4 right) public static UInt4 Max( UInt4 left, UInt4 right )
{ {
UInt4 result; UInt4 result;
Max(ref left, ref right, out result); Max( ref left, ref right, out result );
return result; return result;
} }
@ -377,12 +377,12 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <param name = "result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param> /// <param name = "result">When the method completes, contains an new vector composed of the smallest components of the source vectors.</param>
public static void Min(ref UInt4 left, ref UInt4 right, out UInt4 result) public static void Min( ref UInt4 left, ref UInt4 right, out UInt4 result )
{ {
result.X = (left.X < right.X) ? left.X : right.X; result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = (left.Y < right.Y) ? left.Y : right.Y; result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z; result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
result.W = (left.W < right.W) ? left.W : right.W; result.W = ( left.W < right.W ) ? left.W : right.W;
} }
/// <summary> /// <summary>
@ -391,10 +391,10 @@ namespace math
/// <param name = "left">The first source vector.</param> /// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param> /// <param name = "right">The second source vector.</param>
/// <returns>A vector containing the smallest components of the source vectors.</returns> /// <returns>A vector containing the smallest components of the source vectors.</returns>
public static UInt4 Min(UInt4 left, UInt4 right) public static UInt4 Min( UInt4 left, UInt4 right )
{ {
UInt4 result; UInt4 result;
Min(ref left, ref right, out result); Min( ref left, ref right, out result );
return result; return result;
} }
@ -404,9 +404,9 @@ namespace math
/// <param name = "left">The first vector to add.</param> /// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param> /// <param name = "right">The second vector to add.</param>
/// <returns>The sum of the two vectors.</returns> /// <returns>The sum of the two vectors.</returns>
public static UInt4 operator +(UInt4 left, UInt4 right) public static UInt4 operator +( UInt4 left, UInt4 right )
{ {
return new UInt4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); return new UInt4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W );
} }
/// <summary> /// <summary>
@ -414,7 +414,7 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The vector to assert (unchange).</param> /// <param name = "value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns> /// <returns>The asserted (unchanged) vector.</returns>
public static UInt4 operator +(UInt4 value) public static UInt4 operator +( UInt4 value )
{ {
return value; return value;
} }
@ -425,9 +425,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param> /// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param> /// <param name = "right">The second vector to subtract.</param>
/// <returns>The difference of the two vectors.</returns> /// <returns>The difference of the two vectors.</returns>
public static UInt4 operator -(UInt4 left, UInt4 right) public static UInt4 operator -( UInt4 left, UInt4 right )
{ {
return new UInt4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); return new UInt4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W );
} }
/// <summary> /// <summary>
@ -436,9 +436,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static UInt4 operator *(uint scale, UInt4 value) public static UInt4 operator *( uint scale, UInt4 value )
{ {
return new UInt4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new UInt4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -447,9 +447,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static UInt4 operator *(UInt4 value, uint scale) public static UInt4 operator *( UInt4 value, uint scale )
{ {
return new UInt4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale); return new UInt4( value.X * scale, value.Y * scale, value.Z * scale, value.W * scale );
} }
/// <summary> /// <summary>
@ -458,9 +458,9 @@ namespace math
/// <param name = "value">The vector to scale.</param> /// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param> /// <param name = "scale">The amount by which to scale the vector.</param>
/// <returns>The scaled vector.</returns> /// <returns>The scaled vector.</returns>
public static UInt4 operator /(UInt4 value, uint scale) public static UInt4 operator /( UInt4 value, uint scale )
{ {
return new UInt4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); return new UInt4( value.X / scale, value.Y / scale, value.Z / scale, value.W / scale );
} }
/// <summary> /// <summary>
@ -469,9 +469,9 @@ namespace math
/// <param name = "left">The first value to compare.</param> /// <param name = "left">The first value to compare.</param>
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name = "left" /> has the same value as <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(UInt4 left, UInt4 right) public static bool operator ==( UInt4 left, UInt4 right )
{ {
return left.Equals(right); return left.Equals( right );
} }
/// <summary> /// <summary>
@ -480,9 +480,9 @@ namespace math
/// <param name = "left">The first value to compare.</param> /// <param name = "left">The first value to compare.</param>
/// <param name = "right">The second value to compare.</param> /// <param name = "right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name = "left" /> has a different value than <paramref name = "right" />; otherwise, <c>false</c>.</returns>
public static bool operator !=(UInt4 left, UInt4 right) public static bool operator !=( UInt4 left, UInt4 right )
{ {
return !left.Equals(right); return !left.Equals( right );
} }
/// <summary> /// <summary>
@ -490,9 +490,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec2(UInt4 value) public static explicit operator Vec2( UInt4 value )
{ {
return new Vec2(value.X, value.Y); return new Vec2( value.X, value.Y );
} }
/// <summary> /// <summary>
@ -500,9 +500,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec3(UInt4 value) public static explicit operator Vec3( UInt4 value )
{ {
return new Vec3(value.X, value.Y, value.Z); return new Vec3( value.X, value.Y, value.Z );
} }
/// <summary> /// <summary>
@ -510,9 +510,9 @@ namespace math
/// </summary> /// </summary>
/// <param name = "value">The value.</param> /// <param name = "value">The value.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static explicit operator Vec4(UInt4 value) public static explicit operator Vec4( UInt4 value )
{ {
return new Vec4(value.X, value.Y, value.Z, value.W); return new Vec4( value.X, value.Y, value.Z, value.W );
} }
/// <summary> /// <summary>
@ -523,7 +523,7 @@ namespace math
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W); return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W );
} }
/// <summary> /// <summary>
@ -533,16 +533,16 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format) public string ToString( string format )
{ {
if (format == null) if( format == null )
return ToString(); return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}", return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString(format, CultureInfo.CurrentCulture), X.ToString( format, CultureInfo.CurrentCulture ),
Y.ToString(format, CultureInfo.CurrentCulture), Y.ToString( format, CultureInfo.CurrentCulture ),
Z.ToString(format, CultureInfo.CurrentCulture), Z.ToString( format, CultureInfo.CurrentCulture ),
W.ToString(format, CultureInfo.CurrentCulture)); W.ToString( format, CultureInfo.CurrentCulture ) );
} }
/// <summary> /// <summary>
@ -552,9 +552,9 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(IFormatProvider formatProvider) public string ToString( IFormatProvider formatProvider )
{ {
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W); return string.Format( formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W );
} }
/// <summary> /// <summary>
@ -565,14 +565,14 @@ namespace math
/// <returns> /// <returns>
/// A <see cref = "string" /> that represents this instance. /// A <see cref = "string" /> that represents this instance.
/// </returns> /// </returns>
public string ToString(string format, IFormatProvider formatProvider) public string ToString( string format, IFormatProvider formatProvider )
{ {
if (format == null) if( format == null )
ToString(formatProvider); ToString( formatProvider );
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X.ToString(format, formatProvider), return string.Format( formatProvider, "X:{0} Y:{1} Z:{2} W:{3}", X.ToString( format, formatProvider ),
Y.ToString(format, formatProvider), Z.ToString(format, formatProvider), Y.ToString( format, formatProvider ), Z.ToString( format, formatProvider ),
W.ToString(format, formatProvider)); W.ToString( format, formatProvider ) );
} }
/// <summary> /// <summary>
@ -593,7 +593,7 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref = "UInt4" /> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref = "UInt4" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public bool Equals(UInt4 other) public bool Equals( UInt4 other )
{ {
return other.X == X && other.Y == Y && other.Z == Z && other.W == W; return other.X == X && other.Y == Y && other.Z == Z && other.W == W;
} }
@ -605,15 +605,15 @@ namespace math
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals( object value )
{ {
if (value == null) if( value == null )
return false; return false;
if (value.GetType() != GetType()) if( value.GetType() != GetType() )
return false; return false;
return Equals((UInt4)value); return Equals( (UInt4)value );
} }
/// <summary> /// <summary>
@ -621,9 +621,9 @@ namespace math
/// </summary> /// </summary>
/// <param name="input">The input.</param> /// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator UInt4(uint[] input) public static implicit operator UInt4( uint[] input )
{ {
return new UInt4(input); return new UInt4( input );
} }
/// <summary> /// <summary>
@ -631,7 +631,7 @@ namespace math
/// </summary> /// </summary>
/// <param name="input">The input.</param> /// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns> /// <returns>The result of the conversion.</returns>
public static implicit operator uint[](UInt4 input) public static implicit operator uint[]( UInt4 input )
{ {
return input.ToArray(); return input.ToArray();
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -11,54 +11,54 @@ namespace math
/// Return the Y/X components of the vector in the inverse order. /// Return the Y/X components of the vector in the inverse order.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec2 YX(this Vec2 vector) public static Vec2 YX( this Vec2 vector )
{ {
return new Vec2(vector.Y, vector.X); return new Vec2( vector.Y, vector.X );
} }
/// <summary> /// <summary>
/// Return the X/Y components of the vector. /// Return the X/Y components of the vector.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec2 XY(this Vec3 vector) public static Vec2 XY( this Vec3 vector )
{ {
return new Vec2(vector.X, vector.Y); return new Vec2( vector.X, vector.Y );
} }
/// <summary> /// <summary>
/// Return the X/Z components of the vector. /// Return the X/Z components of the vector.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec2 XZ(this Vec3 vector) public static Vec2 XZ( this Vec3 vector )
{ {
return new Vec2(vector.X, vector.Z); return new Vec2( vector.X, vector.Z );
} }
/// <summary> /// <summary>
/// Return the Y/Z components of the vector. /// Return the Y/Z components of the vector.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec2 YZ(this Vec3 vector) public static Vec2 YZ( this Vec3 vector )
{ {
return new Vec2(vector.Y, vector.Z); return new Vec2( vector.Y, vector.Z );
} }
/// <summary> /// <summary>
/// Return the X/Y components of the vector. /// Return the X/Y components of the vector.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec2 XY(this Vec4 vector) public static Vec2 XY( this Vec4 vector )
{ {
return new Vec2(vector.X, vector.Y); return new Vec2( vector.X, vector.Y );
} }
/// <summary> /// <summary>
/// Return the X/Y/Z components of the vector. /// Return the X/Y/Z components of the vector.
/// </summary> /// </summary>
/// <param name="vector">the input vector</param> /// <param name="vector">the input vector</param>
public static Vec3 XYZ(this Vec4 vector) public static Vec3 XYZ( this Vec4 vector )
{ {
return new Vec3(vector.X, vector.Y, vector.Z); return new Vec3( vector.X, vector.Y, vector.Z );
} }
} }
} }

View File

@ -14,8 +14,8 @@ namespace math
static public class fn static public class fn
{ {
static public float ToDeg( float rad ) => ( float )(180.0 / Math.PI) * rad; static public float ToDeg( float rad ) => (float)( 180.0 / Math.PI ) * rad;
static public float ToRad( float deg ) => ( float )(Math.PI / 180.0) * deg; static public float ToRad( float deg ) => (float)( Math.PI / 180.0 ) * deg;
static public float Clamp( float v, float min, float max ) static public float Clamp( float v, float min, float max )
{ {
@ -29,7 +29,7 @@ namespace math
static public float LogisticsFull( float v, float height, float spread, float f, float g, float h ) static public float LogisticsFull( float v, float height, float spread, float f, float g, float h )
{ {
float res = height / (1.0f + (float)Math.Pow( g, (spread * (v+h))) ) + f; float res = height / ( 1.0f + (float)Math.Pow( g, ( spread * ( v + h ) ) ) ) + f;
return res; return res;
} }
@ -47,28 +47,28 @@ namespace math
} }
//Tracked these down in Desmos //Tracked these down in Desmos
static public float s_a = 0.0f; static public float s_a = 0.0f;
static public float s_b = 0.155f; static public float s_b = 0.155f;
static public float s_c = 1.03f; static public float s_c = 1.03f;
static public float s_d = 6.13f; static public float s_d = 6.13f;
static public float s_f = -10.2f; static public float s_f = -10.2f;
static public float s_g = 4.06f; static public float s_g = 4.06f;
static public float Quintic( float v ) static public float Quintic( float v )
{ {
var vv = v * v; var vv = v * v;
var vvv = vv * v; var vvv = vv * v;
var vvvv = vvv * v; var vvvv = vvv * v;
var vvvvv= vvvv * v; var vvvvv = vvvv * v;
var res = s_a + s_b*v + s_c*vv + s_d*vvv + s_f*vvvv + s_g * vvvvv; var res = s_a + s_b * v + s_c * vv + s_d * vvv + s_f * vvvv + s_g * vvvvv;
return res; return res;
} }
static public float s_p = 0.37f; static public float s_p = 0.37f;
static public float s_o = 0.15f; static public float s_o = 0.15f;
static public float s_m = 2.11f; static public float s_m = 2.11f;
static public float s_n = -0.57f; static public float s_n = -0.57f;
static public float PerlinToContinent( float h ) static public float PerlinToContinent( float h )
@ -93,7 +93,7 @@ namespace math
{ {
var dV = (double)v; var dV = (double)v;
var newV = dV * dV * (3.0 - 2.0 * dV); var newV = dV * dV * ( 3.0 - 2.0 * dV );
return (float)newV; return (float)newV;

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -10,7 +10,7 @@ namespace mod
{ {
[Serializable] [Serializable]
public class Config: lib.Config public class Config : lib.Config
{ {
public String name = "Generic"; public String name = "Generic";
} }
@ -33,13 +33,13 @@ namespace mod
[Serializable] [Serializable]
public class FluidConfig: Config public class FluidConfig : Config
{ {
public String type = "none"; public String type = "none";
} }
public class FluidBase: Base public class FluidBase : Base
{ {
public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } } public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } }
@ -65,7 +65,7 @@ namespace mod
[Serializable] [Serializable]
public class SystemConfig: Config public class SystemConfig : Config
{ {
public String type = "none"; public String type = "none";
} }

View File

@ -52,9 +52,9 @@ namespace lib
// //
// Returns: // Returns:
// The top object of the deserialized graph. // The top object of the deserialized graph.
[RequiresDynamicCode("BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered.")] [RequiresDynamicCode( "BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered." )]
[RequiresUnreferencedCode("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] [RequiresUnreferencedCode( "BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered." )]
object Deserialize(Stream serializationStream); object Deserialize( Stream serializationStream );
// //
// Summary: // Summary:
// Serializes an object, or graph of objects with the given root to the provided // Serializes an object, or graph of objects with the given root to the provided
@ -68,8 +68,8 @@ namespace lib
// graph: // graph:
// The object, or root of the object graph, to serialize. All child objects of this // The object, or root of the object graph, to serialize. All child objects of this
// root object are automatically serialized. // root object are automatically serialized.
[RequiresUnreferencedCode("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] [RequiresUnreferencedCode( "BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered." )]
void Serialize(Stream serializationStream, object graph); void Serialize( Stream serializationStream, object graph );
} }
@ -89,7 +89,7 @@ namespace lib
} }
public class NewEveryCall<T>: ISerDes<T> where T : IFormatter, new() public class NewEveryCall<T> : ISerDes<T> where T : IFormatter, new()
{ {
public T getInstance() public T getInstance()
{ {
@ -104,8 +104,8 @@ namespace lib
public class Conn<T, TInst> : Conn public class Conn<T, TInst> : Conn
where T : IFormatter, new() where T : IFormatter, new()
where TInst : ISerDes<T>, new() where TInst : ISerDes<T>, new()
{ {
public Socket Sock { get { return m_socket; } } public Socket Sock { get { return m_socket; } }
public Stream Stream { get { return m_streamNet; } } public Stream Stream { get { return m_streamNet; } }

View File

@ -43,14 +43,14 @@ namespace lib.Net
}; };
[Serializable] [Serializable]
public class CreateEntity: Admin public class CreateEntity : Admin
{ {
} }
[Serializable] [Serializable]
public class MoveEntity: Admin public class MoveEntity : Admin
{ {
} }
@ -69,7 +69,7 @@ namespace lib.Net
[Serializable] [Serializable]
public class EntityPos: EntityBase public class EntityPos : EntityBase
{ {
public EntityPos( int id, float x, float y, float z ) : public EntityPos( int id, float x, float y, float z ) :
base( id ) base( id )
@ -85,7 +85,7 @@ namespace lib.Net
} }
[Serializable] [Serializable]
public class EntityDesc: EntityBase public class EntityDesc : EntityBase
{ {
public EntityDesc( int id ) : public EntityDesc( int id ) :
base( id ) base( id )

View File

@ -7,37 +7,41 @@ namespace Tracing
// the first frame is the address of the last called method // the first frame is the address of the last called method
private readonly List<ulong> _stack; private readonly List<ulong> _stack;
public AddressStack(int capacity) public AddressStack( int capacity )
{ {
_stack = new List<ulong>(capacity); _stack = new List<ulong>( capacity );
} }
// No need to override GetHashCode because we don't want to use it as a key in a dictionary // No need to override GetHashCode because we don't want to use it as a key in a dictionary
public override bool Equals(object obj) public override bool Equals( object obj )
{ {
if (obj == null) return false; if( obj == null )
return false;
var stack = obj as AddressStack; var stack = obj as AddressStack;
if (stack == null) return false; if( stack == null )
return false;
var frameCount = _stack.Count; var frameCount = _stack.Count;
if (frameCount != stack._stack.Count) return false; if( frameCount != stack._stack.Count )
return false;
for (int i = 0; i < frameCount; i++) for( int i = 0; i < frameCount; i++ )
{ {
if (_stack[i] != stack._stack[i]) return false; if( _stack[i] != stack._stack[i] )
return false;
} }
return true; return true;
} }
public override int GetHashCode() => _stack.GetHashCode(); public override int GetHashCode() => _stack.GetHashCode();
public IReadOnlyList<ulong> Stack => _stack; public IReadOnlyList<ulong> Stack => _stack;
public void AddFrame(ulong address) public void AddFrame( ulong address )
{ {
_stack.Add(address); _stack.Add( address );
} }
} }
} }

View File

@ -68,9 +68,9 @@ namespace Tracing
//* //*
log.info( $"EnableKernelProvider" ); log.info( $"EnableKernelProvider" );
success = log.var( session.EnableKernelProvider( KernelTraceEventParser.Keywords.None | success = log.var( session.EnableKernelProvider( KernelTraceEventParser.Keywords.None |
// KernelTraceEventParser.Keywords.ImageLoad | // KernelTraceEventParser.Keywords.ImageLoad |
// KernelTraceEventParser.Keywords.Process // KernelTraceEventParser.Keywords.Process
0 , 0,
KernelTraceEventParser.Keywords.None KernelTraceEventParser.Keywords.None
) ); ) );
log.info( $"EnableKernelProvider {success}" ); log.info( $"EnableKernelProvider {success}" );
@ -159,7 +159,7 @@ namespace Tracing
GetProcessMethods( data.ProcessID ).AddModule( data.FileName, data.ImageBase, data.ImageSize ); GetProcessMethods( data.ProcessID ).AddModule( data.FileName, data.ImageBase, data.ImageSize );
log.info($"{data.ProcessID}.{data.ThreadID} --> {data.FileName}"); log.info( $"{data.ProcessID}.{data.ThreadID} --> {data.FileName}" );
} }
private void OnMethodDetails( MethodLoadUnloadVerboseTraceData data ) private void OnMethodDetails( MethodLoadUnloadVerboseTraceData data )

View File

@ -77,20 +77,20 @@ namespace Tracing
//await Task.Factory.StartNew( () => { //await Task.Factory.StartNew( () => {
using EventPipeSession session = _client.StartEventPipeSession( providers, false ); using EventPipeSession session = _client.StartEventPipeSession( providers, false );
//log.info( $"SetupProviders" ); //log.info( $"SetupProviders" );
//SetupProviders( session, allAllocations ); //SetupProviders( session, allAllocations );
var source = new EventPipeEventSource( session.EventStream ); var source = new EventPipeEventSource( session.EventStream );
log.info( $"SetupListeners" ); log.info( $"SetupListeners" );
SetupListeners( source ); SetupListeners( source );
log.info( $"Run Process" ); log.info( $"Run Process" );
source.Process(); source.Process();
log.info( $"Done" ); log.info( $"Done" );
//} ); //} );
} }
@ -105,9 +105,9 @@ namespace Tracing
//* //*
log.info( $"EnableKernelProvider" ); log.info( $"EnableKernelProvider" );
success = log.var( session.EnableKernelProvider( KernelTraceEventParser.Keywords.None | success = log.var( session.EnableKernelProvider( KernelTraceEventParser.Keywords.None |
// KernelTraceEventParser.Keywords.ImageLoad | // KernelTraceEventParser.Keywords.ImageLoad |
// KernelTraceEventParser.Keywords.Process // KernelTraceEventParser.Keywords.Process
0 , 0,
KernelTraceEventParser.Keywords.None KernelTraceEventParser.Keywords.None
) ); ) );
log.info( $"EnableKernelProvider {success}" ); log.info( $"EnableKernelProvider {success}" );
@ -179,7 +179,7 @@ namespace Tracing
private void OnAllocTick( GCAllocationTickTraceData data ) private void OnAllocTick( GCAllocationTickTraceData data )
{ {
if( FilterOutEvent( data ) ) if( FilterOutEvent( data ) )
return; return;
//log.info( $"*** RAW: {data}" ); //log.info( $"*** RAW: {data}" );
@ -194,7 +194,7 @@ namespace Tracing
var typeName = GetProcessTypeName( data.ProcessID, data.TypeID ); var typeName = GetProcessTypeName( data.ProcessID, data.TypeID );
//if( data.TotalSizeForTypeSample >= 85000 ) //if( data.TotalSizeForTypeSample >= 85000 )
{ {
var message = $"{data.ThreadID}/{thisThreadId} Alloc {data.ObjectSize, 8} at 0x{data.Address:0000000000000000} in {data.TypeName} (or {GetProcessTypeName( data.ProcessID, data.TypeID )}) "; var message = $"{data.ThreadID}/{thisThreadId} Alloc {data.ObjectSize,8} at 0x{data.Address:0000000000000000} in {data.TypeName} (or {GetProcessTypeName( data.ProcessID, data.TypeID )}) ";
log.info( message ); log.info( message );
} }
GetProcessAllocations( data.ProcessID ) GetProcessAllocations( data.ProcessID )
@ -230,13 +230,13 @@ namespace Tracing
//GetProcessMethods( data.ProcessID ).AddModule( data.FileName, data.ImageBase, data.ImageSize ); //GetProcessMethods( data.ProcessID ).AddModule( data.FileName, data.ImageBase, data.ImageSize );
log.info($"{data.ProcessID}.{data.ThreadID} --> {data.FileName}"); log.info( $"{data.ProcessID}.{data.ThreadID} --> {data.FileName}" );
} }
private void OnMethodDetails( MethodLoadUnloadVerboseTraceData data ) private void OnMethodDetails( MethodLoadUnloadVerboseTraceData data )
{ {
//if( FilterOutEvent( data ) ) //if( FilterOutEvent( data ) )
// return; // return;
//log.info( $"{data}" ); //log.info( $"{data}" );
@ -296,7 +296,7 @@ namespace Tracing
private void OnClrStackWalk( ClrStackWalkTraceData data ) private void OnClrStackWalk( ClrStackWalkTraceData data )
{ {
var message = $"{data.ProcessID}.{data.ThreadID} - {data.TimeStampRelativeMSec,12} | {data.FrameCount} frames"; var message = $"{data.ProcessID}.{data.ThreadID} - {data.TimeStampRelativeMSec,12} | {data.FrameCount} frames";
log.info(message); log.info( message );
var callstack = BuildCallStack( data ); var callstack = BuildCallStack( data );
GetProcessAllocations( data.ProcessID ).AddStack( data.ThreadID, callstack ); GetProcessAllocations( data.ProcessID ).AddStack( data.ThreadID, callstack );

View File

@ -8,34 +8,34 @@ namespace ProfilerHelpers
private readonly int _size; private readonly int _size;
private readonly string _fullName; private readonly string _fullName;
internal MethodInfo(ulong startAddress, int size, string namespaceAndTypeName, string name, string signature) internal MethodInfo( ulong startAddress, int size, string namespaceAndTypeName, string name, string signature )
{ {
_startAddress = startAddress; _startAddress = startAddress;
_size = size; _size = size;
_fullName = ComputeFullName(startAddress, namespaceAndTypeName, name, signature); _fullName = ComputeFullName( startAddress, namespaceAndTypeName, name, signature );
} }
private string ComputeFullName(ulong startAddress, string namespaceAndTypeName, string name, string signature) private string ComputeFullName( ulong startAddress, string namespaceAndTypeName, string name, string signature )
{ {
var fullName = signature; var fullName = signature;
// constructor case: name = .ctor | namespaceAndTypeName = A.B.typeName | signature = ... (parameters) // constructor case: name = .ctor | namespaceAndTypeName = A.B.typeName | signature = ... (parameters)
// --> A.B.typeName(parameters) // --> A.B.typeName(parameters)
if (name == ".ctor") if( name == ".ctor" )
{ {
return $"{namespaceAndTypeName}{ExtractParameters(signature)}"; return $"{namespaceAndTypeName}{ExtractParameters( signature )}";
} }
// general case: name = Foo | namespaceAndTypeName = A.B.typeName | signature = ... (parameters) // general case: name = Foo | namespaceAndTypeName = A.B.typeName | signature = ... (parameters)
// --> A.B.Foo(parameters) // --> A.B.Foo(parameters)
fullName = $"{namespaceAndTypeName}.{name}{ExtractParameters(signature)}"; fullName = $"{namespaceAndTypeName}.{name}{ExtractParameters( signature )}";
return fullName; return fullName;
} }
private string ExtractTypeName(string namespaceAndTypeName) private string ExtractTypeName( string namespaceAndTypeName )
{ {
var pos = namespaceAndTypeName.LastIndexOf(".", StringComparison.Ordinal); var pos = namespaceAndTypeName.LastIndexOf( ".", StringComparison.Ordinal );
if (pos == -1) if( pos == -1 )
{ {
return namespaceAndTypeName; return namespaceAndTypeName;
} }
@ -43,13 +43,13 @@ namespace ProfilerHelpers
// skip the . // skip the .
pos++; pos++;
return namespaceAndTypeName.Substring(pos); return namespaceAndTypeName.Substring( pos );
} }
private string ExtractParameters(string signature) private string ExtractParameters( string signature )
{ {
var pos = signature.IndexOf(" ("); var pos = signature.IndexOf( " (" );
if (pos == -1) if( pos == -1 )
{ {
return "(???)"; return "(???)";
} }
@ -57,7 +57,7 @@ namespace ProfilerHelpers
// skip double space // skip double space
pos += 2; pos += 2;
var parameters = signature.Substring(pos); var parameters = signature.Substring( pos );
return parameters; return parameters;
} }

View File

@ -20,38 +20,38 @@ namespace ProfilerHelpers
private Process _process; private Process _process;
private readonly int _pid; private readonly int _pid;
public MethodStore(int pid, bool loadModules = false) public MethodStore( int pid, bool loadModules = false )
{ {
// it may be possible to open the process // it may be possible to open the process
// in that case, _hProcess = IntPtr.Zero // in that case, _hProcess = IntPtr.Zero
_pid = pid; _pid = pid;
_methods = new List<MethodInfo>(1024); _methods = new List<MethodInfo>( 1024 );
_cache = new Dictionary<ulong, string>(); _cache = new Dictionary<ulong, string>();
_hProcess = BindToProcess(pid, loadModules); _hProcess = BindToProcess( pid, loadModules );
} }
private IntPtr BindToProcess(int pid, bool loadModules) private IntPtr BindToProcess( int pid, bool loadModules )
{ {
try try
{ {
_process = Process.GetProcessById(pid); _process = Process.GetProcessById( pid );
if (!SymInitialize(_process.Handle, loadModules)) if( !SymInitialize( _process.Handle, loadModules ) )
return IntPtr.Zero; return IntPtr.Zero;
return _process.Handle; return _process.Handle;
} }
catch (Exception x) catch( Exception x )
{ {
Console.WriteLine($"Error while binding pid #{pid} to DbgHelp:"); Console.WriteLine( $"Error while binding pid #{pid} to DbgHelp:" );
Console.WriteLine(x.Message); Console.WriteLine( x.Message );
return IntPtr.Zero; return IntPtr.Zero;
} }
} }
private bool SymInitialize(IntPtr hProcess, bool loadModules = false) private bool SymInitialize( IntPtr hProcess, bool loadModules = false )
{ {
// read https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-symsetoptions for more details // read https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-symsetoptions for more details
// maybe SYMOPT_NO_PROMPTS and SYMOPT_FAIL_CRITICAL_ERRORS could be used // maybe SYMOPT_NO_PROMPTS and SYMOPT_FAIL_CRITICAL_ERRORS could be used
@ -68,27 +68,27 @@ namespace ProfilerHelpers
// //
// passing false as last parameter means that we will need to call SymLoadModule64 // passing false as last parameter means that we will need to call SymLoadModule64
// each time a module is loaded in the process // each time a module is loaded in the process
return NativeDbgHelp.SymInitialize(hProcess, null, loadModules); return NativeDbgHelp.SymInitialize( hProcess, null, loadModules );
} }
public MethodInfo Add(ulong address, int size, string namespaceAndTypeName, string name, string signature) public MethodInfo Add( ulong address, int size, string namespaceAndTypeName, string name, string signature )
{ {
var method = new MethodInfo(address, size, namespaceAndTypeName, name, signature); var method = new MethodInfo( address, size, namespaceAndTypeName, name, signature );
_methods.Add(method); _methods.Add( method );
return method; return method;
} }
public string GetFullName(ulong address) public string GetFullName( ulong address )
{ {
if (_cache.TryGetValue(address, out var fullName)) if( _cache.TryGetValue( address, out var fullName ) )
return fullName; return fullName;
// look for managed methods // look for managed methods
for (int i = 0; i < _methods.Count; i++) for( int i = 0; i < _methods.Count; i++ )
{ {
var method = _methods[i]; var method = _methods[i];
if ((address >= method.StartAddress) && (address < method.StartAddress + (ulong)method.Size)) if( ( address >= method.StartAddress ) && ( address < method.StartAddress + (ulong)method.Size ) )
{ {
fullName = method.FullName; fullName = method.FullName;
_cache[address] = fullName; _cache[address] = fullName;
@ -97,40 +97,40 @@ namespace ProfilerHelpers
} }
// look for native methods // look for native methods
fullName = GetNativeMethodName(address); fullName = GetNativeMethodName( address );
_cache[address] = fullName; _cache[address] = fullName;
return fullName; return fullName;
} }
private string GetNativeMethodName(ulong address) private string GetNativeMethodName( ulong address )
{ {
var symbol = new NativeDbgHelp.SYMBOL_INFO(); var symbol = new NativeDbgHelp.SYMBOL_INFO();
symbol.MaxNameLen = 1024; symbol.MaxNameLen = 1024;
symbol.SizeOfStruct = (uint)Marshal.SizeOf(symbol) - 1024; // char buffer is not counted symbol.SizeOfStruct = (uint)Marshal.SizeOf( symbol ) - 1024; // char buffer is not counted
// the ANSI version of SymFromAddr is called so each character is 1 byte long // the ANSI version of SymFromAddr is called so each character is 1 byte long
if (NativeDbgHelp.SymFromAddr(_hProcess, address, out var displacement, ref symbol)) if( NativeDbgHelp.SymFromAddr( _hProcess, address, out var displacement, ref symbol ) )
{ {
var buffer = new StringBuilder(symbol.Name.Length); var buffer = new StringBuilder( symbol.Name.Length );
// remove weird "$##" at the end of some symbols // remove weird "$##" at the end of some symbols
var pos = symbol.Name.LastIndexOf("$##"); var pos = symbol.Name.LastIndexOf( "$##" );
if (pos == -1) if( pos == -1 )
buffer.Append(symbol.Name); buffer.Append( symbol.Name );
else else
buffer.Append(symbol.Name, 0, pos); buffer.Append( symbol.Name, 0, pos );
// add offset if any // add offset if any
if (displacement != 0) if( displacement != 0 )
buffer.Append($"+0x{displacement}"); buffer.Append( $"+0x{displacement}" );
return buffer.ToString(); return buffer.ToString();
} }
// default value is just the address in HEX // default value is just the address in HEX
#if DEBUG #if DEBUG
return ($"0x{address:x} (SymFromAddr failed with 0x{Marshal.GetLastWin32Error():x})"); return ( $"0x{address:x} (SymFromAddr failed with 0x{Marshal.GetLastWin32Error():x})" );
#else #else
return $"0x{address:x}"; return $"0x{address:x}";
#endif #endif
@ -138,21 +138,22 @@ namespace ProfilerHelpers
} }
const int ERROR_SUCCESS = 0; const int ERROR_SUCCESS = 0;
public void AddModule(string filename, ulong baseOfDll, int sizeOfDll) public void AddModule( string filename, ulong baseOfDll, int sizeOfDll )
{ {
var baseAddress = NativeDbgHelp.SymLoadModule64(_hProcess, IntPtr.Zero, filename, null, baseOfDll, (uint)sizeOfDll); var baseAddress = NativeDbgHelp.SymLoadModule64( _hProcess, IntPtr.Zero, filename, null, baseOfDll, (uint)sizeOfDll );
if (baseAddress == 0) if( baseAddress == 0 )
{ {
// should work if the same module is added more than once // should work if the same module is added more than once
if (Marshal.GetLastWin32Error() == ERROR_SUCCESS) return; if( Marshal.GetLastWin32Error() == ERROR_SUCCESS )
return;
Console.WriteLine($"SymLoadModule64 failed for {filename}"); Console.WriteLine( $"SymLoadModule64 failed for {filename}" );
} }
} }
public void Dispose() public void Dispose()
{ {
if (_hProcess == IntPtr.Zero) if( _hProcess == IntPtr.Zero )
return; return;
_hProcess = IntPtr.Zero; _hProcess = IntPtr.Zero;
@ -166,7 +167,7 @@ namespace ProfilerHelpers
public const uint SYMOPT_UNDNAME = 0x00000002; public const uint SYMOPT_UNDNAME = 0x00000002;
public const uint SYMOPT_DEFERRED_LOADS = 0x00000004; public const uint SYMOPT_DEFERRED_LOADS = 0x00000004;
[StructLayout(LayoutKind.Sequential)] [StructLayout( LayoutKind.Sequential )]
public struct SYMBOL_INFO public struct SYMBOL_INFO
{ {
public uint SizeOfStruct; public uint SizeOfStruct;
@ -184,25 +185,25 @@ namespace ProfilerHelpers
public uint Tag; // pdb classification public uint Tag; // pdb classification
public uint NameLen; // Actual length of name public uint NameLen; // Actual length of name
public uint MaxNameLen; public uint MaxNameLen;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 1024 )]
public string Name; public string Name;
} }
[DllImport("dbghelp.dll", SetLastError = true)] [DllImport( "dbghelp.dll", SetLastError = true )]
public static extern bool SymInitialize(IntPtr hProcess, string userSearchPath, bool invadeProcess); public static extern bool SymInitialize( IntPtr hProcess, string userSearchPath, bool invadeProcess );
[DllImport("dbghelp.dll", SetLastError = true)] [DllImport( "dbghelp.dll", SetLastError = true )]
public static extern uint SymSetOptions(uint symOptions); public static extern uint SymSetOptions( uint symOptions );
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Ansi)] [DllImport( "dbghelp.dll", SetLastError = true, CharSet = CharSet.Ansi )]
public static extern ulong SymLoadModule64(IntPtr hProcess, IntPtr hFile, string imageName, string moduleName, ulong baseOfDll, uint sizeOfDll); public static extern ulong SymLoadModule64( IntPtr hProcess, IntPtr hFile, string imageName, string moduleName, ulong baseOfDll, uint sizeOfDll );
// use ANSI version to ensure the right size of the structure // use ANSI version to ensure the right size of the structure
// read https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/ns-dbghelp-symbol_info // read https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/ns-dbghelp-symbol_info
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Ansi)] [DllImport( "dbghelp.dll", SetLastError = true, CharSet = CharSet.Ansi )]
public static extern bool SymFromAddr(IntPtr hProcess, ulong address, out ulong displacement, ref SYMBOL_INFO symbol); public static extern bool SymFromAddr( IntPtr hProcess, ulong address, out ulong displacement, ref SYMBOL_INFO symbol );
[DllImport("dbghelp.dll", SetLastError = true)] [DllImport( "dbghelp.dll", SetLastError = true )]
public static extern bool SymCleanup(IntPtr hProcess); public static extern bool SymCleanup( IntPtr hProcess );
} }
} }

View File

@ -20,10 +20,11 @@ namespace Tracing
public void Dispose() public void Dispose()
{ {
if (_disposed) return; if( _disposed )
return;
_disposed = true; _disposed = true;
foreach (var methodStore in _methods.Values) foreach( var methodStore in _methods.Values )
{ {
methodStore.Dispose(); methodStore.Dispose();
} }

View File

@ -10,7 +10,7 @@ namespace Tracing
private readonly Dictionary<string, AllocationInfo> _allocations; private readonly Dictionary<string, AllocationInfo> _allocations;
private readonly Dictionary<int, AllocationInfo> _perThreadLastAllocation; private readonly Dictionary<int, AllocationInfo> _perThreadLastAllocation;
public ProcessAllocations(int pid) public ProcessAllocations( int pid )
{ {
_pid = pid; _pid = pid;
_allocations = new Dictionary<string, AllocationInfo>(); _allocations = new Dictionary<string, AllocationInfo>();
@ -19,9 +19,9 @@ namespace Tracing
public int Pid => _pid; public int Pid => _pid;
public AllocationInfo GetAllocations(string typeName) public AllocationInfo GetAllocations( string typeName )
{ {
return (_allocations.TryGetValue(typeName, out var info)) ? info : null; return ( _allocations.TryGetValue( typeName, out var info ) ) ? info : null;
} }
public IEnumerable<AllocationInfo> GetAllAllocations() public IEnumerable<AllocationInfo> GetAllAllocations()
@ -29,20 +29,20 @@ namespace Tracing
return _allocations.Values; return _allocations.Values;
} }
public AllocationInfo AddAllocation(int threadID, ulong size, ulong count, string typeName) public AllocationInfo AddAllocation( int threadID, ulong size, ulong count, string typeName )
{ {
if (!_allocations.TryGetValue(typeName, out var info)) if( !_allocations.TryGetValue( typeName, out var info ) )
{ {
info = new AllocationInfo(typeName); info = new AllocationInfo( typeName );
_allocations[typeName] = info; _allocations[typeName] = info;
} }
info.AddAllocation(size, count); info.AddAllocation( size, count );
// the last allocation is still here without the corresponding stack // the last allocation is still here without the corresponding stack
if (_perThreadLastAllocation.TryGetValue(threadID, out var lastAlloc)) if( _perThreadLastAllocation.TryGetValue( threadID, out var lastAlloc ) )
{ {
Console.WriteLine("no stack for the last allocation"); Console.WriteLine( "no stack for the last allocation" );
} }
// keep track of the allocation for the given thread // keep track of the allocation for the given thread
@ -52,12 +52,12 @@ namespace Tracing
return info; return info;
} }
public void AddStack(int threadID, AddressStack stack) public void AddStack( int threadID, AddressStack stack )
{ {
if (_perThreadLastAllocation.TryGetValue(threadID, out var lastAlloc)) if( _perThreadLastAllocation.TryGetValue( threadID, out var lastAlloc ) )
{ {
lastAlloc.AddStack(stack); lastAlloc.AddStack( stack );
_perThreadLastAllocation.Remove(threadID); _perThreadLastAllocation.Remove( threadID );
return; return;
} }
@ -73,7 +73,7 @@ namespace Tracing
private ulong _count; private ulong _count;
private List<StackInfo> _stacks; private List<StackInfo> _stacks;
internal AllocationInfo(string typeName) internal AllocationInfo( string typeName )
{ {
_typeName = typeName; _typeName = typeName;
_stacks = new List<StackInfo>(); _stacks = new List<StackInfo>();
@ -84,30 +84,31 @@ namespace Tracing
public ulong Size => _size; public ulong Size => _size;
public IReadOnlyList<StackInfo> Stacks => _stacks; public IReadOnlyList<StackInfo> Stacks => _stacks;
internal void AddAllocation(ulong size, ulong count) internal void AddAllocation( ulong size, ulong count )
{ {
_count += count; _count += count;
_size += size; _size += size;
} }
internal void AddStack(AddressStack stack) internal void AddStack( AddressStack stack )
{ {
var info = GetInfo(stack); var info = GetInfo( stack );
if (info == null) if( info == null )
{ {
info = new StackInfo(stack); info = new StackInfo( stack );
_stacks.Add(info); _stacks.Add( info );
} }
info.Count++; info.Count++;
} }
private StackInfo GetInfo(AddressStack stack) private StackInfo GetInfo( AddressStack stack )
{ {
for (int i = 0; i < _stacks.Count; i++) for( int i = 0; i < _stacks.Count; i++ )
{ {
var info = _stacks[i]; var info = _stacks[i];
if (stack.Equals(info.Stack)) return info; if( stack.Equals( info.Stack ) )
return info;
} }
return null; return null;
@ -119,7 +120,7 @@ namespace Tracing
private readonly AddressStack _stack; private readonly AddressStack _stack;
public ulong Count; public ulong Count;
internal StackInfo(AddressStack stack) internal StackInfo( AddressStack stack )
{ {
Count = 0; Count = 0;
_stack = stack; _stack = stack;

View File

@ -8,7 +8,7 @@ namespace Tracing
{ {
private readonly Dictionary<ulong, string> _typesIdToName; private readonly Dictionary<ulong, string> _typesIdToName;
public ProcessTypeMapping(int processId) public ProcessTypeMapping( int processId )
{ {
ProcessId = processId; ProcessId = processId;
_typesIdToName = new Dictionary<ulong, string>(); _typesIdToName = new Dictionary<ulong, string>();
@ -20,7 +20,7 @@ namespace Tracing
{ {
get get
{ {
if (!_typesIdToName.ContainsKey(id)) if( !_typesIdToName.ContainsKey( id ) )
return null; return null;
return _typesIdToName[id]; return _typesIdToName[id];

View File

@ -182,7 +182,7 @@ public class Ref<T> : Ref where T : class, new()
// Let's assume you'll add saving logic here. // Let's assume you'll add saving logic here.
// Mgr.Save(value, path); // Example: Needs implementation // Mgr.Save(value, path); // Example: Needs implementation
var immMeta = (value as imm.Obj)?.Meta; var immMeta = ( value as io.Obj )?.Meta;
@ -433,10 +433,10 @@ public static class Mgr
var loadedObject = loaderHolder.Load( filename, reason, dbgName, dbgPath, dbgLine ); var loadedObject = loaderHolder.Load( filename, reason, dbgName, dbgPath, dbgLine );
if( loadedObject is T value ) if( loadedObject is T value )
{ {
var meta = (value as imm.Obj)?.Meta; var meta = ( value as io.Obj )?.Meta;
// If it's an immutable object, record its loading. // If it's an immutable object, record its loading.
if( value is imm.Obj imm ) if( value is io.Obj imm )
{ {
return (T)imm.Record( $"Loading bcs {reason}", dbgName, dbgPath, dbgLine ); return (T)imm.Record( $"Loading bcs {reason}", dbgName, dbgPath, dbgLine );
} }

Some files were not shown because too many files have changed in this diff Show More