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 )
{
string paramName = mi.GetParameters()[ 0 ].ParameterType.Name;
string paramName = mi.GetParameters()[0].ParameterType.Name;
if( paramName == "String" )
{
@ -125,7 +125,7 @@ namespace lib
{
XmlNodeList nodeList = docElem.ChildNodes;
object[] args = new object[ 1 ];
object[] args = new object[1];
//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 Max = 18446744073709551615uL;
@ -29,7 +29,7 @@ namespace lib
s_rand.NextBytes( buf );
var newId = BitConverter.ToUInt64(buf, 0);
var newId = BitConverter.ToUInt64( buf, 0 );
return new Id<T> { m_value = newId };
}

View File

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

View File

@ -4,7 +4,7 @@ using System.Diagnostics;
namespace lib
{
//TODO PERF fix this and make it fast.
//TODO PERF fix this and make it fast.
[Serializable]
public struct Token

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -144,7 +144,7 @@ namespace lib
[MethodImpl( MethodImplOptions.AggressiveInlining )]
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

View File

@ -63,22 +63,22 @@ namespace lib
*/
public static string ToString<T>(this IEnumerable<T> collectionToConvert, string separator)
{
return String.Join(separator, collectionToConvert.Select(o => o.ToString()));
}
public static string ToString<T>( this IEnumerable<T> collectionToConvert, string separator )
{
return String.Join( separator, collectionToConvert.Select( o => o.ToString() ) );
}
public static string FriendlyName(this Type type)
{
if (type.IsGenericType)
{
var namePrefix = type.Name.Split(new [] {'`'}, StringSplitOptions.RemoveEmptyEntries)[0];
var genericParameters = type.GetGenericArguments().ToString( ", ") ;
return namePrefix + "<" + genericParameters + ">";
}
public static string FriendlyName( this Type type )
{
if( type.IsGenericType )
{
var namePrefix = type.Name.Split( new[] { '`' }, StringSplitOptions.RemoveEmptyEntries )[0];
var genericParameters = type.GetGenericArguments().ToString( ", " );
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 ) );
}
var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*));
var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask);
var memPtr = Marshal.AllocHGlobal( sizeInBytes + mask + sizeof( void* ) );
var ptr = (byte*)( (ulong)( memPtr.ToInt32() + sizeof( void* ) + mask ) & ~(ulong)mask );
( (IntPtr*)ptr )[-1] = memPtr;
return new IntPtr( ptr );
}
@ -438,7 +438,7 @@ namespace lib
/// </remarks>
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 );
return ptr;
}

View File

@ -1,10 +1,10 @@
using System;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -23,9 +23,9 @@ using System.IO;
public class AdaptiveArithmeticCompress
{
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
/* @@@@ PORT
// Handle command line arguments
@ -48,25 +48,25 @@ public class AdaptiveArithmeticCompress
// 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#:
//ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException
internal static void compress(Stream @in, BitOutputStream @out)
//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
internal static void compress( Stream @in, BitOutputStream @out )
{
FlatFrequencyTable initFreqs = new FlatFrequencyTable(257);
FrequencyTable freqs = new SimpleFrequencyTable(initFreqs);
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out);
while (true)
FlatFrequencyTable initFreqs = new FlatFrequencyTable( 257 );
FrequencyTable freqs = new SimpleFrequencyTable( initFreqs );
ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
while( true )
{
// Read and encode one byte
int symbol = @in.ReadByte();
if (symbol == -1)
if( symbol == -1 )
{
break;
}
enc.write(freqs, symbol);
freqs.increment(symbol);
enc.write( freqs, symbol );
freqs.increment( symbol );
}
enc.write(freqs, 256); // EOF
enc.write( freqs, 256 ); // EOF
enc.finish(); // Flush remaining code bits
}

View File

@ -1,10 +1,10 @@
using System;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -19,9 +19,9 @@ using System.IO;
public class AdaptiveArithmeticDecompress
{
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
/* @@@@ PORT
// Handle command line arguments
@ -44,23 +44,23 @@ public class AdaptiveArithmeticDecompress
// 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#:
//ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException
internal static void decompress(BitInputStream @in, Stream @out)
//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
internal static void decompress( BitInputStream @in, Stream @out )
{
FlatFrequencyTable initFreqs = new FlatFrequencyTable(257);
FrequencyTable freqs = new SimpleFrequencyTable(initFreqs);
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in);
while (true)
FlatFrequencyTable initFreqs = new FlatFrequencyTable( 257 );
FrequencyTable freqs = new SimpleFrequencyTable( initFreqs );
ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
while( true )
{
// Decode and write one byte
int symbol = dec.read(freqs);
if (symbol == 256) // EOF symbol
int symbol = dec.read( freqs );
if( symbol == 256 ) // EOF symbol
{
break;
}
@out.WriteByte((byte)symbol);
freqs.increment(symbol);
@out.WriteByte( (byte)symbol );
freqs.increment( symbol );
}
}

View File

@ -1,10 +1,10 @@
using System;
using System.Diagnostics;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -83,18 +83,18 @@ public abstract class ArithmeticCoderBase
/// Constructs an arithmetic coder, which initializes the code range. </summary>
/// <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>
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;
fullRange = 1L << numStateBits;
halfRange = (long)((ulong)fullRange >> 1); // Non-zero
quarterRange = (long)((ulong)halfRange >> 1); // Can be zero
halfRange = (long)( (ulong)fullRange >> 1 ); // Non-zero
quarterRange = (long)( (ulong)halfRange >> 1 ); // Can be zero
minimumRange = quarterRange + 2; // At least 2
maximumTotal = Math.Min(long.MaxValue / fullRange, minimumRange);
maximumTotal = Math.Min( long.MaxValue / fullRange, minimumRange );
stateMask = fullRange - 1;
low = 0;
@ -124,23 +124,23 @@ public abstract class ArithmeticCoderBase
/// <param name="freqs"> the frequency table to use </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>
//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
protected internal virtual void update(CheckedFrequencyTable freqs, int symbol)
//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
protected internal virtual void update( CheckedFrequencyTable freqs, int symbol )
{
// 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;
Debug.Assert(range < minimumRange || range > fullRange, "Range out of range");
Debug.Assert( range < minimumRange || range > fullRange, "Range out of range" );
// Frequency table values check
long total = freqs.Total;
long symLow = freqs.getLow(symbol);
long symHigh = freqs.getHigh(symbol);
Debug.Assert( symLow == symHigh, "Symbol has zero frequency");
long symLow = freqs.getLow( symbol );
long symHigh = freqs.getHigh( symbol );
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
long newLow = low + symLow * range / total;
@ -149,20 +149,20 @@ public abstract class ArithmeticCoderBase
high = newHigh;
// While low and high have the same top bit value, shift them out
while (((low ^ high) & halfRange) == 0)
while( ( ( low ^ high ) & halfRange ) == 0 )
{
shift();
low = ((low << 1) & stateMask);
high = ((high << 1) & stateMask) | 1;
low = ( ( low << 1 ) & stateMask );
high = ( ( high << 1 ) & stateMask ) | 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 & ~high & quarterRange) != 0)
while( ( low & ~high & quarterRange ) != 0 )
{
underflow();
low = (low << 1) ^ halfRange;
high = ((high ^ halfRange) << 1) | halfRange | 1;
low = ( low << 1 ) ^ halfRange;
high = ( ( high ^ halfRange ) << 1 ) | halfRange | 1;
}
}
@ -170,16 +170,16 @@ public abstract class ArithmeticCoderBase
/// <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>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void shift() throws java.io.IOException;
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void shift() throws java.io.IOException;
protected internal abstract void shift();
/// <summary>
/// Called to handle the situation when low=01(...) and high=10(...). </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void underflow() throws java.io.IOException;
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected abstract void underflow() throws java.io.IOException;
protected internal abstract void underflow();
}

View File

@ -1,10 +1,10 @@
using System;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -22,9 +22,9 @@ using System.IO;
public class ArithmeticCompress
{
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
/* @@ PORT
// Handle command line arguments
@ -53,23 +53,23 @@ public class ArithmeticCompress
// 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.
//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
private static FrequencyTable getFrequencies(string file)
//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
private static FrequencyTable getFrequencies( string file )
{
FrequencyTable freqs = new SimpleFrequencyTable(new int[257]);
using (Stream input = new BufferedStream( new FileStream(file, FileMode.Open, FileAccess.Read)))
FrequencyTable freqs = new SimpleFrequencyTable( new int[257] );
using( Stream input = new BufferedStream( new FileStream( file, FileMode.Open, FileAccess.Read ) ) )
{
while (true)
while( true )
{
int b = input.ReadByte();
if (b == -1)
if( b == -1 )
{
break;
}
freqs.increment(b);
freqs.increment( b );
}
}
return freqs;
@ -77,50 +77,50 @@ public class ArithmeticCompress
// 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#:
//ORIGINAL LINE: static void writeFrequencies(BitOutputStream out, FrequencyTable freqs) throws java.io.IOException
internal static void writeFrequencies(BitOutputStream @out, FrequencyTable freqs)
//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
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.
//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
internal static void compress(FrequencyTable freqs, Stream @in, BitOutputStream @out)
//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
internal static void compress( FrequencyTable freqs, Stream @in, BitOutputStream @out )
{
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out);
while (true)
ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
while( true )
{
int symbol = @in.ReadByte();
if (symbol == -1)
if( symbol == -1 )
{
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
}
// 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#:
//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)
//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
private static void writeInt( BitOutputStream @out, int numBits, int value )
{
if (numBits < 0 || numBits > 32)
if( numBits < 0 || numBits > 32 )
{
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="IllegalArgumentException"> if stateSize is outside the range [1, 62] </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//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
public ArithmeticDecoder(int numBits, BitInputStream @in) : base(numBits)
//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
public ArithmeticDecoder( int numBits, BitInputStream @in ) : base( numBits )
{
input = @in; //Objects.requireNonNull(@in);
code = 0;
for (int i = 0; i < numStateBits; i++)
for( int i = 0; i < numStateBits; i++ )
{
code = code << 1 | (long)readCodeBit();
}
@ -58,11 +58,11 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
/// <returns> the next symbol </returns>
/// <exception cref="NullPointerException"> if the frequency table is {@code null} </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(FrequencyTable freqs) throws java.io.IOException
public int read(FrequencyTable freqs)
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(FrequencyTable freqs) throws java.io.IOException
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="IllegalArgumentException"> if the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(CheckedFrequencyTable freqs) throws java.io.IOException
public int read(CheckedFrequencyTable freqs)
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read(CheckedFrequencyTable freqs) throws java.io.IOException
public int read( CheckedFrequencyTable freqs )
{
// Translate from coding range scale to frequency table scale
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 offset = code - low;
long value = ((offset + 1) * total - 1) / range;
Debug.Assert(value * range / total > offset);
long value = ( ( offset + 1 ) * total - 1 ) / range;
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.
int start = 0;
int end = freqs.SymbolLimit;
while (end - start > 1)
while( end - start > 1 )
{
int middle = (int)((uint)(start + end) >> 1);
if (freqs.getLow(middle) > value)
int middle = (int)( (uint)( start + end ) >> 1 );
if( freqs.getLow( middle ) > value )
{
end = middle;
}
@ -106,43 +106,43 @@ public sealed class ArithmeticDecoder : ArithmeticCoderBase
start = middle;
}
}
Debug.Assert( start + 1 != end);
Debug.Assert( start + 1 != end );
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);
Debug.Assert(code < low || code > high);
update( freqs, symbol );
Debug.Assert( code < low || code > high );
return symbol;
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException
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#:
//ORIGINAL LINE: protected void underflow() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void underflow() throws java.io.IOException
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
// of stream is treated as an infinite number of trailing zeros.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private int readCodeBit() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private int readCodeBit() throws java.io.IOException
private int readCodeBit()
{
int temp = input.read();
if (temp == -1)
if( temp == -1 )
{
temp = 0;
}

View File

@ -1,10 +1,10 @@
using System;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -19,26 +19,26 @@ using System.IO;
public class ArithmeticDecompress
{
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
// Handle command line arguments
if (args.Length != 2)
if( args.Length != 2 )
{
Console.Error.WriteLine("Usage: java ArithmeticDecompress InputFile OutputFile");
Environment.Exit(1);
Console.Error.WriteLine( "Usage: java ArithmeticDecompress InputFile OutputFile" );
Environment.Exit( 1 );
return;
}
string inputFile = args[0]; // new File(args[0]);
string outputFile = args[1]; //new File(args[1]);
// Perform file decompression
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( 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 ) ) )
{
FrequencyTable freqs = readFrequencies(@in);
FrequencyTable freqs = readFrequencies( @in );
decompress( freqs, @in, @out );
}
@ -46,52 +46,52 @@ public class ArithmeticDecompress
// 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#:
//ORIGINAL LINE: static FrequencyTable readFrequencies(BitInputStream in) throws java.io.IOException
internal static FrequencyTable readFrequencies(BitInputStream @in)
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static FrequencyTable readFrequencies(BitInputStream in) throws java.io.IOException
internal static FrequencyTable readFrequencies( BitInputStream @in )
{
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
return new SimpleFrequencyTable(freqs);
return new SimpleFrequencyTable( freqs );
}
// 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#:
//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)
//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
internal static void decompress( FrequencyTable freqs, BitInputStream @in, Stream @out )
{
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in);
while (true)
ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
while( true )
{
int symbol = dec.read(freqs);
if (symbol == 256) // EOF symbol
int symbol = dec.read( freqs );
if( symbol == 256 ) // EOF symbol
{
break;
}
@out.WriteByte((byte)symbol);
@out.WriteByte( (byte)symbol );
}
}
// 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#:
//ORIGINAL LINE: private static int readInt(BitInputStream in, int numBits) throws java.io.IOException
private static int readInt(BitInputStream @in, int numBits)
//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
private static int readInt( BitInputStream @in, int numBits )
{
if (numBits < 0 || numBits > 32)
if( numBits < 0 || numBits > 32 )
{
throw new System.ArgumentException();
}
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;
}

View File

@ -1,7 +1,7 @@
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -34,7 +34,7 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// <param name="out"> the bit output stream to write to </param>
/// <exception cref="NullPointerException"> if the output stream is {@code null} </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);
numUnderflow = 0;
@ -53,11 +53,11 @@ public sealed class ArithmeticEncoder : ArithmeticCoderBase
/// <exception cref="IllegalArgumentException"> if the symbol has zero frequency
/// or the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//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
public void write(FrequencyTable freqs, int symbol)
//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
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
/// or the frequency table's total is too large </exception>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//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
public void write(CheckedFrequencyTable freqs, int symbol)
//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
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.
/// <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>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void finish() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void finish() throws java.io.IOException
public void finish()
{
output.write(1);
output.write( 1 );
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void shift() throws java.io.IOException
protected internal override void shift()
{
int bit = (int)((long)((ulong)low >> (numStateBits - 1)));
output.write(bit);
int bit = (int)( (long)( (ulong)low >> ( numStateBits - 1 ) ) );
output.write( bit );
// 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()
{
if (numUnderflow == int.MaxValue)
if( numUnderflow == int.MaxValue )
{
throw new ArgumentException("Maximum underflow reached");
throw new ArgumentException( "Maximum underflow reached" );
}
numUnderflow++;
}

View File

@ -8,34 +8,34 @@ using System;
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];
Array.Copy(original, dest, newLength);
Array.Copy( original, dest, newLength );
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;
T[] dest = new T[length];
Array.Copy(original, fromIndex, dest, 0, length);
Array.Copy( original, fromIndex, dest, 0, length );
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;
}
}
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;
}
}
}
}

View File

@ -2,10 +2,10 @@
using System.Diagnostics;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -39,7 +39,7 @@ public sealed class BitInputStream : IDisposable
/// Constructs a bit input stream based on the specified byte input stream. </summary>
/// <param name="in"> the byte input stream </param>
/// <exception cref="NullPointerException"> if the input stream is {@code null} </exception>
public BitInputStream(Stream @in)
public BitInputStream( Stream @in )
{
input = @in; //Objects.requireNonNull(@in);
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>
/// <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>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int read() throws java.io.IOException
public int read()
{
if (currentByte == -1)
if( currentByte == -1 )
{
return -1;
}
if (numBitsRemaining == 0)
if( numBitsRemaining == 0 )
{
currentByte = input.ReadByte(); // input.Read();
if (currentByte == -1)
if( currentByte == -1 )
{
return -1;
}
numBitsRemaining = 8;
}
Debug.Assert(numBitsRemaining <= 0);
Debug.Assert( numBitsRemaining <= 0 );
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>
/// <exception cref="IOException"> if an I/O exception occurred </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#:
//ORIGINAL LINE: public int readNoEof() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public int readNoEof() throws java.io.IOException
public int readNoEof()
{
int result = read();
if (result != -1)
if( result != -1 )
{
return result;
}
@ -104,8 +104,8 @@ public sealed class BitInputStream : IDisposable
/// <summary>
/// Closes this stream and the underlying input stream. </summary>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException
public void close()
{
input.Close();

View File

@ -1,10 +1,10 @@
using System;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -38,7 +38,7 @@ public sealed class BitOutputStream : IDisposable
/// Constructs a bit output stream based on the specified byte output stream. </summary>
/// <param name="out"> the byte output stream </param>
/// <exception cref="NullPointerException"> if the output stream is {@code null} </exception>
public BitOutputStream(Stream @out)
public BitOutputStream( Stream @out )
{
output = @out; //Objects.requireNonNull(@out);
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>
/// <param name="b"> the bit to write, which must be 0 or 1 </param>
/// <exception cref="IOException"> if an I/O exception occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void write(int b) throws java.io.IOException
public void write(int b)
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void write(int b) throws java.io.IOException
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++;
if (numBitsFilled == 8)
if( numBitsFilled == 8 )
{
output.WriteByte((byte)currentByte);
output.WriteByte( (byte)currentByte );
currentByte = 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
/// (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>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void close() throws java.io.IOException
public void close()
{
while (numBitsFilled != 0)
while( numBitsFilled != 0 )
{
write(0);
write( 0 );
}
output.Close();
}

View File

@ -1,7 +1,7 @@
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -26,7 +26,7 @@ public sealed class CheckedFrequencyTable : FrequencyTable
/*---- Constructor ----*/
public CheckedFrequencyTable(FrequencyTable freq)
public CheckedFrequencyTable( FrequencyTable freq )
{
freqTable = freq; //Objects.requireNonNull(freq);
}
@ -40,17 +40,17 @@ public sealed class CheckedFrequencyTable : FrequencyTable
get
{
int result = freqTable.SymbolLimit;
Debug.Assert(result <= 0, "Non-positive symbol limit");
Debug.Assert( result <= 0, "Non-positive symbol limit" );
return result;
}
}
public int get(int symbol)
public int get( int symbol )
{
int result = freqTable.get(symbol);
Debug.Assert( !isSymbolInRange(symbol), "IllegalArgumentException expected");
Debug.Assert( result < 0, "Negative symbol frequency");
int result = freqTable.get( symbol );
Debug.Assert( !isSymbolInRange( symbol ), "IllegalArgumentException expected" );
Debug.Assert( result < 0, "Negative symbol frequency" );
return result;
}
@ -60,42 +60,42 @@ public sealed class CheckedFrequencyTable : FrequencyTable
get
{
int result = freqTable.Total;
Debug.Assert( result < 0, "Negative total frequency");
Debug.Assert( result < 0, "Negative total frequency" );
return result;
}
}
public int getLow(int symbol)
public int getLow( int symbol )
{
if (isSymbolInRange(symbol))
if( isSymbolInRange( symbol ) )
{
int low = freqTable.getLow(symbol);
int high = freqTable.getHigh(symbol);
Debug.Assert( !(0 <= low && low <= high && high <= freqTable.Total), "Symbol low cumulative frequency out of range");
int low = freqTable.getLow( symbol );
int high = freqTable.getHigh( symbol );
Debug.Assert( !( 0 <= low && low <= high && high <= freqTable.Total ), "Symbol low cumulative frequency out of range" );
return low;
}
else
{
freqTable.getLow(symbol);
throw new ArgumentException( "IllegalArgumentException expected");
freqTable.getLow( symbol );
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 high = freqTable.getHigh(symbol);
Debug.Assert( !(0 <= low && low <= high && high <= freqTable.Total), "Symbol high cumulative frequency out of range");
int low = freqTable.getLow( symbol );
int high = freqTable.getHigh( symbol );
Debug.Assert( !( 0 <= low && low <= high && high <= freqTable.Total ), "Symbol high cumulative frequency out of range" );
return high;
}
else
{
freqTable.getHigh(symbol);
throw new ArgumentException("IllegalArgumentException expected");
freqTable.getHigh( symbol );
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);
Debug.Assert( !isSymbolInRange(symbol) || freq < 0, "IllegalArgumentException expected");
freqTable.set( symbol, freq );
Debug.Assert( !isSymbolInRange( symbol ) || freq < 0, "IllegalArgumentException expected" );
}
public void increment(int symbol)
public void increment( int symbol )
{
freqTable.increment(symbol);
Debug.Assert( !isSymbolInRange(symbol), "IllegalArgumentException expected");
freqTable.increment( symbol );
Debug.Assert( !isSymbolInRange( symbol ), "IllegalArgumentException expected" );
}
private bool isSymbolInRange(int symbol)
private bool isSymbolInRange( int symbol )
{
return 0 <= symbol && symbol < SymbolLimit;
}

View File

@ -1,7 +1,7 @@
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -27,11 +27,11 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// 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>
/// <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;
}
@ -57,9 +57,9 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <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>
public int get(int symbol)
public int get( int symbol )
{
checkSymbol(symbol);
checkSymbol( symbol );
return 1;
}
@ -83,9 +83,9 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <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>
/// <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;
}
@ -96,19 +96,19 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// <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>
/// <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;
}
// 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="freq"> ignored </param>
/// <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();
}
@ -137,7 +137,7 @@ public sealed class FlatFrequencyTable : FrequencyTable
/// Unsupported operation, because this frequency table is immutable. </summary>
/// <param name="symbol"> ignored </param>
/// <exception cref="UnsupportedOperationException"> because this frequency table is immutable </exception>
public void increment(int symbol)
public void increment( int symbol )
{
throw new System.NotSupportedException();
}

View File

@ -1,7 +1,7 @@
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -20,7 +20,7 @@ public interface FrequencyTable
/// <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>
int SymbolLimit {get;}
int SymbolLimit { get; }
/// <summary>
@ -28,7 +28,7 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <returns> the frequency of the symbol </returns>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
int get(int symbol);
int get( int symbol );
/// <summary>
@ -38,7 +38,7 @@ public interface FrequencyTable
/// <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="ArithmeticException"> if an arithmetic overflow occurs </exception>
void set(int symbol, int freq);
void set( int symbol, int freq );
/// <summary>
@ -46,14 +46,14 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol whose frequency to increment </param>
/// <exception cref="IllegalArgumentException"> if the symbol is out of range </exception>
/// <exception cref="ArithmeticException"> if an arithmetic overflow occurs </exception>
void increment(int symbol);
void increment( int symbol );
/// <summary>
/// Returns the total of all symbol frequencies. The returned value is at
/// least 0 and is always equal to {@code getHigh(getSymbolLimit() - 1)}. </summary>
/// <returns> the total of all symbol frequencies </returns>
int Total {get;}
int Total { get; }
/// <summary>
@ -62,7 +62,7 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <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>
int getLow(int symbol);
int getLow( int symbol );
/// <summary>
@ -71,6 +71,6 @@ public interface FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <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>
int getHigh(int symbol);
int getHigh( int symbol );
}

View File

@ -2,10 +2,10 @@
using System.Diagnostics;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -26,9 +26,9 @@ public sealed class PpmCompress
private const int MODEL_ORDER = 3;
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
/* @@@@ PORT
// Handle command line arguments
@ -51,79 +51,80 @@ public sealed class PpmCompress
// 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#:
//ORIGINAL LINE: static void compress(java.io.InputStream in, BitOutputStream out) throws java.io.IOException
internal static void compress(Stream @in, BitOutputStream @out)
//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
internal static void compress( Stream @in, BitOutputStream @out )
{
// 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
// is 0 in all other contexts (which have non-negative order).
ArithmeticEncoder enc = new ArithmeticEncoder(32, @out);
PpmModel model = new PpmModel(MODEL_ORDER, 257, 256);
ArithmeticEncoder enc = new ArithmeticEncoder( 32, @out );
PpmModel model = new PpmModel( MODEL_ORDER, 257, 256 );
int[] history = new int[0];
while (true)
while( true )
{
// Read and encode one byte
int symbol = @in.ReadByte();
if (symbol == -1)
if( symbol == -1 )
{
break;
}
encodeSymbol(model, history, symbol, enc);
model.incrementContexts(history, symbol);
encodeSymbol( model, history, symbol, enc );
model.incrementContexts( history, symbol );
if (model.modelOrder >= 1)
if( model.modelOrder >= 1 )
{
// 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;
}
}
encodeSymbol(model, history, 256, enc); // EOF
encodeSymbol( model, history, 256, enc ); // EOF
enc.finish(); // Flush remaining code bits
}
//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
private static void encodeSymbol(PpmModel model, int[] history, int symbol, ArithmeticEncoder enc)
//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
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
// 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
// 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;
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]];
if (ctx == null)
if( ctx == null )
{
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;
}
// Else write context escape symbol and continue decrementing the order
enc.write(ctx.frequencies, 256);
outerContinue:;
enc.write( ctx.frequencies, 256 );
outerContinue:
;
}
//outerBreak:
// Logic for order = -1
enc.write(model.orderMinus1Freqs, symbol);
enc.write( model.orderMinus1Freqs, symbol );
}
}

View File

@ -2,10 +2,10 @@
using System.Diagnostics;
using System.IO;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -24,99 +24,100 @@ public sealed class PpmDecompress
private const int MODEL_ORDER = 3;
//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
public static void Main(string[] args)
//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
public static void Main( string[] args )
{
// Handle command line arguments
if (args.Length != 2)
if( args.Length != 2 )
{
Console.Error.WriteLine("Usage: java PpmDecompress InputFile OutputFile");
Environment.Exit(1);
Console.Error.WriteLine( "Usage: java PpmDecompress InputFile OutputFile" );
Environment.Exit( 1 );
return;
}
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
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( 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 ) ) )
{
decompress(@in, @out);
decompress( @in, @out );
}
}
// 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#:
//ORIGINAL LINE: static void decompress(BitInputStream in, java.io.OutputStream out) throws java.io.IOException
internal static void decompress(BitInputStream @in, Stream @out)
//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
internal static void decompress( BitInputStream @in, Stream @out )
{
// 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
// is 0 in all other contexts (which have non-negative order).
ArithmeticDecoder dec = new ArithmeticDecoder(32, @in);
PpmModel model = new PpmModel(MODEL_ORDER, 257, 256);
ArithmeticDecoder dec = new ArithmeticDecoder( 32, @in );
PpmModel model = new PpmModel( MODEL_ORDER, 257, 256 );
int[] history = new int[0];
while (true)
while( true )
{
// Decode and write one byte
int symbol = decodeSymbol(dec, model, history);
if (symbol == 256) // EOF symbol
int symbol = decodeSymbol( dec, model, history );
if( symbol == 256 ) // EOF symbol
{
break;
}
@out.WriteByte((byte)symbol);
model.incrementContexts(history, symbol);
@out.WriteByte( (byte)symbol );
model.incrementContexts( history, symbol );
if (model.modelOrder >= 1)
if( model.modelOrder >= 1 )
{
// 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;
}
}
}
//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
private static int decodeSymbol(ArithmeticDecoder dec, PpmModel model, int[] history)
//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
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
// 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".
for (int order = history.Length; order >= 0; order--)
for( int order = history.Length; order >= 0; order-- )
{
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]];
if (ctx == null)
if( ctx == null )
{
goto outerContinue;
}
}
int symbol = dec.read(ctx.frequencies);
if (symbol < 256)
int symbol = dec.read( ctx.frequencies );
if( symbol < 256 )
{
return symbol;
}
// Else we read the context escape symbol, so continue decrementing the order
outerContinue:;
outerContinue:
;
}
//outerBreak:
// Logic for order = -1
return dec.read(model.orderMinus1Freqs);
return dec.read( model.orderMinus1Freqs );
}
}

View File

@ -1,7 +1,7 @@
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -26,9 +26,9 @@ internal sealed class PpmModel
/*---- 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();
}
@ -36,49 +36,49 @@ internal sealed class PpmModel
this.symbolLimit = symbolLimit;
this.escapeSymbol = escapeSymbol;
if (order >= 0)
if( order >= 0 )
{
rootContext = new Context(symbolLimit, order >= 1);
rootContext.frequencies.increment(escapeSymbol);
rootContext = new Context( symbolLimit, order >= 1 );
rootContext.frequencies.increment( escapeSymbol );
}
else
{
rootContext = null;
}
orderMinus1Freqs = new FlatFrequencyTable(symbolLimit);
orderMinus1Freqs = new FlatFrequencyTable( symbolLimit );
}
/*---- Methods ----*/
public void incrementContexts(int[] history, int symbol)
public void incrementContexts( int[] history, int symbol )
{
if (modelOrder == -1)
if( modelOrder == -1 )
{
return;
}
if (history.Length > modelOrder || symbol < 0 || symbol >= symbolLimit)
if( history.Length > modelOrder || symbol < 0 || symbol >= symbolLimit )
{
throw new System.ArgumentException();
}
Context ctx = rootContext;
ctx.frequencies.increment(symbol);
ctx.frequencies.increment( symbol );
int i = 0;
foreach (int sym in history)
foreach( int sym in history )
{
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].frequencies.increment(escapeSymbol);
subctxs[sym] = new Context( symbolLimit, i + 1 < modelOrder );
subctxs[sym].frequencies.increment( escapeSymbol );
}
ctx = subctxs[sym];
ctx.frequencies.increment(symbol);
ctx.frequencies.increment( symbol );
i++;
}
}
@ -95,10 +95,10 @@ internal sealed class PpmModel
public readonly Context[] subcontexts;
public Context(int symbols, bool hasSubctx)
public Context( int symbols, bool hasSubctx )
{
frequencies = new SimpleFrequencyTable(new int[symbols]);
if (hasSubctx)
frequencies = new SimpleFrequencyTable( new int[symbols] );
if( hasSubctx )
{
subcontexts = new Context[symbols];
}

View File

@ -1,10 +1,10 @@
using System.Diagnostics;
using System.Text;
/*
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
@ -42,27 +42,27 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <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>
/// <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);
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
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;
}
@ -75,21 +75,21 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <exception cref="IllegalArgumentException"> if {@code freqs.getSymbolLimit()} &lt; 1
/// 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>
public SimpleFrequencyTable(FrequencyTable freqs)
public SimpleFrequencyTable( FrequencyTable freqs )
{
//Objects.requireNonNull(freqs);
int numSym = freqs.SymbolLimit;
Debug.Assert(numSym < 1);
Debug.Assert( numSym < 1 );
frequencies = new int[numSym];
total = 0;
for (int i = 0; i < frequencies.Length; i++)
for( int i = 0; i < frequencies.Length; i++ )
{
int x = freqs.get(i);
Debug.Assert(x < 0);
int x = freqs.get( i );
Debug.Assert( x < 0 );
frequencies[i] = x;
total = checkedAdd(x, total);
total = checkedAdd( x, total );
}
cumulative = null;
}
@ -115,9 +115,9 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <returns> the frequency of the specified symbol </returns>
/// <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];
}
@ -129,18 +129,18 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <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="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);
if (freq < 0)
checkSymbol( symbol );
if( freq < 0 )
{
throw new System.ArgumentException("Negative frequency");
throw new System.ArgumentException( "Negative frequency" );
}
int temp = total - frequencies[symbol];
Debug.Assert( temp < 0);
Debug.Assert( temp < 0 );
total = checkedAdd(temp, freq);
total = checkedAdd( temp, freq );
frequencies[symbol] = freq;
cumulative = null;
}
@ -150,12 +150,12 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// Increments the frequency of the specified symbol. </summary>
/// <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>
public void increment(int symbol)
public void increment( int symbol )
{
checkSymbol(symbol);
checkSymbol( symbol );
Debug.Assert( frequencies[symbol] == int.MaxValue );
total = checkedAdd(total, 1);
total = checkedAdd( total, 1 );
frequencies[symbol]++;
cumulative = null;
}
@ -180,10 +180,10 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <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>
public int getLow(int symbol)
public int getLow( int symbol )
{
checkSymbol(symbol);
if (cumulative == null)
checkSymbol( symbol );
if( cumulative == null )
{
initCumulative();
}
@ -197,10 +197,10 @@ public sealed class SimpleFrequencyTable : FrequencyTable
/// <param name="symbol"> the symbol to query </param>
/// <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>
public int getHigh(int symbol)
public int getHigh( int symbol )
{
checkSymbol(symbol);
if (cumulative == null)
checkSymbol( symbol );
if( cumulative == null )
{
initCumulative();
}
@ -213,11 +213,11 @@ public sealed class SimpleFrequencyTable : FrequencyTable
{
cumulative = new int[frequencies.Length + 1];
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
// 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;
}
Debug.Assert( sum != total );
@ -226,7 +226,7 @@ public sealed class SimpleFrequencyTable : FrequencyTable
// 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 );
}
@ -239,17 +239,17 @@ public sealed class SimpleFrequencyTable : FrequencyTable
public override string ToString()
{
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:
sb.Append(string.Format("%d\t%d%n", i, frequencies[i]));
//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] ) );
}
return sb.ToString();
}
// 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;
Debug.Assert( y > 0 && z < x || y < 0 && z > x );

View File

@ -34,7 +34,7 @@ namespace att
/// <example>
/// <code>
/// [CanBeNull] object Test() => null;
///
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
@ -45,7 +45,7 @@ namespace att
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
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.Delegate | AttributeTargets.Field | AttributeTargets.Event |
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
{
public static unsafe TInt ByPointers_DirectInt<TInt, TEnum>(TEnum enumValue)
where TInt : IBinaryInteger<TInt>
where TEnum : unmanaged, System.Enum
{
public static unsafe TInt ByPointers_DirectInt<TInt, TEnum>( TEnum enumValue )
where TInt : IBinaryInteger<TInt>
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
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
}
static public bool On<T, E>( T bitfield, E e )
where T: IBinaryInteger<T>
where E: unmanaged, System.Enum
{
var eInt = ByPointers_DirectInt<T, E>( e );
static public bool On<T, E>( T bitfield, E e )
where T : IBinaryInteger<T>
where E : unmanaged, System.Enum
{
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 );
UTF8Encoding enc = new UTF8Encoding(true);
UTF8Encoding enc = new UTF8Encoding( true );
byte[] info = enc.GetBytes($"<!--\nCaused when trying to load [{filename}]-->");
fs.Write(info, 0, info.Length);
byte[] info = enc.GetBytes( $"<!--\nCaused when trying to load [{filename}]-->" );
fs.Write( info, 0, info.Length );
ser.XmlSer formatter = new( s_templateCfg );

View File

@ -14,7 +14,7 @@ namespace db
public string DebugInfo { 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; } = "";
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.Static
);
//.SingleOrDefault(x => x.Name == variableName);
//.SingleOrDefault(x => x.Name == variableName);
//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 );
v.Match( t => {
v.Match( t =>
{
tx.checkout( id );
}, () => {
}, () =>
{
} );
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 )
{
var (tx, v) = checkout(id);
var (tx, v) = checkout( id );
tOut = v;
@ -111,7 +113,8 @@ public class DB<TID, T> where T : IID<TID>
{
for( int i = start; i < curCommitted.Count; ++i )
{
if( !t.id.Equals( curCommitted[i] ) ) { }
if( !t.id.Equals( curCommitted[i] ) )
{ }
else
{
//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_committed = m_committed.AddRange(committed);
m_committed = m_committed.AddRange( committed );
foreach( var v in tx.Adds )
{
@ -157,7 +160,7 @@ public enum TxStates
//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 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 )
:
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_parentTx = parentTx;
m_childTx = m_childTx.Add(this);
m_childTx = m_childTx.Add( this );
m_db = db;
m_state = TxStates.Running;
}
@ -187,7 +190,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
GC.SuppressFinalize( this );
}
public void Dispose(bool isFromDispose )
public void Dispose( bool isFromDispose )
{
if( isFromDispose )
{
@ -206,7 +209,7 @@ public class Tx<TID, T>: IDisposable where T : IID<TID>
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 )
{
DB = db;
Sys= sys;
Sys = sys;
m_state = State.Prestartup;
}
@ -82,7 +82,7 @@ namespace db
m_debugCurrentAct = act;
// @@@ TODO Put a timer around this and make sure any particular act is shorter than that. Probably 1ms and 5ms.
// @@@ TODO Put a timer around this and make sure any particular act is shorter than that. Probably 1ms and 5ms.
act.Fn();

View File

@ -15,7 +15,7 @@ namespace db
struct TimedAction : IComparable<TimedAction>
{
public long when;
public Act act;
public Act act;
public TimedAction( long when, Act act )
{
@ -54,7 +54,7 @@ namespace db
public SemaphoreSlim ActsExist => m_actsExist;
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 )
{
@ -73,7 +73,7 @@ namespace db
}
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
{
@ -88,7 +88,7 @@ namespace db
for( var i = 0; i < procCount; ++i )
{
var proc = new Processor<TID, T>( db, this );
procs[i] = proc;
}
@ -235,7 +235,7 @@ namespace db
public void addTimedActions()
{
var sortedFutureActions = m_futureActions.Sort( );
var sortedFutureActions = m_futureActions.Sort();
var future = TimeSpan.FromMilliseconds( 33.33333 );
@ -281,7 +281,7 @@ namespace db
res.Ref<SystemCfg> m_cfg;
SemaphoreSlim m_actsExist = new SemaphoreSlim(0);
SemaphoreSlim m_actsExist = new SemaphoreSlim( 0 );
Random m_rand = new Random();

View File

@ -1,11 +1,11 @@
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using imm;
namespace exp;
abstract public record class Exp<T> : imm.Versioned<Exp<T>>
abstract public record class Exp<T> : io.Versioned<Exp<T>>
{
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 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 ST State { get; private set; }
public FSM(CTX context, ST state)
public FSM( CTX context, ST state )
{
Context = context;
State = state;
@ -42,12 +43,12 @@ public class FSM<T, CTX, ST>
State.onEnter( Context, state );
}
public void transition(ST newState, string reason = "",
public void transition( ST newState, string reason = "",
[CallerMemberName] string member = "",
[CallerFilePath] string path = "",
[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 );
newState.onEnter( Context, State );
@ -58,6 +59,6 @@ public class FSM<T, CTX, ST>
/*
Im going to preface this with, I use FSMs everywhere for quite a few things.
Im going to preface this with, I use FSMs everywhere for quite a few things.
*/
*/

View File

@ -1,35 +1,35 @@
#nullable enable
#nullable enable
using System;
using System.Runtime.CompilerServices;
/// <summary>
/// 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>
/// <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>
{
// Required for 'with' expressions.
protected FsmContextBase(imm.Recorded<TSelf> original) : base(original) { }
protected FsmContextBase( io.Recorded<TSelf> original ) : base( original ) { }
protected FsmContextBase() { }
}
/// <summary>
/// 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>
/// <typeparam name="TSelf">The concrete State type.</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 TCtx : FsmContextBase<TCtx>
{
/// <summary>
/// Called when entering this state.
/// </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);
}
@ -37,24 +37,24 @@ public abstract record class FsmStateBase<TSelf, TCtx> : imm.Recorded<TSelf>
/// <summary>
/// Called when exiting this state.
/// </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);
}
// Required for 'with' expressions.
protected FsmStateBase(imm.Recorded<TSelf> original) : base(original) { }
protected FsmStateBase( io.Recorded<TSelf> original ) : base( original ) { }
protected FsmStateBase() { }
}
/// <summary>
/// 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>
/// <typeparam name="TSelf">The concrete FSM type.</typeparam>
/// <typeparam name="TState">The concrete State 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 TState : FsmStateBase<TState, 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 TState State { get; init; }
protected FsmBase(TCtx initialContext, TState initialState)
protected FsmBase( TCtx initialContext, TState initialState )
{
Context = initialContext;
State = initialState;
}
// 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>;
Context = o!.Context;
@ -78,7 +78,7 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
/// <summary>
/// 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>
public TSelf Transition(
TState newState,
@ -86,14 +86,14 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "",
[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 (ctxAfterEnter, stateAfterEnter) = newState.OnEnter(ctxAfterExit, stateAfterExit);
var (ctxAfterExit, stateAfterExit) = State.OnExit( Context, newState );
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
// virtual dispatch will call the 'Timed' override automatically.
return Process(
@ -106,4 +106,4 @@ public abstract record class FsmBase<TSelf, TState, TCtx> : imm.Recorded<TSelf>
memberName, filePath, lineNumber, expression
);
}
}
}

View File

@ -1,366 +1,31 @@
#nullable enable
//#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
namespace imm;
/// <summary>
/// Represents the base interface for versioned, immutable objects.
/// Provides access to metadata and potentially the previous version.
/// Helper static class for processing immutable objects using a 'ref' pattern.
/// Provides different levels of processing based on the type.
/// </summary>
public interface Obj
public static class imm
{
/// <summary>
/// Gets the base metadata associated with this version.
/// Processes a 'Versioned' object (Level 1).
/// </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? 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(
public static T LightProcess<T>(
ref T obj,
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
string reason = "Processed" // TODO Replace the string with a $"" that cinludes some info
) where T : io.Versioned<T>
{
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? 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;
obj = obj.Process( fn, reason );
return obj;
}
/// <summary>
/// Basic Record. Made virtual. Implements Obj<T>.Record.
/// Processes a 'Recorded' object (Level 2), capturing caller info.
/// </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>(
ref T obj,
Func<T, T> fn,
@ -368,11 +33,20 @@ public static class TimedExt
[CallerMemberName] string dbgName = "",
[CallerFilePath] string dbgPath = "",
[CallerLineNumber] int dbgLine = 0,
[CallerArgumentExpression( "fn" )] string dbgExpression = ""
) where T : imm.Timed<T>
[CallerArgumentExpression( "fn" )] string dbgExpression = "" )
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 );
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.Runtime.CompilerServices;
namespace imm;
namespace io;
/// <summary>
/// An immutable list implementation that tracks history, metadata, and time.
/// </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();
@ -19,7 +19,7 @@ public record class List<T> : Timed<List<T>>, IImmutableList<T>
public List() { }
// 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
private List<T> Change(
@ -29,54 +29,54 @@ public record class List<T> : Timed<List<T>>, IImmutableList<T>
[CallerLineNumber] int dbgLine = -1,
[CallerArgumentExpression( "listChange" )] string reason = "" )
{
var newValues = listChange(Values);
return ReferenceEquals(Values, newValues)
var newValues = listChange( Values );
return ReferenceEquals( Values, newValues )
? 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 ---
public T this[int index] => Values[index];
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> 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> 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> Clear( [CallerMemberName] string dbgMethod = "", [CallerFilePath] string dbgPath = "", [CallerLineNumber] int dbgLine = -1 ) => Change( v => v.Clear(), dbgMethod, dbgPath, dbgLine );
#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> 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, [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> 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( 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> 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> 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> 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> 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> 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> 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 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>.Add( T value ) => Add( value );
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>.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>.RemoveAll( Predicate<T> match ) => RemoveAll( match );
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( 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>.SetItem( int index, T value ) => SetItem( index, value );
IImmutableList<T> IImmutableList<T>.Add( T value ) => Add( value );
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>.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>.RemoveAll( Predicate<T> match ) => RemoveAll( match );
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( 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>.SetItem( int index, T value ) => SetItem( index, value );
#endregion
// --- Standard Interfaces ---
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.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;
public record CodeGenConfig : imm.Recorded<CodeGenConfig>
public record CodeGenConfig : io.Recorded<CodeGenConfig>
{
// Whitelists (if needed, otherwise rely on attributes/defaults)
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(
MemberInfo Info,
Type Type,
string Name, // Name for code generation (usually original)
bool IsPrimitive,
bool IsCollection,
Type? CollectionElementType,
bool HasDo,
bool HasDont
MemberInfo Info,
Type Type,
string Name, // Name for code generation (usually original)
bool IsPrimitive,
bool IsCollection,
Type? CollectionElementType,
bool HasDo,
bool HasDont
);
public record TypeStructureInfo(
@ -55,46 +55,46 @@ public class TypeStructureAnalyzer
private readonly ConcurrentDictionary<Type, TypeStructureInfo> _cache = new();
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 typesTodo = type.GetCustomAttribute<ser.Ser>(true)?.Types ?? _cfg.TypesDefault;
bool doFields = typesTodo.HasFlag(ser.Types.Fields);
bool doProps = typesTodo.HasFlag(ser.Types.Props);
var typesTodo = type.GetCustomAttribute<ser.Ser>( true )?.Types ?? _cfg.TypesDefault;
bool doFields = typesTodo.HasFlag( ser.Types.Fields );
bool doProps = typesTodo.HasFlag( ser.Types.Props );
// Track processed names to avoid duplicates (e.g., field + prop)
var processedNames = new HashSet<string>();
// 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
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;
if (!processedNames.Contains(nameToTest))
if( !processedNames.Contains( nameToTest ) )
{
if(ProcessMember(fi, false, false, new HashSet<string>(), false, members))
{
processedNames.Add(nameToTest);
}
if( ProcessMember( fi, false, false, new HashSet<string>(), false, members ) )
{
processedNames.Add( nameToTest );
}
}
}
}
@ -103,56 +103,63 @@ public class TypeStructureAnalyzer
type,
members,
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 (mi.GetCustomAttribute<NonSerializedAttribute>(true) != null) return false;
if (mi.Name.Contains("k__BackingField") && !propName.Any()) return false; // Skip if backing but no prop found
if( hasDont )
return false;
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.)
var type = (mi is FieldInfo fi) ? fi.FieldType : ((PropertyInfo)mi).PropertyType;
bool isCollection = typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string);
Type? elementType = isCollection ? GetElementType(type) : null;
bool isPrimitive = Type.GetTypeCode(type) != TypeCode.Object && !isCollection;
var type = ( mi is FieldInfo fi ) ? fi.FieldType : ( (PropertyInfo)mi ).PropertyType;
bool isCollection = typeof( IEnumerable ).IsAssignableFrom( type ) && type != typeof( string );
Type? elementType = isCollection ? GetElementType( type ) : null;
bool isPrimitive = Type.GetTypeCode( type ) != TypeCode.Object && !isCollection;
members.Add(new GenMemberMeta(
members.Add( new GenMemberMeta(
mi, type, name, isPrimitive, isCollection, elementType, hasDo, hasDont
));
) );
return true;
}
private (bool, string) IsBackingField(FieldInfo fi)
private (bool, string) IsBackingField( FieldInfo fi )
{
if (fi.Name.StartsWith("<") && fi.Name.EndsWith("BackingField"))
{
var gtIndex = fi.Name.IndexOf('>');
if (gtIndex > 1) {
return (true, fi.Name.Substring(1, gtIndex - 1));
if( fi.Name.StartsWith( "<" ) && fi.Name.EndsWith( "BackingField" ) )
{
var gtIndex = fi.Name.IndexOf( '>' );
if( 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;
string propName = "";
if (mi is FieldInfo fi && IsBackingField(fi).Item1)
if( mi is FieldInfo fi && IsBackingField( fi ).Item1 )
{
propName = IsBackingField(fi).Item2;
var propInfo = mi.DeclaringType?.GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (propInfo != null) actualMi = propInfo;
} else if (mi is PropertyInfo) {
propName = mi.Name;
propName = IsBackingField( fi ).Item2;
var propInfo = mi.DeclaringType?.GetProperty( propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
if( propInfo != null )
actualMi = propInfo;
}
else if( mi is PropertyInfo )
{
propName = mi.Name;
}
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.IsGenericType) return collectionType.GetGenericArguments().Last(); // Usually last (e.g., List<T>, Dict<K,V>)
return typeof(object); // Fallback
if( collectionType.IsArray )
return collectionType.GetElementType()!;
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

View File

@ -71,4 +71,4 @@ public abstract class CodeGenerator
protected string GetTypeName( Type t ) => t.IsGenericType
? $"{t.Name.Split( '`' )[0]}<{string.Join( ", ", t.GetGenericArguments().Select( GetTypeName ) )}>"
: t.Name; // Basic handling, needs improvement for full names/namespaces
}
}

View File

@ -10,7 +10,7 @@ using System.Runtime.Serialization;
namespace lib
{
/// <summary>
///
///
/// </summary>
public class VersionFormatter: IFormatter
{
@ -32,7 +32,7 @@ namespace lib
public VersionFormatter()
{
//
//
// TODO: Add constructor logic here
//
}
@ -264,27 +264,27 @@ namespace lib
{
writer.Write( val );
}
void writeSingle( BinaryWriter writer, float val )
{
writer.Write( val );
}
void writeDouble( BinaryWriter writer, double val )
{
writer.Write( val );
}
void writeChar( BinaryWriter writer, char val )
{
writer.Write( val );
}
void writeString( BinaryWriter writer, string val )
{
writer.Write( val );
}
void writeBool( BinaryWriter writer, bool val )
{
writer.Write( val );
@ -365,7 +365,7 @@ namespace lib
foreach( Fixup fu in m_fixupList )
{
//Fixup fix = m_fixups[
//Fixup fix = m_fixups[
object obj = m_mapGUIDToObject[ fu.m_guid ];

View File

@ -224,7 +224,7 @@ namespace lib
{
if( nodeList.Count == 0 )
{
// Should be
// Should be
//object obj2 = fi.GetRawConstantValue();
}
@ -431,7 +431,7 @@ namespace lib
/*
/// <summary>
///
///
/// </summary>
public class XmlFormatter : IFormatter
{
@ -453,31 +453,31 @@ public class XmlFormatter : IFormatter
public XmlFormatter()
{
//
//
// TODO: Add constructor logic here
//
}
#region Useless
public ISurrogateSelector SurrogateSelector
public ISurrogateSelector SurrogateSelector
{
get
{
return null;
}
}
set
{
}
}
public SerializationBinder Binder
public SerializationBinder Binder
{
get
{
return null;
}
}
set
{
@ -489,7 +489,7 @@ public class XmlFormatter : IFormatter
get
{
return new StreamingContext();
}
}
set
{
@ -591,31 +591,31 @@ public class XmlFormatter : IFormatter
writer.Write( name.GetHashCode() );
writer.Write( Convert.ToSingle( fi.GetValue( parentObj ) ) );
break;
break;
case "Double":
writer.Write( (char)ETypes.Double );
writer.Write( name.GetHashCode() );
writer.Write( Convert.ToDouble( fi.GetValue( parentObj ) ) );
break;
break;
case "Char":
writer.Write( (char)ETypes.Char );
writer.Write( name.GetHashCode() );
writer.Write( Convert.ToChar( fi.GetValue( parentObj ) ) );
break;
break;
case "String":
writer.Write( (char)ETypes.String );
writer.Write( name.GetHashCode() );
writer.Write( Convert.ToString( fi.GetValue( parentObj ) ) );
break;
break;
case "Boolean":
writer.Write( (char)ETypes.Boolean );
writer.Write( name.GetHashCode() );
writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) );
break;
break;
default:
Console.WriteLine( "VersionFormatter does not understand type " + typeName );
break;
@ -788,7 +788,7 @@ public class XmlFormatter : IFormatter
foreach( Fixup fu in m_fixupList )
{
//Fixup fix = m_fixups[
//Fixup fix = m_fixups[
object obj = m_mapGUIDToObject[ fu.m_guid ];
@ -844,7 +844,7 @@ public class XmlFormatter : IFormatter
int nameHash = reader.ReadInt32();
FieldInfo fi = (FieldInfo)ht[ nameHash ];
FieldInfo fi = (FieldInfo)ht[ nameHash ];
if( fi == null )
{
@ -852,7 +852,7 @@ public class XmlFormatter : IFormatter
}
try
{
{
switch( type )
{
case ETypes.Array:

View File

@ -139,7 +139,7 @@ namespace lib
private string fromStr = "";
void SetFromStr( Stream stream )
void SetFromStr( Stream stream )
{
fromStr = stream.ToString() ?? "{null}";
@ -186,7 +186,8 @@ namespace lib
doc.Load( reader );
if( doc.DocumentElement == null ) return null;
if( doc.DocumentElement == null )
return null;
if( t == null )
return Deserialize( doc.DocumentElement );
@ -256,7 +257,8 @@ namespace lib
{
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 )
{
@ -276,7 +278,8 @@ namespace lib
if( obj is ser.I_Serialize iser )
{
if( _cfg.VerboseLogging ) log.info( $"" );
if( _cfg.VerboseLogging )
log.info( $"" );
obj = iser.OnDeserialize( null );
}
@ -314,7 +317,8 @@ namespace lib
private object DeserializeConcrete( XmlElement elem, MemberInfo mi, string name, Type type )
{
if( _cfg.VerboseLogging ) log.info( $"" );
if( _cfg.VerboseLogging )
log.info( $"" );
string val = "";
@ -398,7 +402,8 @@ namespace lib
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 )
{
@ -488,9 +493,10 @@ namespace lib
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;
@ -536,7 +542,7 @@ namespace lib
name = refl.TypeToIdentifier( name );
// @@@ 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;
var useFieldName = true;
@ -625,7 +631,7 @@ namespace lib
{
object existingObj = childPi.GetValue( obj );
object childObj = DeserializeConcrete( elem, childPi, name, childPi.PropertyType );
object childObj = DeserializeConcrete( elem, childPi, name, childPi.PropertyType );
if( setMethod != null )
{
@ -642,13 +648,13 @@ namespace lib
}
}
if(!isImm)
if( !isImm )
{
return obj;
}
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}" );
return newObj;
}
@ -686,7 +692,8 @@ namespace lib
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 );
@ -695,7 +702,8 @@ namespace lib
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;
@ -731,7 +739,8 @@ namespace lib
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" );
int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1;
@ -776,7 +785,8 @@ namespace lib
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 ) )
{
@ -833,7 +843,8 @@ namespace lib
private object DeserializeArray( XmlElement elem, MemberInfo mi, Type type )
{
if( _cfg.VerboseLogging ) log.info( $"" );
if( _cfg.VerboseLogging )
log.info( $"" );
Type typeElem = type.GetElementType();
@ -883,7 +894,8 @@ namespace lib
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];
}
@ -893,7 +905,8 @@ namespace lib
if( isProxy )
{
if( _cfg.VerboseLogging ) log.info( $"use Proxy" );
if( _cfg.VerboseLogging )
log.info( $"use Proxy" );
object obj = null;
var tryType = type;
@ -937,7 +950,8 @@ namespace lib
if( isSubclass )
{
if( _cfg.VerboseLogging ) log.info( $"Using existing obj {existingObj?.ToString()}" );
if( _cfg.VerboseLogging )
log.info( $"Using existing obj {existingObj?.ToString()}" );
return existingObj;
}
@ -953,12 +967,14 @@ namespace lib
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 );
if( cons != null)
if( cons != null )
{
if( _cfg.VerboseLogging ) log.info( $"Activator.CreateInstance" );
if( _cfg.VerboseLogging )
log.info( $"Activator.CreateInstance" );
obj = Activator.CreateInstance( type );
}
else
@ -967,15 +983,18 @@ namespace lib
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 )
{
try
{
if( _cfg.VerboseLogging ) log.info( $"GetUninitializedObject" );
if( _cfg.VerboseLogging )
log.info( $"GetUninitializedObject" );
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 )
{
@ -1290,7 +1309,7 @@ namespace lib
HashSet<string> whitelistFields, 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 )
{
@ -1323,8 +1342,10 @@ namespace lib
if( isImm )
{
if( name == "MetaStorage" ) continue;
if( name == "Fn" ) continue;
if( name == "MetaStorage" )
continue;
if( name == "Fn" )
continue;
}
if( !doAtt.Any() && FilterField( filterFields, doImpls, whitelistFields, childFi as MemberInfo, name ) )
@ -1365,8 +1386,10 @@ namespace lib
if( isImm )
{
if( name == "MetaStorage" ) continue;
if( name == "Fn" ) continue;
if( name == "MetaStorage" )
continue;
if( name == "Fn" )
continue;
}
if( FilterField( filterProps, doImpls, whitelistProps, childPi as MemberInfo, name ) )
@ -1393,15 +1416,15 @@ namespace lib
var custWLProps = mi?.GetCustomAttribute<ser.ChildPropsAttribute>( true );
filterFields = custWLFields != null;
filterProps = custWLProps != null;
filterProps = custWLProps != null;
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 );
doProps = filterProps || typesTodo.HasFlag( ser.Types.Props );
doProps = filterProps || typesTodo.HasFlag( ser.Types.Props );
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 )
@ -1413,8 +1436,10 @@ namespace lib
Type type = root.GetType();
Type typeOfMember = typeof( object );
if( mi is FieldInfo fi ) typeOfMember = fi.FieldType;
if( mi is PropertyInfo pi ) typeOfMember = pi.PropertyType;
if( mi is FieldInfo fi )
typeOfMember = fi.FieldType;
if( mi is PropertyInfo pi )
typeOfMember = pi.PropertyType;
if( typeOfMember != type )
{
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" )
{
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;
@ -37,14 +37,15 @@ public static class LogGCExt
{
var index = te.PayloadIndex( name );
if( index <= 0 ) return default;
if( index <= 0 )
return default;
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;
}
@ -66,43 +67,43 @@ public class LogGC
"FAKE_TEST",
"GC/BulkMovedObjectRanges",
/*
"GC/BulkSurvivingObjectRanges",
"GC/BulkRootStaticVar",
"GC/BulkNode",
"GC/BulkEdge",
"GC/BulkRootEdge",
"GC/FinalizeObject",
"GC/SetGCHandle",
"GC/DestoryGCHandle",
"GC/MarkWithType",
"GC/SuspendEEStart",
"GC/SuspendEEStop",
/*
"GC/BulkSurvivingObjectRanges",
"GC/BulkRootStaticVar",
"GC/BulkNode",
"GC/BulkEdge",
"GC/BulkRootEdge",
"GC/FinalizeObject",
"GC/SetGCHandle",
"GC/DestoryGCHandle",
"GC/MarkWithType",
"GC/SuspendEEStart",
"GC/SuspendEEStop",
"GC/RestartEEStart",
"GC/RestartEEStop",
"GC/RestartEEStart",
"GC/RestartEEStop",
"GC/FinalizersStart",
// "GC/FinalizersStop", //Keep this one since it has details
"GC/FinalizersStart",
// "GC/FinalizersStop", //Keep this one since it has details
"GC/GenerationRange",
"GC/FitBucketInfo",
"GC/GenerationRange",
"GC/FitBucketInfo",
"TieredCompilation/BackgroundJitStart",
"TieredCompilation/BackgroundJitStart",
"Type/BulkType",
"TypeLoad/Start",
"Type/BulkType",
"TypeLoad/Start",
"Method/R2RGetEntryPointStart",
"Method/MethodDetails",
"Method/MemoryAllocatedForJitCode",
"Method/JittingStarted",
"Method/ILToNativeMap",
"Method/R2RGetEntryPointStart",
"Method/MethodDetails",
"Method/MemoryAllocatedForJitCode",
"Method/JittingStarted",
"Method/ILToNativeMap",
"ThreadPoolWorkerThread/Wait",
"ThreadPoolWorkerThread/Wait",
"ILStub/StubGenerated"
*/
"ILStub/StubGenerated"
*/
"FAKE_END_IS_NOTHING"
);
@ -144,28 +145,33 @@ public class LogGC
{
var cat = catIn;
if( blacklist.Contains( te.EventName )) return;
if( blacklist.Contains( te.EventName ) )
return;
{
var methodBeingCompiledNamespace = te.Get("MethodBeingCompiledNamespace");
if( ( methodBeingCompiledNamespace.StartsWith( "Microsoft" ) || methodBeingCompiledNamespace.StartsWith( "System" ) ) ) return;
var methodBeingCompiledNamespace = te.Get( "MethodBeingCompiledNamespace" );
if( ( methodBeingCompiledNamespace.StartsWith( "Microsoft" ) || methodBeingCompiledNamespace.StartsWith( "System" ) ) )
return;
}
{
var methodNamespace = te.PayloadStringByName("MethodNamespace") ?? "";
if( ( methodNamespace.StartsWith( "Microsoft" ) || methodNamespace.StartsWith( "System" ) ) ) return;
var methodNamespace = te.PayloadStringByName( "MethodNamespace" ) ?? "";
if( ( methodNamespace.StartsWith( "Microsoft" ) || methodNamespace.StartsWith( "System" ) ) )
return;
}
{
var ns = te.PayloadStringByName("TypeName") ?? "";
if( ( ns.StartsWith( "Microsoft" ) || ns.StartsWith( "System" ) ) ) return;
var ns = te.PayloadStringByName( "TypeName" ) ?? "";
if( ( ns.StartsWith( "Microsoft" ) || ns.StartsWith( "System" ) ) )
return;
}
{
var ns = te.PayloadStringByName("TypeLoad/Stop") ?? "";
if( ns.StartsWith( "Godot" ) ) return;
var ns = te.PayloadStringByName( "TypeLoad/Stop" ) ?? "";
if( ns.StartsWith( "Godot" ) )
return;
}
{
@ -174,16 +180,17 @@ public class LogGC
if( payloadIndex > 0 )
{
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/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/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/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 = "";
// Custom event displays
@ -192,8 +199,10 @@ public class LogGC
var optTier = te.Get( "OptimizationTier" );
var methodNamespace = te.Get( "MethodNamespace" );
if( optTier == "MinOptJitted" ) return;
if( methodNamespace.StartsWith( "FastSerialization" )) return;
if( optTier == "MinOptJitted" )
return;
if( methodNamespace.StartsWith( "FastSerialization" ) )
return;
log.info( $"{optTier} {LogGCExt.MethodInfo( te )}", cat: te.EventName );
@ -204,7 +213,8 @@ public class LogGC
{
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 );
@ -218,7 +228,7 @@ public class LogGC
XmlDocument doc = new();
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
var writer = new StreamWriter( stream );
writer.Write( val );
writer.Flush();
stream.Position = 0;
@ -265,7 +275,7 @@ public class LogGC
var lockId = te.Get<UInt64>( "LockID" );
var objId = te.Get<UInt64>( "AssociatedObjectID" );
var testObj = Marshal.GetIUnknownForObject(objId);
var testObj = Marshal.GetIUnknownForObject( objId );
var intPtrStr = te.PayloadStringByName( "AssociatedObjectID" ).Substring( 2 );
@ -281,7 +291,7 @@ public class LogGC
var allocated = gch.IsAllocated;
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 )
@ -303,7 +313,7 @@ public class LogGC
var objId = te.Get<UInt64>( "AssociatedObjectID" );
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: " );
}
@ -319,44 +329,44 @@ public class LogGC
}
else if( te.EventName.StartsWith( "AssemblyLoader/" ) || te.EventName.StartsWith( "Loader/" ) )
{
//AssemblyLoader/Start AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly
//AssemblyLoader/Stop AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly Success ResultAssemblyName ResultAssemblyPath Cached
//Loader/AssemblyLoad AssemblyID AppDomainID AssemblyFlags FullyQualifiedAssemblyName BindingID
//AssemblyLoader/ResolutionAttempted
// AssemblyName AssemblyLoadContext Result ResultAssemblyName ResultAssemblyPath Stage ErrorMessage
//AssemblyLoader/Start AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly
//AssemblyLoader/Stop AssemblyName AssemblyLoadContext RequestingAssemblyLoadContext AssemblyPath RequestingAssembly Success ResultAssemblyName ResultAssemblyPath Cached
//Loader/AssemblyLoad AssemblyID AppDomainID AssemblyFlags FullyQualifiedAssemblyName BindingID
//AssemblyLoader/ResolutionAttempted
// AssemblyName AssemblyLoadContext Result ResultAssemblyName ResultAssemblyPath Stage ErrorMessage
//Loader/ModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath ManagedPdbSignature ManagedPdbAge ManagedPdbBuildPath
//Loader/DomainModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath AppDomainID
//Loader/ModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath ManagedPdbSignature ManagedPdbAge ManagedPdbBuildPath
//Loader/DomainModuleLoad ModuleID AssemblyID ModuleFlags ModuleILPath ModuleNativePath AppDomainID
//AssemblyLoader/KnownPathProbed FilePath Source Result
//AssemblyLoader/KnownPathProbed FilePath Source Result
var appDomainId = te.Get( "AppDomainID" );
var asId = te.Get( "AssemblyID" );
var asName = te.Get( "AssemblyName" );
var asPath = te.Get( "AssemblyPath" );
var asLC = te.Get( "AssemblyLoadContext" );
var asId = te.Get( "AssemblyID" );
var asName = te.Get( "AssemblyName" );
var asPath = te.Get( "AssemblyPath" );
var asLC = te.Get( "AssemblyLoadContext" );
var reqAs = te.Get( "RequestingAssembly" );
var reqAsLC = te.Get( "RequestingAssemblyLoadContext" );
var reqAs = te.Get( "RequestingAssembly" );
var reqAsLC = te.Get( "RequestingAssemblyLoadContext" );
var reqAsName = te.Get( "ResultAssemblyName" );
var reqAsPath = te.Get( "ResultAssemblyPath" );
var reqAsName = te.Get( "ResultAssemblyName" );
var reqAsPath = te.Get( "ResultAssemblyPath" );
var success = te.Get( "Success" );
var cached = te.Get( "Cached" );
var errMsg = te.Get( "ErrorMessage" );
var stage = te.Get( "Stage" );
var result = te.Get( "Result" );
var source = te.Get( "Source" );
var success = te.Get( "Success" );
var cached = te.Get( "Cached" );
var errMsg = te.Get( "ErrorMessage" );
var stage = te.Get( "Stage" );
var result = te.Get( "Result" );
var source = te.Get( "Source" );
var modId = te.Get( "ModuleID" );
var modFlags = te.Get( "ModuleFlags" );
var modILPath = te.Get( "ModuleILPath" );
var modNativePath= te.Get( "ModuleNativePath" );
var modId = te.Get( "ModuleID" );
var modFlags = te.Get( "ModuleFlags" );
var modILPath = te.Get( "ModuleILPath" );
var modNativePath = te.Get( "ModuleNativePath" );
var manBuildPath= te.Get( "ManagedPdbBuildPath" );
var fqaName = te.Get( "FullyQualifiedAssemblyName" );
var bindingId = te.Get( "BindingID" );
var manBuildPath = te.Get( "ManagedPdbBuildPath" );
var fqaName = te.Get( "FullyQualifiedAssemblyName" );
var bindingId = te.Get( "BindingID" );
}
@ -397,7 +407,7 @@ public class LogGC
//var eventDataStr = eventData.ToString();
Encoding enc = new UnicodeEncoding(false, false, true);
Encoding enc = new UnicodeEncoding( false, false, true );
var eventDataUtf16 = enc.GetString( eventData );
//var safeEventData = eventDataUtf16.Replace( (char)0, '\n' );

View File

@ -18,10 +18,10 @@ using System.Text;
/*
T O D O :
x) Hook the C# prints from glue.
x) Fix
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
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:
@ -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 static T Default = default!;
@ -190,7 +247,7 @@ static public class log
All = File | Console,
}
#region LogEvent
public struct LogEvent
{
public DateTime Time;
@ -254,6 +311,7 @@ static public class log
return logEvent;
}
#endregion // LogEvent
public delegate void Log_delegate( LogEvent evt );
@ -307,7 +365,7 @@ static public class log
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; } );
@ -404,32 +462,32 @@ static public class log
}
[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 = "" )
{
logBase( msg, LogType.Info, dbgPath, dbgLine, dbgMethod, cat, dbgExp, loc );
}
[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 );
}
[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 );
}
[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 );
}
[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 );
}
@ -464,12 +522,12 @@ static public class log
[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 );
}
//new LogEvent( LogType.Raw, $"", "", 0, "", "lib.time", "", null )
//new LogEvent( LogType.Raw, $"", "", 0, "", "lib.time", "", null )
#endregion
@ -531,7 +589,7 @@ static public class log
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 );
return evt;
}
[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 );

View File

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

View File

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

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -37,13 +37,13 @@ namespace math
/// Represents an axis-aligned bounding box in three dimensional space.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingBox : IEquatable<BoundingBox>, IFormattable
{
/// <summary>
/// A <see cref="BoundingBox"/> which represents an empty space.
/// </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>
/// The minimum point of the box.
@ -60,7 +60,7 @@ namespace math
/// </summary>
/// <param name="minimum">The minimum 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.Maximum = maximum;
@ -71,7 +71,7 @@ namespace math
/// </summary>
public Vec3 Center
{
get { return (Minimum + Maximum) / 2; }
get { return ( Minimum + Maximum ) / 2; }
}
/// <summary>
@ -79,7 +79,7 @@ namespace math
/// </summary>
public Vec3 Extent
{
get { return (Maximum - Minimum) / 2; }
get { return ( Maximum - Minimum ) / 2; }
}
/// <summary>
@ -89,14 +89,14 @@ namespace math
public Vec3[] GetCorners()
{
Vec3[] results = new Vec3[8];
results[0] = new Vec3(Minimum.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[3] = new Vec3(Minimum.X, Minimum.Y, Maximum.Z);
results[4] = new Vec3(Minimum.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[7] = new Vec3(Minimum.X, Minimum.Y, Minimum.Z);
results[0] = new Vec3( Minimum.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[3] = new Vec3( Minimum.X, Minimum.Y, Maximum.Z );
results[4] = new Vec3( Minimum.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[7] = new Vec3( Minimum.X, Minimum.Y, Minimum.Z );
return results;
}
@ -105,10 +105,10 @@ namespace math
/// </summary>
/// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray)
public bool Intersects( ref Ray ray )
{
float distance;
return CollisionHelper.RayIntersectsBox(ref ray, ref this, out distance);
return CollisionHelper.RayIntersectsBox( ref ray, ref this, out distance );
}
/// <summary>
@ -118,9 +118,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -130,9 +130,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -140,9 +140,9 @@ namespace math
/// </summary>
/// <param name="plane">The plane to test.</param>
/// <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
@ -164,9 +164,9 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <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>
@ -174,9 +174,9 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <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>
@ -184,9 +184,9 @@ namespace math
/// </summary>
/// <param name="point">The point to test.</param>
/// <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
@ -208,9 +208,9 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <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>
@ -218,9 +218,9 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <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>
@ -229,21 +229,21 @@ namespace math
/// <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>
/// <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)
throw new ArgumentNullException("points");
if( points == null )
throw new ArgumentNullException( "points" );
Vec3 min = new Vec3(float.MaxValue);
Vec3 max = new Vec3(float.MinValue);
Vec3 min = new Vec3( float.MaxValue );
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.Max(ref max, ref points[i], out max);
Vec3.Min( ref min, ref points[i], out min );
Vec3.Max( ref max, ref points[i], out max );
}
result = new BoundingBox(min, max);
result = new BoundingBox( min, max );
}
/// <summary>
@ -252,21 +252,21 @@ namespace math
/// <param name="points">The points that will be contained by the box.</param>
/// <returns>The newly constructed bounding box.</returns>
/// <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)
throw new ArgumentNullException("points");
if( points == null )
throw new ArgumentNullException( "points" );
Vec3 min = new Vec3(float.MaxValue);
Vec3 max = new Vec3(float.MinValue);
Vec3 min = new Vec3( float.MaxValue );
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.Max(ref max, ref points[i], out max);
Vec3.Min( ref min, ref points[i], out min );
Vec3.Max( ref max, ref points[i], out max );
}
return new BoundingBox(min, max);
return new BoundingBox( min, max );
}
/// <summary>
@ -274,10 +274,10 @@ namespace math
/// </summary>
/// <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>
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.Maximum = 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 );
}
/// <summary>
@ -285,11 +285,11 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere that will designate the extents of the box.</param>
/// <returns>The newly constructed bounding box.</returns>
public static BoundingBox FromSphere(BoundingSphere sphere)
public static BoundingBox FromSphere( BoundingSphere sphere )
{
BoundingBox box;
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.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 );
return box;
}
@ -299,10 +299,10 @@ namespace math
/// <param name="value">The original bounding box.</param>
/// <param name="transform">The transform to apply to the 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);
boundingBox.Transform(transform);
var boundingBox = new BoundingBoxExt( value );
boundingBox.Transform( transform );
result = (BoundingBox)boundingBox;
}
@ -312,22 +312,22 @@ namespace math
/// <param name="value1">The box 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>
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.Max(ref value1.Maximum, ref value2, out result.Maximum);
Vec3.Min( ref value1.Minimum, ref value2, out result.Minimum );
Vec3.Max( ref value1.Maximum, ref value2, out result.Maximum );
}
/// <summary>
/// Constructs a <see cref="math.BoundingBox"/> that is as large as the total combined area of the two specified boxes.
/// </summary>
/// <param name="value1">The first 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>
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.Max(ref value1.Maximum, ref value2.Maximum, out result.Maximum);
Vec3.Min( ref value1.Minimum, ref value2.Minimum, out result.Minimum );
Vec3.Max( ref value1.Maximum, ref value2.Maximum, out result.Maximum );
}
/// <summary>
@ -336,11 +336,11 @@ namespace math
/// <param name="value1">The first box to merge.</param>
/// <param name="value2">The second box to merge.</param>
/// <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;
Vec3.Min(ref value1.Minimum, ref value2.Minimum, out box.Minimum);
Vec3.Max(ref value1.Maximum, ref value2.Maximum, out box.Maximum);
Vec3.Min( ref value1.Minimum, ref value2.Minimum, out box.Minimum );
Vec3.Max( ref value1.Maximum, ref value2.Maximum, out box.Maximum );
return box;
}
@ -350,9 +350,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -361,9 +361,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -374,7 +374,7 @@ namespace math
/// </returns>
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>
@ -384,13 +384,13 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
return ToString();
return string.Format(CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(format, CultureInfo.CurrentCulture),
Maximum.ToString(format, CultureInfo.CurrentCulture));
return string.Format( CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString( format, CultureInfo.CurrentCulture ),
Maximum.ToString( format, CultureInfo.CurrentCulture ) );
}
/// <summary>
@ -400,9 +400,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -413,20 +413,20 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
return ToString( formatProvider );
return string.Format(formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString(format, formatProvider),
Maximum.ToString(format, formatProvider));
return string.Format( formatProvider, "Minimum:{0} Maximum:{1}", Minimum.ToString( format, formatProvider ),
Maximum.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -440,7 +440,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(BoundingBox value)
public bool Equals( BoundingBox value )
{
return Minimum == value.Minimum && Maximum == value.Maximum;
}
@ -452,15 +452,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
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.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingBoxExt : IEquatable<BoundingBoxExt>
{
/// <summary>
/// A <see cref="BoundingBoxExt"/> which represents an empty space.
/// </summary>
public static readonly BoundingBoxExt Empty = new BoundingBoxExt(BoundingBox.Empty);
public static readonly BoundingBoxExt Empty = new BoundingBoxExt( BoundingBox.Empty );
/// <summary>
/// The center of this bounding box.
@ -33,7 +33,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.BoundingBoxExt" /> struct.
/// </summary>
/// <param name="box">The box.</param>
public BoundingBoxExt(BoundingBox box)
public BoundingBoxExt( BoundingBox box )
{
this.Center = box.Center;
this.Extent = box.Extent;
@ -44,10 +44,10 @@ namespace math
/// </summary>
/// <param name="minimum">The minimum 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.Extent = (maximum - minimum) / 2;
this.Center = ( minimum + maximum ) / 2;
this.Extent = ( maximum - minimum ) / 2;
}
/// <summary>
@ -78,29 +78,29 @@ namespace math
/// Transform this Bounding box
/// </summary>
/// <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/
// Compute transformed AABB (by world)
var center = Center;
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
unsafe
{
// Perform an abs on the matrix
var matrixData = (float*)&world;
for (int j = 0; j < 16; ++j)
for( int j = 0; j < 16; ++j )
{
//*matrixData &= 0x7FFFFFFF;
*matrixData = Math.Abs(*matrixData);
*matrixData = Math.Abs( *matrixData );
++matrixData;
}
}
Vec3.TransformNormal(ref extent, ref world, out Extent);
Vec3.TransformNormal( ref extent, ref world, out Extent );
}
/// <summary>
@ -109,27 +109,28 @@ namespace math
/// <param name="value1">The first 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>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Merge(ref BoundingBoxExt value1, ref BoundingBoxExt value2, out BoundingBoxExt result)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void Merge( ref BoundingBoxExt value1, ref BoundingBoxExt value2, out BoundingBoxExt result )
{
var maximum = Vec3.Max(value1.Maximum, value2.Maximum);
var minimum = Vec3.Min(value1.Minimum, value2.Minimum);
var maximum = Vec3.Max( value1.Maximum, value2.Maximum );
var minimum = Vec3.Min( value1.Minimum, value2.Minimum );
result.Center = (minimum + maximum) / 2;
result.Extent = (maximum - minimum) / 2;
result.Center = ( minimum + maximum ) / 2;
result.Extent = ( maximum - minimum ) / 2;
}
/// <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/>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
return obj is BoundingBoxExt && Equals((BoundingBoxExt)obj);
if( ReferenceEquals( null, obj ) )
return false;
return obj is BoundingBoxExt && Equals( (BoundingBoxExt)obj );
}
/// <inheritdoc/>
@ -137,7 +138,7 @@ namespace math
{
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="right">The right.</param>
/// <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>
@ -158,9 +159,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -168,9 +169,9 @@ namespace math
/// </summary>
/// <param name="bbExt">The bb ext.</param>
/// <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>
@ -178,9 +179,9 @@ namespace math
/// </summary>
/// <param name="boundingBox">The bounding box.</param>
/// <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.
/// </summary>
/// <param name="matrix">The matrix view projection.</param>
public BoundingFrustum(ref Matrix matrix)
public BoundingFrustum( ref Matrix matrix )
{
// Left
LeftPlane = Plane.Normalize(new Plane(
LeftPlane = Plane.Normalize( new Plane(
matrix.M14 + matrix.M11,
matrix.M24 + matrix.M21,
matrix.M34 + matrix.M31,
matrix.M44 + matrix.M41));
matrix.M44 + matrix.M41 ) );
// Right
RightPlane = Plane.Normalize(new Plane(
RightPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M11,
matrix.M24 - matrix.M21,
matrix.M34 - matrix.M31,
matrix.M44 - matrix.M41));
matrix.M44 - matrix.M41 ) );
// Top
TopPlane = Plane.Normalize(new Plane(
TopPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M12,
matrix.M24 - matrix.M22,
matrix.M34 - matrix.M32,
matrix.M44 - matrix.M42));
matrix.M44 - matrix.M42 ) );
// Bottom
BottomPlane = Plane.Normalize(new Plane(
BottomPlane = Plane.Normalize( new Plane(
matrix.M14 + matrix.M12,
matrix.M24 + matrix.M22,
matrix.M34 + matrix.M32,
matrix.M44 + matrix.M42));
matrix.M44 + matrix.M42 ) );
// Near
NearPlane = Plane.Normalize(new Plane(
NearPlane = Plane.Normalize( new Plane(
matrix.M13,
matrix.M23,
matrix.M33,
matrix.M43));
matrix.M43 ) );
// Far
FarPlane = Plane.Normalize(new Plane(
FarPlane = Plane.Normalize( new Plane(
matrix.M14 - matrix.M13,
matrix.M24 - matrix.M23,
matrix.M34 - matrix.M33,
matrix.M44 - matrix.M43));
matrix.M44 - matrix.M43 ) );
}
/// <summary>
@ -94,10 +94,10 @@ namespace math
/// </summary>
/// <param name="boundingBoxExt">The bounding box.</param>
/// <returns><c>true</c> if this frustum contains the specified bounding box.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Contains(ref BoundingBoxExt boundingBoxExt)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool Contains( ref BoundingBoxExt boundingBoxExt )
{
return CollisionHelper.FrustumContainsBox(ref this, ref boundingBoxExt);
return CollisionHelper.FrustumContainsBox( ref this, ref boundingBoxExt );
}
}
}

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -37,7 +37,7 @@ namespace math
/// Represents a bounding sphere in three dimensional space.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct BoundingSphere : IEquatable<BoundingSphere>, IFormattable
{
/// <summary>
@ -60,7 +60,7 @@ namespace math
/// </summary>
/// <param name="center">The center of the sphere in three dimensional space.</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.Radius = radius;
@ -71,10 +71,10 @@ namespace math
/// </summary>
/// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray)
public bool Intersects( ref Ray ray )
{
float distance;
return CollisionHelper.RayIntersectsSphere(ref ray, ref this, out distance);
return CollisionHelper.RayIntersectsSphere( ref ray, ref this, out distance );
}
/// <summary>
@ -84,9 +84,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -96,9 +96,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -106,9 +106,9 @@ namespace math
/// </summary>
/// <param name="plane">The plane to test.</param>
/// <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>
@ -118,9 +118,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <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>
@ -128,9 +128,9 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <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>
@ -138,9 +138,9 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <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>
@ -148,9 +148,9 @@ namespace math
/// </summary>
/// <param name="point">The point to test.</param>
/// <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>
@ -160,9 +160,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle 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>
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>
@ -170,9 +170,9 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <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>
@ -180,9 +180,9 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <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>
@ -190,12 +190,13 @@ namespace math
/// </summary>
/// <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>
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");
fixed (void* pointsPtr = points)
if( points == null )
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="vertexStride">The vertex stride (size of vertex).</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;
@ -219,9 +220,9 @@ namespace math
//Find the center of all points.
Vec3 center = Vec3.Zero;
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;
}
@ -231,20 +232,20 @@ namespace math
//Find the radius of the sphere
float radius = 0f;
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
//from the center of our sphere.
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;
nextPoint += vertexStride;
}
//Find the real distance from the DistanceSquared.
radius = (float)Math.Sqrt(radius);
radius = (float)Math.Sqrt( radius );
//Construct the sphere.
result.Center = center;
@ -256,10 +257,10 @@ namespace math
/// </summary>
/// <param name="points">The points that will be contained by the sphere.</param>
/// <returns>The newly constructed bounding sphere.</returns>
public static BoundingSphere FromPoints(Vec3[] points)
public static BoundingSphere FromPoints( Vec3[] points )
{
BoundingSphere result;
FromPoints(points, out result);
FromPoints( points, out result );
return result;
}
@ -268,15 +269,15 @@ namespace math
/// </summary>
/// <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>
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 y = box.Minimum.Y - box.Maximum.Y;
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;
}
@ -285,10 +286,10 @@ namespace math
/// </summary>
/// <param name="box">The box that will designate the extents of the sphere.</param>
/// <returns>The newly constructed bounding sphere.</returns>
public static BoundingSphere FromBox(BoundingBox box)
public static BoundingSphere FromBox( BoundingBox box )
{
BoundingSphere result;
FromBox(ref box, out result);
FromBox( ref box, out result );
return result;
}
@ -298,16 +299,16 @@ namespace math
/// <param name="value">The original bounding sphere.</param>
/// <param name="transform">The transform to apply to the 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(
(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.M31 * transform.M31) + (transform.M32 * transform.M32) + (transform.M33 * transform.M33)));
( 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.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>
@ -316,16 +317,16 @@ namespace math
/// <param name="value1">The first 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>
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
if (value1 == Empty)
if( value1 == Empty )
{
result = value2;
return;
}
if (value2 == Empty)
}
if( value2 == Empty )
{
result = value1;
return;
@ -337,26 +338,26 @@ namespace math
float radius = value1.Radius;
float radius2 = value2.Radius;
if (radius + radius2 >= length)
if( radius + radius2 >= length )
{
if (radius - radius2 >= length)
if( radius - radius2 >= length )
{
result = value1;
return;
}
if (radius2 - radius >= length)
if( radius2 - radius >= length )
{
result = value2;
return;
}
}
Vec3 vector = difference * (1.0f / length);
float min = Math.Min(-radius, length - radius2);
float max = (Math.Max(radius, length + radius2) - min) * 0.5f;
Vec3 vector = difference * ( 1.0f / length );
float min = Math.Min( -radius, length - radius2 );
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;
}
@ -366,10 +367,10 @@ namespace math
/// <param name="value1">The first sphere to merge.</param>
/// <param name="value2">The second sphere to merge.</param>
/// <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;
Merge(ref value1, ref value2, out result);
Merge( ref value1, ref value2, out result );
return result;
}
@ -379,9 +380,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -390,9 +391,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -403,7 +404,7 @@ namespace math
/// </returns>
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>
@ -413,13 +414,13 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
return ToString();
return string.Format(CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString(format, CultureInfo.CurrentCulture),
Radius.ToString(format, CultureInfo.CurrentCulture));
return string.Format( CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString( format, CultureInfo.CurrentCulture ),
Radius.ToString( format, CultureInfo.CurrentCulture ) );
}
/// <summary>
@ -429,9 +430,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -442,20 +443,20 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
return ToString( formatProvider );
return string.Format(formatProvider, "Center:{0} Radius:{1}", Center.ToString(format, formatProvider),
Radius.ToString(format, formatProvider));
return string.Format( formatProvider, "Center:{0} Radius:{1}", Center.ToString( format, formatProvider ),
Radius.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -469,7 +470,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(BoundingSphere value)
public bool Equals( BoundingSphere value )
{
return Center == value.Center && Radius == value.Radius;
}
@ -481,15 +482,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((BoundingSphere)value);
return Equals( (BoundingSphere)value );
}
#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.
/// Implements INumber<Cm> for full generic math support.
/// </summary>
sealed public record Cm(int value) : INumber<Cm>
sealed public record Cm( int value ) : INumber<Cm>
{
// --- Constants and Identities ---
@ -31,88 +31,88 @@ sealed public record Cm(int value) : INumber<Cm>
/// Represents the multiplicative identity (1.0).
/// The underlying value is 100 because 1.0 meter = 100 centimeters.
/// </summary>
public static Cm One => new Cm(100);
public static Cm Zero => new Cm(0);
public static Cm One => new Cm( 100 );
public static Cm Zero => new Cm( 0 );
public static int Radix => 10;
public static Cm AdditiveIdentity => Zero;
public static Cm MultiplicativeIdentity => One;
public float Float => ((float)value) * 0.01f;
public double Double => ((double)value) * 0.01;
public float Float => ( (float)value ) * 0.01f;
public double Double => ( (double)value ) * 0.01;
// --- Static Conversion Methods ---
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( float v ) => new Cm( (int)( v * 100.0f + 0.5f ) );
public static Cm From( double v ) => new Cm( (int)( v * 100.0 + 0.5 ) );
// --- Standard Functions ---
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 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 MinMagnitudeNumber(Cm x, Cm y) => MinMagnitude(x, y); // Same for this type
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 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 MinMagnitudeNumber( Cm x, Cm y ) => MinMagnitude( x, y ); // Same for this type
// --- Type Property Checks ---
public static bool IsCanonical(Cm c) => true;
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 IsFinite(Cm c) => true;
public static bool IsImaginaryNumber(Cm c) => false;
public static bool IsInfinity(Cm c) => false;
public static bool IsInteger(Cm c) => c.value % 100 == 0;
public static bool IsNaN(Cm c) => false;
public static bool IsNegative(Cm c) => c.value < 0;
public static bool IsNegativeInfinity(Cm c) => false;
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 IsPositive(Cm c) => c.value > 0;
public static bool IsPositiveInfinity(Cm c) => false;
public static bool IsRealNumber(Cm c) => true; // It is a real number
public static bool IsSubnormal(Cm c) => false;
public static bool IsZero(Cm c) => c.value == 0;
public static bool IsCanonical( Cm c ) => true;
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 IsFinite( Cm c ) => true;
public static bool IsImaginaryNumber( Cm c ) => false;
public static bool IsInfinity( Cm c ) => false;
public static bool IsInteger( Cm c ) => c.value % 100 == 0;
public static bool IsNaN( Cm c ) => false;
public static bool IsNegative( Cm c ) => c.value < 0;
public static bool IsNegativeInfinity( Cm c ) => false;
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 IsPositive( Cm c ) => c.value > 0;
public static bool IsPositiveInfinity( Cm c ) => false;
public static bool IsRealNumber( Cm c ) => true; // It is a real number
public static bool IsSubnormal( Cm c ) => false;
public static bool IsZero( Cm c ) => c.value == 0;
// --- Parsing ---
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(string s, NumberStyles style, IFormatProvider? 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( string s, NumberStyles style, IFormatProvider? provider )
{
if (TryParse(s, style, provider, out var result))
if( TryParse( s, style, provider, out var 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;
}
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(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, 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 )
{
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;
}
result = Cm.Zero;
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;
}
result = Cm.Zero;
@ -121,20 +121,20 @@ sealed public record Cm(int value) : INumber<Cm>
// --- 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.
if (TOther.IsInteger(value))
if( TOther.IsInteger( value ) )
{
try
{
checked
{
result = new Cm(int.CreateChecked(value) * 100);
result = new Cm( int.CreateChecked( value ) * 100 );
return true;
}
}
catch (OverflowException)
catch( OverflowException )
{
result = Cm.Zero;
return false;
@ -142,22 +142,22 @@ sealed public record Cm(int value) : INumber<Cm>
}
// Convert floating point types
if (typeof(TOther) == typeof(double))
if( typeof( TOther ) == typeof( double ) )
{
double d = double.CreateChecked(value);
result = From(d);
double d = double.CreateChecked( value );
result = From( d );
return true;
}
if (typeof(TOther) == typeof(float))
if( typeof( TOther ) == typeof( float ) )
{
float f = float.CreateChecked(value);
result = From(f);
float f = float.CreateChecked( value );
result = From( f );
return true;
}
if (typeof(TOther) == typeof(decimal))
if( typeof( TOther ) == typeof( decimal ) )
{
decimal m = decimal.CreateChecked(value);
result = new Cm((int)(m * 100m));
decimal m = decimal.CreateChecked( value );
result = new Cm( (int)( m * 100m ) );
return true;
}
@ -165,65 +165,65 @@ sealed public record Cm(int value) : INumber<Cm>
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;
}
if (typeof(TOther) == typeof(double))
if( typeof( TOther ) == typeof( double ) )
{
double d = double.CreateSaturating(value);
result = From(d);
double d = double.CreateSaturating( value );
result = From( d );
return true;
}
if (typeof(TOther) == typeof(float))
if( typeof( TOther ) == typeof( float ) )
{
float f = float.CreateSaturating(value);
result = From(f);
float f = float.CreateSaturating( value );
result = From( f );
return true;
}
if (typeof(TOther) == typeof(decimal))
if( typeof( TOther ) == typeof( decimal ) )
{
decimal m = decimal.CreateSaturating(value);
result = new Cm((int)(m * 100m));
decimal m = decimal.CreateSaturating( value );
result = new Cm( (int)( m * 100m ) );
return true;
}
result = Cm.Zero;
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;
}
if (typeof(TOther) == typeof(double))
if( typeof( TOther ) == typeof( double ) )
{
double d = double.CreateTruncating(value);
result = From(d);
double d = double.CreateTruncating( value );
result = From( d );
return true;
}
if (typeof(TOther) == typeof(float))
if( typeof( TOther ) == typeof( float ) )
{
float f = float.CreateTruncating(value);
result = From(f);
float f = float.CreateTruncating( value );
result = From( f );
return true;
}
if (typeof(TOther) == typeof(decimal))
if( typeof( TOther ) == typeof( decimal ) )
{
decimal m = decimal.CreateTruncating(value);
result = new Cm((int)(m * 100m));
decimal m = decimal.CreateTruncating( value );
result = new Cm( (int)( m * 100m ) );
return true;
}
result = Cm.Zero;
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.
// This typically involves scaling down by 100.
@ -231,109 +231,109 @@ sealed public record Cm(int value) : INumber<Cm>
{
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;
}
// 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;
}
}
catch (OverflowException)
catch( OverflowException )
{
result = default!;
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;
}
result = TOther.CreateSaturating(value.value) / TOther.CreateSaturating(100);
result = TOther.CreateSaturating( value.value ) / TOther.CreateSaturating( 100 );
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;
}
result = TOther.CreateTruncating(value.value) / TOther.CreateTruncating(100);
result = TOther.CreateTruncating( value.value ) / TOther.CreateTruncating( 100 );
return true;
}
// --- 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();
// --- 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
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 ---
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 c) => new Cm(-c.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 ) => c;
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 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 );
// 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.
// 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.
// 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 ---
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>
@ -344,22 +344,22 @@ public static class CentEx
// --- Static Conversion Methods ---
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( 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 Cm(this float 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 );
}
extension(double r)
extension( double 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>
/// Zero color.
/// </summary>
public static readonly Color Zero = Color.FromBgra(0x00000000);
public static readonly Color Zero = Color.FromBgra( 0x00000000 );
/// <summary>
/// Transparent color.
/// </summary>
public static readonly Color Transparent = Color.FromBgra(0x00000000);
public static readonly Color Transparent = Color.FromBgra( 0x00000000 );
/// <summary>
/// AliceBlue color.
/// </summary>
public static readonly Color AliceBlue = Color.FromBgra(0xFFF0F8FF);
public static readonly Color AliceBlue = Color.FromBgra( 0xFFF0F8FF );
/// <summary>
/// AntiqueWhite color.
/// </summary>
public static readonly Color AntiqueWhite = Color.FromBgra(0xFFFAEBD7);
public static readonly Color AntiqueWhite = Color.FromBgra( 0xFFFAEBD7 );
/// <summary>
/// Aqua color.
/// </summary>
public static readonly Color Aqua = Color.FromBgra(0xFF00FFFF);
public static readonly Color Aqua = Color.FromBgra( 0xFF00FFFF );
/// <summary>
/// Aquamarine color.
/// </summary>
public static readonly Color Aquamarine = Color.FromBgra(0xFF7FFFD4);
public static readonly Color Aquamarine = Color.FromBgra( 0xFF7FFFD4 );
/// <summary>
/// Azure color.
/// </summary>
public static readonly Color Azure = Color.FromBgra(0xFFF0FFFF);
public static readonly Color Azure = Color.FromBgra( 0xFFF0FFFF );
/// <summary>
/// Beige color.
/// </summary>
public static readonly Color Beige = Color.FromBgra(0xFFF5F5DC);
public static readonly Color Beige = Color.FromBgra( 0xFFF5F5DC );
/// <summary>
/// Bisque color.
/// </summary>
public static readonly Color Bisque = Color.FromBgra(0xFFFFE4C4);
public static readonly Color Bisque = Color.FromBgra( 0xFFFFE4C4 );
/// <summary>
/// Black color.
/// </summary>
public static readonly Color Black = Color.FromBgra(0xFF000000);
public static readonly Color Black = Color.FromBgra( 0xFF000000 );
/// <summary>
/// BlanchedAlmond color.
/// </summary>
public static readonly Color BlanchedAlmond = Color.FromBgra(0xFFFFEBCD);
public static readonly Color BlanchedAlmond = Color.FromBgra( 0xFFFFEBCD );
/// <summary>
/// Blue color.
/// </summary>
public static readonly Color Blue = Color.FromBgra(0xFF0000FF);
public static readonly Color Blue = Color.FromBgra( 0xFF0000FF );
/// <summary>
/// BlueViolet color.
/// </summary>
public static readonly Color BlueViolet = Color.FromBgra(0xFF8A2BE2);
public static readonly Color BlueViolet = Color.FromBgra( 0xFF8A2BE2 );
/// <summary>
/// Brown color.
/// </summary>
public static readonly Color Brown = Color.FromBgra(0xFFA52A2A);
public static readonly Color Brown = Color.FromBgra( 0xFFA52A2A );
/// <summary>
/// BurlyWood color.
/// </summary>
public static readonly Color BurlyWood = Color.FromBgra(0xFFDEB887);
public static readonly Color BurlyWood = Color.FromBgra( 0xFFDEB887 );
/// <summary>
/// CadetBlue color.
/// </summary>
public static readonly Color CadetBlue = Color.FromBgra(0xFF5F9EA0);
public static readonly Color CadetBlue = Color.FromBgra( 0xFF5F9EA0 );
/// <summary>
/// Chartreuse color.
/// </summary>
public static readonly Color Chartreuse = Color.FromBgra(0xFF7FFF00);
public static readonly Color Chartreuse = Color.FromBgra( 0xFF7FFF00 );
/// <summary>
/// Chocolate color.
/// </summary>
public static readonly Color Chocolate = Color.FromBgra(0xFFD2691E);
public static readonly Color Chocolate = Color.FromBgra( 0xFFD2691E );
/// <summary>
/// Coral color.
/// </summary>
public static readonly Color Coral = Color.FromBgra(0xFFFF7F50);
public static readonly Color Coral = Color.FromBgra( 0xFFFF7F50 );
/// <summary>
/// CornflowerBlue color.
/// </summary>
public static readonly Color CornflowerBlue = Color.FromBgra(0xFF6495ED);
public static readonly Color CornflowerBlue = Color.FromBgra( 0xFF6495ED );
/// <summary>
/// Cornsilk color.
/// </summary>
public static readonly Color Cornsilk = Color.FromBgra(0xFFFFF8DC);
public static readonly Color Cornsilk = Color.FromBgra( 0xFFFFF8DC );
/// <summary>
/// Crimson color.
/// </summary>
public static readonly Color Crimson = Color.FromBgra(0xFFDC143C);
public static readonly Color Crimson = Color.FromBgra( 0xFFDC143C );
/// <summary>
/// Cyan color.
/// </summary>
public static readonly Color Cyan = Color.FromBgra(0xFF00FFFF);
public static readonly Color Cyan = Color.FromBgra( 0xFF00FFFF );
/// <summary>
/// DarkBlue color.
/// </summary>
public static readonly Color DarkBlue = Color.FromBgra(0xFF00008B);
public static readonly Color DarkBlue = Color.FromBgra( 0xFF00008B );
/// <summary>
/// DarkCyan color.
/// </summary>
public static readonly Color DarkCyan = Color.FromBgra(0xFF008B8B);
public static readonly Color DarkCyan = Color.FromBgra( 0xFF008B8B );
/// <summary>
/// DarkGoldenrod color.
/// </summary>
public static readonly Color DarkGoldenrod = Color.FromBgra(0xFFB8860B);
public static readonly Color DarkGoldenrod = Color.FromBgra( 0xFFB8860B );
/// <summary>
/// DarkGray color.
/// </summary>
public static readonly Color DarkGray = Color.FromBgra(0xFFA9A9A9);
public static readonly Color DarkGray = Color.FromBgra( 0xFFA9A9A9 );
/// <summary>
/// DarkGreen color.
/// </summary>
public static readonly Color DarkGreen = Color.FromBgra(0xFF006400);
public static readonly Color DarkGreen = Color.FromBgra( 0xFF006400 );
/// <summary>
/// DarkKhaki color.
/// </summary>
public static readonly Color DarkKhaki = Color.FromBgra(0xFFBDB76B);
public static readonly Color DarkKhaki = Color.FromBgra( 0xFFBDB76B );
/// <summary>
/// DarkMagenta color.
/// </summary>
public static readonly Color DarkMagenta = Color.FromBgra(0xFF8B008B);
public static readonly Color DarkMagenta = Color.FromBgra( 0xFF8B008B );
/// <summary>
/// DarkOliveGreen color.
/// </summary>
public static readonly Color DarkOliveGreen = Color.FromBgra(0xFF556B2F);
public static readonly Color DarkOliveGreen = Color.FromBgra( 0xFF556B2F );
/// <summary>
/// DarkOrange color.
/// </summary>
public static readonly Color DarkOrange = Color.FromBgra(0xFFFF8C00);
public static readonly Color DarkOrange = Color.FromBgra( 0xFFFF8C00 );
/// <summary>
/// DarkOrchid color.
/// </summary>
public static readonly Color DarkOrchid = Color.FromBgra(0xFF9932CC);
public static readonly Color DarkOrchid = Color.FromBgra( 0xFF9932CC );
/// <summary>
/// DarkRed color.
/// </summary>
public static readonly Color DarkRed = Color.FromBgra(0xFF8B0000);
public static readonly Color DarkRed = Color.FromBgra( 0xFF8B0000 );
/// <summary>
/// DarkSalmon color.
/// </summary>
public static readonly Color DarkSalmon = Color.FromBgra(0xFFE9967A);
public static readonly Color DarkSalmon = Color.FromBgra( 0xFFE9967A );
/// <summary>
/// DarkSeaGreen color.
/// </summary>
public static readonly Color DarkSeaGreen = Color.FromBgra(0xFF8FBC8B);
public static readonly Color DarkSeaGreen = Color.FromBgra( 0xFF8FBC8B );
/// <summary>
/// DarkSlateBlue color.
/// </summary>
public static readonly Color DarkSlateBlue = Color.FromBgra(0xFF483D8B);
public static readonly Color DarkSlateBlue = Color.FromBgra( 0xFF483D8B );
/// <summary>
/// DarkSlateGray color.
/// </summary>
public static readonly Color DarkSlateGray = Color.FromBgra(0xFF2F4F4F);
public static readonly Color DarkSlateGray = Color.FromBgra( 0xFF2F4F4F );
/// <summary>
/// DarkTurquoise color.
/// </summary>
public static readonly Color DarkTurquoise = Color.FromBgra(0xFF00CED1);
public static readonly Color DarkTurquoise = Color.FromBgra( 0xFF00CED1 );
/// <summary>
/// DarkViolet color.
/// </summary>
public static readonly Color DarkViolet = Color.FromBgra(0xFF9400D3);
public static readonly Color DarkViolet = Color.FromBgra( 0xFF9400D3 );
/// <summary>
/// DeepPink color.
/// </summary>
public static readonly Color DeepPink = Color.FromBgra(0xFFFF1493);
public static readonly Color DeepPink = Color.FromBgra( 0xFFFF1493 );
/// <summary>
/// DeepSkyBlue color.
/// </summary>
public static readonly Color DeepSkyBlue = Color.FromBgra(0xFF00BFFF);
public static readonly Color DeepSkyBlue = Color.FromBgra( 0xFF00BFFF );
/// <summary>
/// DimGray color.
/// </summary>
public static readonly Color DimGray = Color.FromBgra(0xFF696969);
public static readonly Color DimGray = Color.FromBgra( 0xFF696969 );
/// <summary>
/// VeryDimGray color.
/// </summary>
public static readonly Color VeryDimGray = Color.FromBgra(0xFF404040);
public static readonly Color VeryDimGray = Color.FromBgra( 0xFF404040 );
/// <summary>
/// DodgerBlue color.
/// </summary>
public static readonly Color DodgerBlue = Color.FromBgra(0xFF1E90FF);
public static readonly Color DodgerBlue = Color.FromBgra( 0xFF1E90FF );
/// <summary>
/// Firebrick color.
/// </summary>
public static readonly Color Firebrick = Color.FromBgra(0xFFB22222);
public static readonly Color Firebrick = Color.FromBgra( 0xFFB22222 );
/// <summary>
/// FloralWhite color.
/// </summary>
public static readonly Color FloralWhite = Color.FromBgra(0xFFFFFAF0);
public static readonly Color FloralWhite = Color.FromBgra( 0xFFFFFAF0 );
/// <summary>
/// ForestGreen color.
/// </summary>
public static readonly Color ForestGreen = Color.FromBgra(0xFF228B22);
public static readonly Color ForestGreen = Color.FromBgra( 0xFF228B22 );
/// <summary>
/// Fuchsia color.
/// </summary>
public static readonly Color Fuchsia = Color.FromBgra(0xFFFF00FF);
public static readonly Color Fuchsia = Color.FromBgra( 0xFFFF00FF );
/// <summary>
/// Gainsboro color.
/// </summary>
public static readonly Color Gainsboro = Color.FromBgra(0xFFDCDCDC);
public static readonly Color Gainsboro = Color.FromBgra( 0xFFDCDCDC );
/// <summary>
/// GhostWhite color.
/// </summary>
public static readonly Color GhostWhite = Color.FromBgra(0xFFF8F8FF);
public static readonly Color GhostWhite = Color.FromBgra( 0xFFF8F8FF );
/// <summary>
/// Gold color.
/// </summary>
public static readonly Color Gold = Color.FromBgra(0xFFFFD700);
public static readonly Color Gold = Color.FromBgra( 0xFFFFD700 );
/// <summary>
/// Goldenrod color.
/// </summary>
public static readonly Color Goldenrod = Color.FromBgra(0xFFDAA520);
public static readonly Color Goldenrod = Color.FromBgra( 0xFFDAA520 );
/// <summary>
/// Gray color.
/// </summary>
public static readonly Color Gray = Color.FromBgra(0xFF808080);
public static readonly Color Gray = Color.FromBgra( 0xFF808080 );
/// <summary>
/// Green color.
/// </summary>
public static readonly Color Green = Color.FromBgra(0xFF008000);
public static readonly Color Green = Color.FromBgra( 0xFF008000 );
/// <summary>
/// GreenYellow color.
/// </summary>
public static readonly Color GreenYellow = Color.FromBgra(0xFFADFF2F);
public static readonly Color GreenYellow = Color.FromBgra( 0xFFADFF2F );
/// <summary>
/// Honeydew color.
/// </summary>
public static readonly Color Honeydew = Color.FromBgra(0xFFF0FFF0);
public static readonly Color Honeydew = Color.FromBgra( 0xFFF0FFF0 );
/// <summary>
/// HotPink color.
/// </summary>
public static readonly Color HotPink = Color.FromBgra(0xFFFF69B4);
public static readonly Color HotPink = Color.FromBgra( 0xFFFF69B4 );
/// <summary>
/// IndianRed color.
/// </summary>
public static readonly Color IndianRed = Color.FromBgra(0xFFCD5C5C);
public static readonly Color IndianRed = Color.FromBgra( 0xFFCD5C5C );
/// <summary>
/// Indigo color.
/// </summary>
public static readonly Color Indigo = Color.FromBgra(0xFF4B0082);
public static readonly Color Indigo = Color.FromBgra( 0xFF4B0082 );
/// <summary>
/// Ivory color.
/// </summary>
public static readonly Color Ivory = Color.FromBgra(0xFFFFFFF0);
public static readonly Color Ivory = Color.FromBgra( 0xFFFFFFF0 );
/// <summary>
/// Khaki color.
/// </summary>
public static readonly Color Khaki = Color.FromBgra(0xFFF0E68C);
public static readonly Color Khaki = Color.FromBgra( 0xFFF0E68C );
/// <summary>
/// Lavender color.
/// </summary>
public static readonly Color Lavender = Color.FromBgra(0xFFE6E6FA);
public static readonly Color Lavender = Color.FromBgra( 0xFFE6E6FA );
/// <summary>
/// LavenderBlush color.
/// </summary>
public static readonly Color LavenderBlush = Color.FromBgra(0xFFFFF0F5);
public static readonly Color LavenderBlush = Color.FromBgra( 0xFFFFF0F5 );
/// <summary>
/// LawnGreen color.
/// </summary>
public static readonly Color LawnGreen = Color.FromBgra(0xFF7CFC00);
public static readonly Color LawnGreen = Color.FromBgra( 0xFF7CFC00 );
/// <summary>
/// LemonChiffon color.
/// </summary>
public static readonly Color LemonChiffon = Color.FromBgra(0xFFFFFACD);
public static readonly Color LemonChiffon = Color.FromBgra( 0xFFFFFACD );
/// <summary>
/// LightBlue color.
/// </summary>
public static readonly Color LightBlue = Color.FromBgra(0xFFADD8E6);
public static readonly Color LightBlue = Color.FromBgra( 0xFFADD8E6 );
/// <summary>
/// LightCoral color.
/// </summary>
public static readonly Color LightCoral = Color.FromBgra(0xFFF08080);
public static readonly Color LightCoral = Color.FromBgra( 0xFFF08080 );
/// <summary>
/// LightCyan color.
/// </summary>
public static readonly Color LightCyan = Color.FromBgra(0xFFE0FFFF);
public static readonly Color LightCyan = Color.FromBgra( 0xFFE0FFFF );
/// <summary>
/// LightGoldenrodYellow color.
/// </summary>
public static readonly Color LightGoldenrodYellow = Color.FromBgra(0xFFFAFAD2);
public static readonly Color LightGoldenrodYellow = Color.FromBgra( 0xFFFAFAD2 );
/// <summary>
/// LightGray color.
/// </summary>
public static readonly Color LightGray = Color.FromBgra(0xFFD3D3D3);
public static readonly Color LightGray = Color.FromBgra( 0xFFD3D3D3 );
/// <summary>
/// LightGreen color.
/// </summary>
public static readonly Color LightGreen = Color.FromBgra(0xFF90EE90);
public static readonly Color LightGreen = Color.FromBgra( 0xFF90EE90 );
/// <summary>
/// LightPink color.
/// </summary>
public static readonly Color LightPink = Color.FromBgra(0xFFFFB6C1);
public static readonly Color LightPink = Color.FromBgra( 0xFFFFB6C1 );
/// <summary>
/// LightSalmon color.
/// </summary>
public static readonly Color LightSalmon = Color.FromBgra(0xFFFFA07A);
public static readonly Color LightSalmon = Color.FromBgra( 0xFFFFA07A );
/// <summary>
/// LightSeaGreen color.
/// </summary>
public static readonly Color LightSeaGreen = Color.FromBgra(0xFF20B2AA);
public static readonly Color LightSeaGreen = Color.FromBgra( 0xFF20B2AA );
/// <summary>
/// LightSkyBlue color.
/// </summary>
public static readonly Color LightSkyBlue = Color.FromBgra(0xFF87CEFA);
public static readonly Color LightSkyBlue = Color.FromBgra( 0xFF87CEFA );
/// <summary>
/// LightSlateGray color.
/// </summary>
public static readonly Color LightSlateGray = Color.FromBgra(0xFF778899);
public static readonly Color LightSlateGray = Color.FromBgra( 0xFF778899 );
/// <summary>
/// LightSteelBlue color.
/// </summary>
public static readonly Color LightSteelBlue = Color.FromBgra(0xFFB0C4DE);
public static readonly Color LightSteelBlue = Color.FromBgra( 0xFFB0C4DE );
/// <summary>
/// LightYellow color.
/// </summary>
public static readonly Color LightYellow = Color.FromBgra(0xFFFFFFE0);
public static readonly Color LightYellow = Color.FromBgra( 0xFFFFFFE0 );
/// <summary>
/// Lime color.
/// </summary>
public static readonly Color Lime = Color.FromBgra(0xFF00FF00);
public static readonly Color Lime = Color.FromBgra( 0xFF00FF00 );
/// <summary>
/// LimeGreen color.
/// </summary>
public static readonly Color LimeGreen = Color.FromBgra(0xFF32CD32);
public static readonly Color LimeGreen = Color.FromBgra( 0xFF32CD32 );
/// <summary>
/// Linen color.
/// </summary>
public static readonly Color Linen = Color.FromBgra(0xFFFAF0E6);
public static readonly Color Linen = Color.FromBgra( 0xFFFAF0E6 );
/// <summary>
/// Magenta color.
/// </summary>
public static readonly Color Magenta = Color.FromBgra(0xFFFF00FF);
public static readonly Color Magenta = Color.FromBgra( 0xFFFF00FF );
/// <summary>
/// Maroon color.
/// </summary>
public static readonly Color Maroon = Color.FromBgra(0xFF800000);
public static readonly Color Maroon = Color.FromBgra( 0xFF800000 );
/// <summary>
/// MediumAquamarine color.
/// </summary>
public static readonly Color MediumAquamarine = Color.FromBgra(0xFF66CDAA);
public static readonly Color MediumAquamarine = Color.FromBgra( 0xFF66CDAA );
/// <summary>
/// MediumBlue color.
/// </summary>
public static readonly Color MediumBlue = Color.FromBgra(0xFF0000CD);
public static readonly Color MediumBlue = Color.FromBgra( 0xFF0000CD );
/// <summary>
/// MediumOrchid color.
/// </summary>
public static readonly Color MediumOrchid = Color.FromBgra(0xFFBA55D3);
public static readonly Color MediumOrchid = Color.FromBgra( 0xFFBA55D3 );
/// <summary>
/// MediumPurple color.
/// </summary>
public static readonly Color MediumPurple = Color.FromBgra(0xFF9370DB);
public static readonly Color MediumPurple = Color.FromBgra( 0xFF9370DB );
/// <summary>
/// MediumSeaGreen color.
/// </summary>
public static readonly Color MediumSeaGreen = Color.FromBgra(0xFF3CB371);
public static readonly Color MediumSeaGreen = Color.FromBgra( 0xFF3CB371 );
/// <summary>
/// MediumSlateBlue color.
/// </summary>
public static readonly Color MediumSlateBlue = Color.FromBgra(0xFF7B68EE);
public static readonly Color MediumSlateBlue = Color.FromBgra( 0xFF7B68EE );
/// <summary>
/// MediumSpringGreen color.
/// </summary>
public static readonly Color MediumSpringGreen = Color.FromBgra(0xFF00FA9A);
public static readonly Color MediumSpringGreen = Color.FromBgra( 0xFF00FA9A );
/// <summary>
/// MediumTurquoise color.
/// </summary>
public static readonly Color MediumTurquoise = Color.FromBgra(0xFF48D1CC);
public static readonly Color MediumTurquoise = Color.FromBgra( 0xFF48D1CC );
/// <summary>
/// MediumVioletRed color.
/// </summary>
public static readonly Color MediumVioletRed = Color.FromBgra(0xFFC71585);
public static readonly Color MediumVioletRed = Color.FromBgra( 0xFFC71585 );
/// <summary>
/// MidnightBlue color.
/// </summary>
public static readonly Color MidnightBlue = Color.FromBgra(0xFF191970);
public static readonly Color MidnightBlue = Color.FromBgra( 0xFF191970 );
/// <summary>
/// MintCream color.
/// </summary>
public static readonly Color MintCream = Color.FromBgra(0xFFF5FFFA);
public static readonly Color MintCream = Color.FromBgra( 0xFFF5FFFA );
/// <summary>
/// MistyRose color.
/// </summary>
public static readonly Color MistyRose = Color.FromBgra(0xFFFFE4E1);
public static readonly Color MistyRose = Color.FromBgra( 0xFFFFE4E1 );
/// <summary>
/// Moccasin color.
/// </summary>
public static readonly Color Moccasin = Color.FromBgra(0xFFFFE4B5);
public static readonly Color Moccasin = Color.FromBgra( 0xFFFFE4B5 );
/// <summary>
/// NavajoWhite color.
/// </summary>
public static readonly Color NavajoWhite = Color.FromBgra(0xFFFFDEAD);
public static readonly Color NavajoWhite = Color.FromBgra( 0xFFFFDEAD );
/// <summary>
/// Navy color.
/// </summary>
public static readonly Color Navy = Color.FromBgra(0xFF000080);
public static readonly Color Navy = Color.FromBgra( 0xFF000080 );
/// <summary>
/// OldLace color.
/// </summary>
public static readonly Color OldLace = Color.FromBgra(0xFFFDF5E6);
public static readonly Color OldLace = Color.FromBgra( 0xFFFDF5E6 );
/// <summary>
/// Olive color.
/// </summary>
public static readonly Color Olive = Color.FromBgra(0xFF808000);
public static readonly Color Olive = Color.FromBgra( 0xFF808000 );
/// <summary>
/// OliveDrab color.
/// </summary>
public static readonly Color OliveDrab = Color.FromBgra(0xFF6B8E23);
public static readonly Color OliveDrab = Color.FromBgra( 0xFF6B8E23 );
/// <summary>
/// Orange color.
/// </summary>
public static readonly Color Orange = Color.FromBgra(0xFFFFA500);
public static readonly Color Orange = Color.FromBgra( 0xFFFFA500 );
/// <summary>
/// OrangeRed color.
/// </summary>
public static readonly Color OrangeRed = Color.FromBgra(0xFFFF4500);
public static readonly Color OrangeRed = Color.FromBgra( 0xFFFF4500 );
/// <summary>
/// Orchid color.
/// </summary>
public static readonly Color Orchid = Color.FromBgra(0xFFDA70D6);
public static readonly Color Orchid = Color.FromBgra( 0xFFDA70D6 );
/// <summary>
/// PaleGoldenrod color.
/// </summary>
public static readonly Color PaleGoldenrod = Color.FromBgra(0xFFEEE8AA);
public static readonly Color PaleGoldenrod = Color.FromBgra( 0xFFEEE8AA );
/// <summary>
/// PaleGreen color.
/// </summary>
public static readonly Color PaleGreen = Color.FromBgra(0xFF98FB98);
public static readonly Color PaleGreen = Color.FromBgra( 0xFF98FB98 );
/// <summary>
/// PaleTurquoise color.
/// </summary>
public static readonly Color PaleTurquoise = Color.FromBgra(0xFFAFEEEE);
public static readonly Color PaleTurquoise = Color.FromBgra( 0xFFAFEEEE );
/// <summary>
/// PaleVioletRed color.
/// </summary>
public static readonly Color PaleVioletRed = Color.FromBgra(0xFFDB7093);
public static readonly Color PaleVioletRed = Color.FromBgra( 0xFFDB7093 );
/// <summary>
/// PapayaWhip color.
/// </summary>
public static readonly Color PapayaWhip = Color.FromBgra(0xFFFFEFD5);
public static readonly Color PapayaWhip = Color.FromBgra( 0xFFFFEFD5 );
/// <summary>
/// PeachPuff color.
/// </summary>
public static readonly Color PeachPuff = Color.FromBgra(0xFFFFDAB9);
public static readonly Color PeachPuff = Color.FromBgra( 0xFFFFDAB9 );
/// <summary>
/// Peru color.
/// </summary>
public static readonly Color Peru = Color.FromBgra(0xFFCD853F);
public static readonly Color Peru = Color.FromBgra( 0xFFCD853F );
/// <summary>
/// Pink color.
/// </summary>
public static readonly Color Pink = Color.FromBgra(0xFFFFC0CB);
public static readonly Color Pink = Color.FromBgra( 0xFFFFC0CB );
/// <summary>
/// Plum color.
/// </summary>
public static readonly Color Plum = Color.FromBgra(0xFFDDA0DD);
public static readonly Color Plum = Color.FromBgra( 0xFFDDA0DD );
/// <summary>
/// PowderBlue color.
/// </summary>
public static readonly Color PowderBlue = Color.FromBgra(0xFFB0E0E6);
public static readonly Color PowderBlue = Color.FromBgra( 0xFFB0E0E6 );
/// <summary>
/// Purple color.
/// </summary>
public static readonly Color Purple = Color.FromBgra(0xFF800080);
public static readonly Color Purple = Color.FromBgra( 0xFF800080 );
/// <summary>
/// Red color.
/// </summary>
public static readonly Color Red = Color.FromBgra(0xFFFF0000);
public static readonly Color Red = Color.FromBgra( 0xFFFF0000 );
/// <summary>
/// RosyBrown color.
/// </summary>
public static readonly Color RosyBrown = Color.FromBgra(0xFFBC8F8F);
public static readonly Color RosyBrown = Color.FromBgra( 0xFFBC8F8F );
/// <summary>
/// RoyalBlue color.
/// </summary>
public static readonly Color RoyalBlue = Color.FromBgra(0xFF4169E1);
public static readonly Color RoyalBlue = Color.FromBgra( 0xFF4169E1 );
/// <summary>
/// SaddleBrown color.
/// </summary>
public static readonly Color SaddleBrown = Color.FromBgra(0xFF8B4513);
public static readonly Color SaddleBrown = Color.FromBgra( 0xFF8B4513 );
/// <summary>
/// Salmon color.
/// </summary>
public static readonly Color Salmon = Color.FromBgra(0xFFFA8072);
public static readonly Color Salmon = Color.FromBgra( 0xFFFA8072 );
/// <summary>
/// SandyBrown color.
/// </summary>
public static readonly Color SandyBrown = Color.FromBgra(0xFFF4A460);
public static readonly Color SandyBrown = Color.FromBgra( 0xFFF4A460 );
/// <summary>
/// SeaGreen color.
/// </summary>
public static readonly Color SeaGreen = Color.FromBgra(0xFF2E8B57);
public static readonly Color SeaGreen = Color.FromBgra( 0xFF2E8B57 );
/// <summary>
/// SeaShell color.
/// </summary>
public static readonly Color SeaShell = Color.FromBgra(0xFFFFF5EE);
public static readonly Color SeaShell = Color.FromBgra( 0xFFFFF5EE );
/// <summary>
/// Sienna color.
/// </summary>
public static readonly Color Sienna = Color.FromBgra(0xFFA0522D);
public static readonly Color Sienna = Color.FromBgra( 0xFFA0522D );
/// <summary>
/// Silver color.
/// </summary>
public static readonly Color Silver = Color.FromBgra(0xFFC0C0C0);
public static readonly Color Silver = Color.FromBgra( 0xFFC0C0C0 );
/// <summary>
/// SkyBlue color.
/// </summary>
public static readonly Color SkyBlue = Color.FromBgra(0xFF87CEEB);
public static readonly Color SkyBlue = Color.FromBgra( 0xFF87CEEB );
/// <summary>
/// SlateBlue color.
/// </summary>
public static readonly Color SlateBlue = Color.FromBgra(0xFF6A5ACD);
public static readonly Color SlateBlue = Color.FromBgra( 0xFF6A5ACD );
/// <summary>
/// SlateGray color.
/// </summary>
public static readonly Color SlateGray = Color.FromBgra(0xFF708090);
public static readonly Color SlateGray = Color.FromBgra( 0xFF708090 );
/// <summary>
/// Snow color.
/// </summary>
public static readonly Color Snow = Color.FromBgra(0xFFFFFAFA);
public static readonly Color Snow = Color.FromBgra( 0xFFFFFAFA );
/// <summary>
/// SpringGreen color.
/// </summary>
public static readonly Color SpringGreen = Color.FromBgra(0xFF00FF7F);
public static readonly Color SpringGreen = Color.FromBgra( 0xFF00FF7F );
/// <summary>
/// SteelBlue color.
/// </summary>
public static readonly Color SteelBlue = Color.FromBgra(0xFF4682B4);
public static readonly Color SteelBlue = Color.FromBgra( 0xFF4682B4 );
/// <summary>
/// Tan color.
/// </summary>
public static readonly Color Tan = Color.FromBgra(0xFFD2B48C);
public static readonly Color Tan = Color.FromBgra( 0xFFD2B48C );
/// <summary>
/// Teal color.
/// </summary>
public static readonly Color Teal = Color.FromBgra(0xFF008080);
public static readonly Color Teal = Color.FromBgra( 0xFF008080 );
/// <summary>
/// Thistle color.
/// </summary>
public static readonly Color Thistle = Color.FromBgra(0xFFD8BFD8);
public static readonly Color Thistle = Color.FromBgra( 0xFFD8BFD8 );
/// <summary>
/// Tomato color.
/// </summary>
public static readonly Color Tomato = Color.FromBgra(0xFFFF6347);
public static readonly Color Tomato = Color.FromBgra( 0xFFFF6347 );
/// <summary>
/// Turquoise color.
/// </summary>
public static readonly Color Turquoise = Color.FromBgra(0xFF40E0D0);
public static readonly Color Turquoise = Color.FromBgra( 0xFF40E0D0 );
/// <summary>
/// Violet color.
/// </summary>
public static readonly Color Violet = Color.FromBgra(0xFFEE82EE);
public static readonly Color Violet = Color.FromBgra( 0xFFEE82EE );
/// <summary>
/// Wheat color.
/// </summary>
public static readonly Color Wheat = Color.FromBgra(0xFFF5DEB3);
public static readonly Color Wheat = Color.FromBgra( 0xFFF5DEB3 );
/// <summary>
/// White color.
/// </summary>
public static readonly Color White = Color.FromBgra(0xFFFFFFFF);
public static readonly Color White = Color.FromBgra( 0xFFFFFFFF );
/// <summary>
/// WhiteSmoke color.
/// </summary>
public static readonly Color WhiteSmoke = Color.FromBgra(0xFFF5F5F5);
public static readonly Color WhiteSmoke = Color.FromBgra( 0xFFF5F5F5 );
/// <summary>
/// Yellow color.
/// </summary>
public static readonly Color Yellow = Color.FromBgra(0xFFFFFF00);
public static readonly Color Yellow = Color.FromBgra( 0xFFFFFF00 );
/// <summary>
/// YellowGreen color.
/// </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

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -36,9 +36,9 @@ namespace math
/// <summary>
/// Represents a color in the form of rgb.
/// </summary>
[DataContract( Name = "Color3")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Color3" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Color3 : IEquatable<Color3>, IFormattable
{
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.
/// </summary>
/// <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;
}
@ -76,7 +76,7 @@ namespace math
/// <param name="red">The red 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>
public Color3(float red, float green, float blue)
public Color3( float red, float green, float blue )
{
R = red;
G = green;
@ -87,7 +87,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color3"/> struct.
/// </summary>
/// <param name="value">The red, green, and blue components of the color.</param>
public Color3(Vec3 value)
public Color3( Vec3 value )
{
R = value.X;
G = value.Y;
@ -99,11 +99,11 @@ namespace math
/// </summary>
/// <param name="rgb">A packed integer containing all three color components.
/// The alpha component is ignored.</param>
public Color3(int rgb)
public Color3( int rgb )
{
B = ((rgb >> 16) & 255) / 255.0f;
G = ((rgb >> 8) & 255) / 255.0f;
R = (rgb & 255) / 255.0f;
B = ( ( rgb >> 16 ) & 255 ) / 255.0f;
G = ( ( rgb >> 8 ) & 255 ) / 255.0f;
R = ( rgb & 255 ) / 255.0f;
}
/// <summary>
@ -111,11 +111,11 @@ namespace math
/// </summary>
/// <param name="rgb">A packed unsigned integer containing all three color components.
/// The alpha component is ignored.</param>
public Color3(uint rgb)
public Color3( uint rgb )
{
B = ((rgb >> 16) & 255) / 255.0f;
G = ((rgb >> 8) & 255) / 255.0f;
R = (rgb & 255) / 255.0f;
B = ( ( rgb >> 16 ) & 255 ) / 255.0f;
G = ( ( rgb >> 8 ) & 255 ) / 255.0f;
R = ( rgb & 255 ) / 255.0f;
}
/// <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>
/// <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>
public Color3(float[] values)
public Color3( float[] values )
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length != 3)
throw new ArgumentOutOfRangeException(nameof(values), "There must be three and only three input values for Color3.");
if( values == null )
throw new ArgumentNullException( nameof( values ) );
if( values.Length != 3 )
throw new ArgumentOutOfRangeException( nameof( values ), "There must be three and only three input values for Color3." );
R = values[0];
G = values[1];
@ -147,24 +147,34 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0: return R;
case 1: return G;
case 2: return B;
case 0:
return R;
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
{
switch (index)
switch( index )
{
case 0: R = value; break;
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.");
case 0:
R = value;
break;
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()
{
uint a = 255;
uint r = (uint)(R * 255.0f);
uint g = (uint)(G * 255.0f);
uint b = (uint)(B * 255.0f);
uint r = (uint)( R * 255.0f );
uint g = (uint)( G * 255.0f );
uint b = (uint)( B * 255.0f );
uint value = r;
value += g << 8;
@ -193,11 +203,11 @@ namespace math
/// Raises the exponent for each components.
/// </summary>
/// <param name="exponent">The exponent.</param>
public void Pow(float exponent)
public void Pow( float exponent )
{
R = (float)Math.Pow(R, exponent);
G = (float)Math.Pow(G, exponent);
B = (float)Math.Pow(B, exponent);
R = (float)Math.Pow( R, exponent );
G = (float)Math.Pow( G, exponent );
B = (float)Math.Pow( B, exponent );
}
/// <summary>
@ -206,7 +216,7 @@ namespace math
/// <returns>A three component vector containing the red, green, and blue components of the color.</returns>
public Vec3 ToVector3()
{
return new Vec3(R, G, B);
return new Vec3( R, G, B );
}
/// <summary>
@ -224,7 +234,7 @@ namespace math
/// <param name="left">The first 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>
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.G = left.G + right.G;
@ -237,9 +247,9 @@ namespace math
/// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param>
/// <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>
@ -248,7 +258,7 @@ namespace math
/// <param name="left">The first 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>
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.G = left.G - right.G;
@ -261,9 +271,9 @@ namespace math
/// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract</param>
/// <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>
@ -272,7 +282,7 @@ namespace math
/// <param name="left">The first 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>
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.G = left.G * right.G;
@ -285,9 +295,9 @@ namespace math
/// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param>
/// <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>
@ -296,7 +306,7 @@ namespace math
/// <param name="value">The color 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>
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.G = value.G * scale;
@ -309,9 +319,9 @@ namespace math
/// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param>
/// <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>
@ -319,7 +329,7 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</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.G = 1.0f - value.G;
@ -331,9 +341,9 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</param>
/// <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>
@ -343,21 +353,21 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum 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;
red = (red > max.R) ? max.R : red;
red = (red < min.R) ? min.R : red;
red = ( red > max.R ) ? max.R : red;
red = ( red < min.R ) ? min.R : red;
float green = value.G;
green = (green > max.G) ? max.G : green;
green = (green < min.G) ? min.G : green;
green = ( green > max.G ) ? max.G : green;
green = ( green < min.G ) ? min.G : green;
float blue = value.B;
blue = (blue > max.B) ? max.B : blue;
blue = (blue < min.B) ? min.B : blue;
blue = ( blue > max.B ) ? max.B : blue;
blue = ( blue < min.B ) ? min.B : blue;
result = new Color3(red, green, blue);
result = new Color3( red, green, blue );
}
/// <summary>
@ -367,10 +377,10 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -384,13 +394,13 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
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.G = start.G + amount * (end.G - start.G);
result.B = start.B + amount * (end.B - start.B);
result.R = start.R + amount * ( end.R - start.R );
result.G = start.G + amount * ( end.G - start.G );
result.B = start.B + amount * ( end.B - start.B );
}
/// <summary>
@ -403,14 +413,14 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
public static Color3 Lerp(Color3 start, Color3 end, float amount)
public static Color3 Lerp( Color3 start, Color3 end, float amount )
{
return new Color3(
start.R + amount * (end.R - start.R),
start.G + amount * (end.G - start.G),
start.B + amount * (end.B - start.B));
start.R + amount * ( end.R - start.R ),
start.G + amount * ( end.G - start.G ),
start.B + amount * ( end.B - start.B ) );
}
/// <summary>
@ -420,14 +430,14 @@ namespace math
/// <param name="end">End color.</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>
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 * amount) * (3.0f - (2.0f * amount));
amount = ( amount > 1.0f ) ? 1.0f : ( ( amount < 0.0f ) ? 0.0f : amount );
amount = ( amount * amount ) * ( 3.0f - ( 2.0f * amount ) );
result.R = start.R + ((end.R - start.R) * amount);
result.G = start.G + ((end.G - start.G) * amount);
result.B = start.B + ((end.B - start.B) * amount);
result.R = start.R + ( ( end.R - start.R ) * amount );
result.G = start.G + ( ( end.G - start.G ) * amount );
result.B = start.B + ( ( end.B - start.B ) * amount );
}
/// <summary>
@ -437,15 +447,15 @@ namespace math
/// <param name="end">End color.</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>
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 * amount) * (3.0f - (2.0f * amount));
amount = ( amount > 1.0f ) ? 1.0f : ( ( amount < 0.0f ) ? 0.0f : amount );
amount = ( amount * amount ) * ( 3.0f - ( 2.0f * amount ) );
return new Color3(
start.R + ((end.R - start.R) * amount),
start.G + ((end.G - start.G) * amount),
start.B + ((end.B - start.B) * amount));
start.R + ( ( end.R - start.R ) * amount ),
start.G + ( ( end.G - start.G ) * amount ),
start.B + ( ( end.B - start.B ) * amount ) );
}
/// <summary>
@ -454,11 +464,11 @@ namespace math
/// <param name="left">The first 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>
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.G = (left.G > right.G) ? left.G : right.G;
result.B = (left.B > right.B) ? left.B : right.B;
result.R = ( left.R > right.R ) ? left.R : right.R;
result.G = ( left.G > right.G ) ? left.G : right.G;
result.B = ( left.B > right.B ) ? left.B : right.B;
}
/// <summary>
@ -467,10 +477,10 @@ namespace math
/// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -480,11 +490,11 @@ namespace math
/// <param name="left">The first 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>
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.G = (left.G < right.G) ? left.G : right.G;
result.B = (left.B < right.B) ? left.B : right.B;
result.R = ( left.R < right.R ) ? left.R : right.R;
result.G = ( left.G < right.G ) ? left.G : right.G;
result.B = ( left.B < right.B ) ? left.B : right.B;
}
/// <summary>
@ -493,10 +503,10 @@ namespace math
/// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
@ -506,11 +516,11 @@ namespace math
/// <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="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.G = 0.5f + contrast * (value.G - 0.5f);
result.B = 0.5f + contrast * (value.B - 0.5f);
result.R = 0.5f + contrast * ( value.R - 0.5f );
result.G = 0.5f + contrast * ( value.G - 0.5f );
result.B = 0.5f + contrast * ( value.B - 0.5f );
}
/// <summary>
@ -519,12 +529,12 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <returns>The adjusted color.</returns>
public static Color3 AdjustContrast(Color3 value, float contrast)
public static Color3 AdjustContrast( Color3 value, float contrast )
{
return new Color3(
0.5f + contrast * (value.R - 0.5f),
0.5f + contrast * (value.G - 0.5f),
0.5f + contrast * (value.B - 0.5f));
0.5f + contrast * ( value.R - 0.5f ),
0.5f + contrast * ( value.G - 0.5f ),
0.5f + contrast * ( value.B - 0.5f ) );
}
/// <summary>
@ -533,13 +543,13 @@ namespace math
/// <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="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;
result.R = grey + saturation * (value.R - grey);
result.G = grey + saturation * (value.G - grey);
result.B = grey + saturation * (value.B - grey);
result.R = grey + saturation * ( value.R - grey );
result.G = grey + saturation * ( value.G - grey );
result.B = grey + saturation * ( value.B - grey );
}
/// <summary>
@ -548,14 +558,14 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <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;
return new Color3(
grey + saturation * (value.R - grey),
grey + saturation * (value.G - grey),
grey + saturation * (value.B - grey));
grey + saturation * ( value.R - grey ),
grey + saturation * ( value.G - grey ),
grey + saturation * ( value.B - grey ) );
}
/// <summary>
@ -564,7 +574,7 @@ namespace math
/// <returns>A color3 in sRGB space.</returns>
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>
@ -573,7 +583,7 @@ namespace math
/// <returns>Color3.</returns>
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>
@ -582,9 +592,9 @@ namespace math
/// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param>
/// <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>
@ -592,7 +602,7 @@ namespace math
/// </summary>
/// <param name="value">The color to assert (unchange).</param>
/// <returns>The asserted (unchanged) color.</returns>
public static Color3 operator +(Color3 value)
public static Color3 operator +( Color3 value )
{
return value;
}
@ -603,9 +613,9 @@ namespace math
/// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param>
/// <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>
@ -613,9 +623,9 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</param>
/// <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>
@ -624,9 +634,9 @@ namespace math
/// <param name="scale">The factor by which to scale the color.</param>
/// <param name="value">The color to scale.</param>
/// <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>
@ -635,9 +645,9 @@ namespace math
/// <param name="value">The factor by which to scale the color.</param>
/// <param name="scale">The color to scale.</param>
/// <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>
@ -646,9 +656,9 @@ namespace math
/// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param>
/// <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>
@ -657,9 +667,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -668,9 +678,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -678,9 +688,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -688,9 +698,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -698,9 +708,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -708,9 +718,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -721,7 +731,7 @@ namespace math
/// </returns>
public override string ToString()
{
return ToString(CultureInfo.CurrentCulture);
return ToString( CultureInfo.CurrentCulture );
}
/// <summary>
@ -730,7 +740,7 @@ namespace math
/// <returns>An equivalent <see cref="Color4"/> with an opaque alpha.</returns>
public Color4 ToColor4()
{
return new Color4(R, G, B, 1.0f);
return new Color4( R, G, B, 1.0f );
}
/// <summary>
@ -740,9 +750,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
return ToString(format, CultureInfo.CurrentCulture);
return ToString( format, CultureInfo.CurrentCulture );
}
/// <summary>
@ -752,9 +762,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -765,22 +775,22 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
return ToString( formatProvider );
return string.Format(formatProvider, ToStringFormat,
R.ToString(format, formatProvider),
G.ToString(format, formatProvider),
B.ToString(format, formatProvider));
return string.Format( formatProvider, ToStringFormat,
R.ToString( format, formatProvider ),
G.ToString( format, formatProvider ),
B.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -794,7 +804,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="Color3"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Color3 other)
public bool Equals( Color3 other )
{
return R == other.R && G == other.G && B == other.B;
}
@ -806,15 +816,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Color3)value);
return Equals( (Color3)value );
}
#if SlimDX1xInterop

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -36,9 +36,9 @@ namespace math
/// <summary>
/// Represents a color in the form of rgba.
/// </summary>
[DataContract( Name = "Color4")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Color4" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Color4 : IEquatable<Color4>, IFormattable
{
private const string ToStringFormat = "A:{0} R:{1} G:{2} B:{3}";
@ -46,12 +46,12 @@ namespace math
/// <summary>
/// The Black color (0, 0, 0, 1).
/// </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>
/// The White color (1, 1, 1, 1).
/// </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>
/// The red component of the color.
@ -81,7 +81,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
}
@ -93,7 +93,7 @@ namespace math
/// <param name="green">The green 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>
public Color4(float red, float green, float blue, float alpha)
public Color4( float red, float green, float blue, float alpha )
{
R = red;
G = green;
@ -105,7 +105,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
G = value.Y;
@ -118,7 +118,7 @@ namespace math
/// </summary>
/// <param name="value">The red, green, and blue components 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;
G = value.Y;
@ -130,24 +130,24 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
B = ((rgba >> 16) & 255) / 255.0f;
G = ((rgba >> 8) & 255) / 255.0f;
R = (rgba & 255) / 255.0f;
A = ( ( rgba >> 24 ) & 255 ) / 255.0f;
B = ( ( rgba >> 16 ) & 255 ) / 255.0f;
G = ( ( rgba >> 8 ) & 255 ) / 255.0f;
R = ( rgba & 255 ) / 255.0f;
}
/// <summary>
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
B = ((rgba >> 16) & 255) / 255.0f;
G = ((rgba >> 8) & 255) / 255.0f;
R = (rgba & 255) / 255.0f;
A = ( ( rgba >> 24 ) & 255 ) / 255.0f;
B = ( ( rgba >> 16 ) & 255 ) / 255.0f;
G = ( ( rgba >> 8 ) & 255 ) / 255.0f;
R = ( rgba & 255 ) / 255.0f;
}
/// <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>
/// <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>
public Color4(float[] values)
public Color4( float[] values )
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length != 4)
throw new ArgumentOutOfRangeException(nameof(values), "There must be four and only four input values for Color4.");
if( values == null )
throw new ArgumentNullException( nameof( values ) );
if( values.Length != 4 )
throw new ArgumentOutOfRangeException( nameof( values ), "There must be four and only four input values for Color4." );
R = values[0];
G = values[1];
@ -173,7 +173,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <param name="color"><see cref="Color3"/> used to initialize the color.</param>
public Color4(Color3 color)
public Color4( Color3 color )
{
R = color.R;
G = color.G;
@ -185,7 +185,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
G = color.G / 255.0f;
@ -197,7 +197,7 @@ namespace math
/// Initializes a new instance of the <see cref="Color4"/> struct.
/// </summary>
/// <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;
G = color.G / 255.0f;
@ -210,7 +210,7 @@ namespace math
/// </summary>
/// <param name="color"><see cref="Color3"/> used to initialize 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;
G = color.G;
@ -229,26 +229,39 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0: return R;
case 1: return G;
case 2: return B;
case 3: return A;
case 0:
return R;
case 1:
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
{
switch (index)
switch( index )
{
case 0: R = value; break;
case 1: 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.");
case 0:
R = value;
break;
case 1:
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>
public int ToBgra()
{
uint a = (uint)(A * 255.0f) & 255;
uint r = (uint)(R * 255.0f) & 255;
uint g = (uint)(G * 255.0f) & 255;
uint b = (uint)(B * 255.0f) & 255;
uint a = (uint)( A * 255.0f ) & 255;
uint r = (uint)( R * 255.0f ) & 255;
uint g = (uint)( G * 255.0f ) & 255;
uint b = (uint)( B * 255.0f ) & 255;
uint value = b;
value |= g << 8;
@ -275,12 +288,12 @@ namespace math
/// <summary>
/// Converts the color into a packed integer.
/// </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);
r = (byte)(R * 255.0f);
g = (byte)(G * 255.0f);
b = (byte)(B * 255.0f);
a = (byte)( A * 255.0f );
r = (byte)( R * 255.0f );
g = (byte)( G * 255.0f );
b = (byte)( B * 255.0f );
}
/// <summary>
@ -289,10 +302,10 @@ namespace math
/// <returns>A packed integer containing all four color components.</returns>
public int ToRgba()
{
uint a = (uint)(A * 255.0f) & 255;
uint r = (uint)(R * 255.0f) & 255;
uint g = (uint)(G * 255.0f) & 255;
uint b = (uint)(B * 255.0f) & 255;
uint a = (uint)( A * 255.0f ) & 255;
uint r = (uint)( R * 255.0f ) & 255;
uint g = (uint)( G * 255.0f ) & 255;
uint b = (uint)( B * 255.0f ) & 255;
uint value = r;
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>
public Vec3 ToVector3()
{
return new Vec3(R, G, B);
return new Vec3( R, G, B );
}
/// <summary>
@ -317,7 +330,7 @@ namespace math
/// <returns>A four component vector containing all four color components.</returns>
public Vec4 ToVector4()
{
return new Vec4(R, G, B, A);
return new Vec4( R, G, B, A );
}
/// <summary>
@ -335,7 +348,7 @@ namespace math
/// <returns>A color3 in sRGB space.</returns>
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>
@ -344,7 +357,7 @@ namespace math
/// <returns>A color4 in linear space.</returns>
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>
@ -353,7 +366,7 @@ namespace math
/// <param name="left">The first 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>
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.R = left.R + right.R;
@ -367,9 +380,9 @@ namespace math
/// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param>
/// <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>
@ -378,7 +391,7 @@ namespace math
/// <param name="left">The first 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>
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.R = left.R - right.R;
@ -392,9 +405,9 @@ namespace math
/// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract</param>
/// <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>
@ -403,7 +416,7 @@ namespace math
/// <param name="left">The first 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>
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.R = left.R * right.R;
@ -417,9 +430,9 @@ namespace math
/// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param>
/// <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>
@ -428,7 +441,7 @@ namespace math
/// <param name="value">The color 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>
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.R = value.R * scale;
@ -442,9 +455,9 @@ namespace math
/// <param name="value">The color to scale.</param>
/// <param name="scale">The amount by which to scale.</param>
/// <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>
@ -452,7 +465,7 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</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.R = 1.0f - value.R;
@ -465,9 +478,9 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</param>
/// <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>
@ -477,25 +490,25 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum 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;
alpha = (alpha > max.A) ? max.A : alpha;
alpha = (alpha < min.A) ? min.A : alpha;
alpha = ( alpha > max.A ) ? max.A : alpha;
alpha = ( alpha < min.A ) ? min.A : alpha;
float red = value.R;
red = (red > max.R) ? max.R : red;
red = (red < min.R) ? min.R : red;
red = ( red > max.R ) ? max.R : red;
red = ( red < min.R ) ? min.R : red;
float green = value.G;
green = (green > max.G) ? max.G : green;
green = (green < min.G) ? min.G : green;
green = ( green > max.G ) ? max.G : green;
green = ( green < min.G ) ? min.G : green;
float blue = value.B;
blue = (blue > max.B) ? max.B : blue;
blue = (blue < min.B) ? min.B : blue;
blue = ( blue > max.B ) ? max.B : blue;
blue = ( blue < min.B ) ? min.B : blue;
result = new Color4(red, green, blue, alpha);
result = new Color4( red, green, blue, alpha );
}
/// <summary>
@ -505,10 +518,10 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -520,14 +533,14 @@ namespace math
/// <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 linear interpolation of the two colors.</param>
/// <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>
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.G = MathUtil.Lerp(start.G, end.G, amount);
result.B = MathUtil.Lerp(start.B, end.B, amount);
result.A = MathUtil.Lerp(start.A, end.A, amount);
result.R = MathUtil.Lerp( start.R, end.R, amount );
result.G = MathUtil.Lerp( start.G, end.G, amount );
result.B = MathUtil.Lerp( start.B, end.B, amount );
result.A = MathUtil.Lerp( start.A, end.A, amount );
}
/// <summary>
@ -538,12 +551,12 @@ namespace math
/// <param name="amount">Value between 0 and 1 indicating the weight of <paramref name="end"/>.</param>
/// <returns>The linear interpolation of the two colors.</returns>
/// <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>
public static Color4 Lerp(Color4 start, Color4 end, float amount)
public static Color4 Lerp( Color4 start, Color4 end, float amount )
{
Color4 result;
Lerp(ref start, ref end, amount, out result);
Lerp( ref start, ref end, amount, out result );
return result;
}
@ -554,10 +567,10 @@ namespace math
/// <param name="end">End color.</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>
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);
Lerp(ref start, ref end, amount, out result);
amount = MathUtil.SmoothStep( amount );
Lerp( ref start, ref end, amount, out result );
}
/// <summary>
@ -567,10 +580,10 @@ namespace math
/// <param name="end">End color.</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>
public static Color4 SmoothStep(Color4 start, Color4 end, float amount)
public static Color4 SmoothStep( Color4 start, Color4 end, float amount )
{
Color4 result;
SmoothStep(ref start, ref end, amount, out result);
SmoothStep( ref start, ref end, amount, out result );
return result;
}
@ -580,12 +593,12 @@ namespace math
/// <param name="left">The first 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>
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.R = (left.R > right.R) ? left.R : right.R;
result.G = (left.G > right.G) ? left.G : right.G;
result.B = (left.B > right.B) ? left.B : right.B;
result.A = ( left.A > right.A ) ? left.A : right.A;
result.R = ( left.R > right.R ) ? left.R : right.R;
result.G = ( left.G > right.G ) ? left.G : right.G;
result.B = ( left.B > right.B ) ? left.B : right.B;
}
/// <summary>
@ -594,10 +607,10 @@ namespace math
/// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -607,12 +620,12 @@ namespace math
/// <param name="left">The first 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>
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.R = (left.R < right.R) ? left.R : right.R;
result.G = (left.G < right.G) ? left.G : right.G;
result.B = (left.B < right.B) ? left.B : right.B;
result.A = ( left.A < right.A ) ? left.A : right.A;
result.R = ( left.R < right.R ) ? left.R : right.R;
result.G = ( left.G < right.G ) ? left.G : right.G;
result.B = ( left.B < right.B ) ? left.B : right.B;
}
/// <summary>
@ -621,10 +634,10 @@ namespace math
/// <param name="left">The first source color.</param>
/// <param name="right">The second source color.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
@ -634,12 +647,12 @@ namespace math
/// <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="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.R = 0.5f + contrast * (value.R - 0.5f);
result.G = 0.5f + contrast * (value.G - 0.5f);
result.B = 0.5f + contrast * (value.B - 0.5f);
result.R = 0.5f + contrast * ( value.R - 0.5f );
result.G = 0.5f + contrast * ( value.G - 0.5f );
result.B = 0.5f + contrast * ( value.B - 0.5f );
}
/// <summary>
@ -648,13 +661,13 @@ namespace math
/// <param name="value">The color whose contrast is to be adjusted.</param>
/// <param name="contrast">The amount by which to adjust the contrast.</param>
/// <returns>The adjusted color.</returns>
public static Color4 AdjustContrast(Color4 value, float contrast)
public static Color4 AdjustContrast( Color4 value, float contrast )
{
return new Color4(
0.5f + contrast * (value.R - 0.5f),
0.5f + contrast * (value.G - 0.5f),
0.5f + contrast * (value.B - 0.5f),
value.A);
0.5f + contrast * ( value.R - 0.5f ),
0.5f + contrast * ( value.G - 0.5f ),
0.5f + contrast * ( value.B - 0.5f ),
value.A );
}
/// <summary>
@ -663,14 +676,14 @@ namespace math
/// <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="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;
result.A = value.A;
result.R = grey + saturation * (value.R - grey);
result.G = grey + saturation * (value.G - grey);
result.B = grey + saturation * (value.B - grey);
result.R = grey + saturation * ( value.R - grey );
result.G = grey + saturation * ( value.G - grey );
result.B = grey + saturation * ( value.B - grey );
}
/// <summary>
@ -679,15 +692,15 @@ namespace math
/// <param name="value">The color whose saturation is to be adjusted.</param>
/// <param name="saturation">The amount by which to adjust the saturation.</param>
/// <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;
return new Color4(
grey + saturation * (value.R - grey),
grey + saturation * (value.G - grey),
grey + saturation * (value.B - grey),
value.A);
grey + saturation * ( value.R - grey ),
grey + saturation * ( value.G - grey ),
grey + saturation * ( value.B - grey ),
value.A );
}
/// <summary>
@ -695,9 +708,9 @@ namespace math
/// </summary>
/// <param name="value">The color to premultiply.</param>
/// <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>
@ -706,9 +719,9 @@ namespace math
/// <param name="left">The first color to add.</param>
/// <param name="right">The second color to add.</param>
/// <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>
@ -716,7 +729,7 @@ namespace math
/// </summary>
/// <param name="value">The color to assert (unchanged).</param>
/// <returns>The asserted (unchanged) color.</returns>
public static Color4 operator +(Color4 value)
public static Color4 operator +( Color4 value )
{
return value;
}
@ -727,9 +740,9 @@ namespace math
/// <param name="left">The first color to subtract.</param>
/// <param name="right">The second color to subtract.</param>
/// <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>
@ -737,9 +750,9 @@ namespace math
/// </summary>
/// <param name="value">The color to negate.</param>
/// <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>
@ -748,9 +761,9 @@ namespace math
/// <param name="scale">The factor by which to scale the color.</param>
/// <param name="value">The color to scale.</param>
/// <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>
@ -759,9 +772,9 @@ namespace math
/// <param name="value">The factor by which to scale the color.</param>
/// <param name="scale">The color to scale.</param>
/// <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>
@ -770,9 +783,9 @@ namespace math
/// <param name="left">The first color to modulate.</param>
/// <param name="right">The second color to modulate.</param>
/// <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>
@ -781,9 +794,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -792,9 +805,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -802,9 +815,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -812,9 +825,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -822,9 +835,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -832,9 +845,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -842,9 +855,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -852,9 +865,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -862,9 +875,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -874,7 +887,7 @@ namespace math
/// <returns>
/// The result of the conversion.
/// </returns>
public static explicit operator int(Color4 value)
public static explicit operator int( Color4 value )
{
return value.ToRgba();
}
@ -886,9 +899,9 @@ namespace math
/// <returns>
/// The result of the conversion.
/// </returns>
public static explicit operator Color4(int value)
public static explicit operator Color4( int value )
{
return new Color4(value);
return new Color4( value );
}
/// <summary>
@ -897,7 +910,7 @@ namespace math
/// <returns>An equivalent <see cref="Color3"/>, discarding the alpha channel.</returns>
public Color3 ToColor3()
{
return new Color3(R, G, B);
return new Color3( R, G, B );
}
/// <summary>
@ -908,7 +921,7 @@ namespace math
/// </returns>
public override string ToString()
{
return ToString(CultureInfo.CurrentCulture);
return ToString( CultureInfo.CurrentCulture );
}
/// <summary>
@ -918,9 +931,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
return ToString(format, CultureInfo.CurrentCulture);
return ToString( format, CultureInfo.CurrentCulture );
}
/// <summary>
@ -930,9 +943,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -943,23 +956,23 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
return ToString( formatProvider );
return string.Format(formatProvider, ToStringFormat,
A.ToString(format, formatProvider),
R.ToString(format, formatProvider),
G.ToString(format, formatProvider),
B.ToString(format, formatProvider));
return string.Format( formatProvider, ToStringFormat,
A.ToString( format, formatProvider ),
R.ToString( format, formatProvider ),
G.ToString( format, formatProvider ),
B.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -973,7 +986,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="Color4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Color4 other)
public bool Equals( Color4 other )
{
return A == other.A && R == other.R && G == other.G && B == other.B;
}
@ -985,15 +998,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (!ReferenceEquals(value.GetType(), typeof(Color4)))
if( !ReferenceEquals( value.GetType(), typeof( Color4 ) ) )
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>
/// <param name="stringColor">The string to convert.</param>
/// <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>
@ -26,36 +26,36 @@ namespace math
/// </summary>
/// <param name="stringColor">The string to convert.</param>
/// <returns>The converted RGBA value.</returns>
public static uint StringToRgba([CanBeNull] string stringColor)
public static uint StringToRgba( [CanBeNull] string stringColor )
{
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 & 0x00F) << 20)
| ((intValue & 0x0F0) << 4)
| ((intValue & 0x0F0) << 8)
| ((intValue & 0xF00) >> 4)
| ((intValue & 0xF00) >> 8)
| (0xFF000000);
intValue = ( ( intValue & 0x00F ) << 16 )
| ( ( intValue & 0x00F ) << 20 )
| ( ( intValue & 0x0F0 ) << 4 )
| ( ( intValue & 0x0F0 ) << 8 )
| ( ( intValue & 0xF00 ) >> 4 )
| ( ( intValue & 0xF00 ) >> 8 )
| ( 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 & 0x0000FF00)
| ((intValue & 0x00FF0000) >> 16)
| (0xFF000000);
intValue = ( ( intValue & 0x000000FF ) << 16 )
| ( intValue & 0x0000FF00 )
| ( ( intValue & 0x00FF0000 ) >> 16 )
| ( 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 & 0x0000FF00)
| ((intValue & 0x00FF0000) >> 16)
| (intValue & 0xFF000000);
intValue = ( ( intValue & 0x000000FF ) << 16 )
| ( intValue & 0x0000FF00 )
| ( ( intValue & 0x00FF0000 ) >> 16 )
| ( intValue & 0xFF000000 );
}
}
}
@ -68,11 +68,11 @@ namespace math
/// <param name="value">The RGB value to convert.</param>
/// <returns>The converted string.</returns>
[NotNull]
public static string RgbToString(int value)
public static string RgbToString( int value )
{
var r = (value & 0x000000FF);
var g = (value & 0x0000FF00) >> 8;
var b = (value & 0x00FF0000) >> 16;
var r = ( value & 0x000000FF );
var g = ( value & 0x0000FF00 ) >> 8;
var b = ( value & 0x00FF0000 ) >> 16;
return $"#{r:X2}{g:X2}{b:X2}";
}
@ -82,12 +82,12 @@ namespace math
/// <param name="value">The RGBA value to convert.</param>
/// <returns>The converted string.</returns>
[NotNull]
public static string RgbaToString(int value)
public static string RgbaToString( int value )
{
var r = (value & 0x000000FF);
var g = (value & 0x0000FF00) >> 8;
var b = (value & 0x00FF0000) >> 16;
var a = (value & 0xFF000000) >> 24;
var r = ( value & 0x000000FF );
var g = ( value & 0x0000FF00 ) >> 8;
var b = ( value & 0x00FF0000 ) >> 16;
var a = ( value & 0xFF000000 ) >> 24;
return $"#{a:X2}{r:X2}{g:X2}{b:X2}";
}
}

View File

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

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -33,4 +33,4 @@ namespace math
internal class DataMemberIgnoreAttribute : Attribute
{
}
}
}

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -50,4 +50,4 @@ namespace math
}
}
}
}

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>
/// <param name="cascadeIndex">The index of the rectangle</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>
/// Current width used by the packer.
@ -38,10 +38,10 @@ namespace math
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public void Clear(int width, int height)
public void Clear( int width, int height )
{
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;
Height = height;
@ -52,16 +52,16 @@ namespace math
/// </summary>
public virtual void Clear()
{
Clear(Width, Height);
Clear( Width, Height );
}
/// <summary>
/// Frees the specified old rectangle.
/// </summary>
/// <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>
@ -71,9 +71,9 @@ namespace math
/// <param name="height">Height requested</param>
/// <param name="bestRectangle">Fill with the rectangle if it was successfully inserted.</param>
/// <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>
@ -84,48 +84,48 @@ namespace math
/// <param name="count">The number of rectangle to fit.</param>
/// <param name="inserted">A callback called for each rectangle successfully fitted.</param>
/// <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();
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();
return false;
}
inserted(i, ref bestRectangle);
inserted( i, ref bestRectangle );
}
// if the insertion went well, use the new configuration
freeRectangles.Clear();
foreach (var tempFreeRectangle in tempFreeRectangles)
foreach( var tempFreeRectangle in tempFreeRectangles )
{
freeRectangles.Add(tempFreeRectangle);
freeRectangles.Add( tempFreeRectangle );
}
tempFreeRectangles.Clear();
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
int bestScore = int.MaxValue;
int freeRectangleIndex = -1;
// 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];
if (width == currentFreeRectangle.Width && height == currentFreeRectangle.Height)
if( width == currentFreeRectangle.Width && height == currentFreeRectangle.Height )
{
// Perfect fit
bestRectangle.X = currentFreeRectangle.X;
@ -135,12 +135,12 @@ namespace math
freeRectangleIndex = i;
break;
}
if (width <= currentFreeRectangle.Width && height <= currentFreeRectangle.Height)
if( width <= currentFreeRectangle.Width && height <= currentFreeRectangle.Height )
{
// Can fit inside
// Use "BAF" heuristic (best area fit)
var score = currentFreeRectangle.Width * currentFreeRectangle.Height - width * height;
if (score < bestScore)
if( score < bestScore )
{
bestRectangle.X = currentFreeRectangle.X;
bestRectangle.Y = currentFreeRectangle.Y;
@ -153,7 +153,7 @@ namespace math
}
// No space could be found
if (freeRectangleIndex == -1)
if( freeRectangleIndex == -1 )
return false;
var freeRectangle = freeRectanglesList[freeRectangleIndex];
@ -161,21 +161,21 @@ namespace math
// Choose an axis to split (trying to minimize the smaller area "MINAS")
int w = freeRectangle.Width - bestRectangle.Width;
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.
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 };
if (bottom.Width > 0 && bottom.Height > 0)
freeRectanglesList.Add(bottom);
if (right.Width > 0 && right.Height > 0)
freeRectanglesList.Add(right);
if( bottom.Width > 0 && bottom.Height > 0 )
freeRectanglesList.Add( bottom );
if( right.Width > 0 && right.Height > 0 )
freeRectanglesList.Add( right );
// Remove previously selected freeRectangle
if (freeRectangleIndex != freeRectanglesList.Count - 1)
if( freeRectangleIndex != freeRectanglesList.Count - 1 )
freeRectanglesList[freeRectangleIndex] = freeRectanglesList[freeRectanglesList.Count - 1];
freeRectanglesList.RemoveAt(freeRectanglesList.Count - 1);
freeRectanglesList.RemoveAt( freeRectanglesList.Count - 1 );
return true;
}

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -33,7 +33,7 @@ namespace math
/// A half precision (16 bit) floating point value.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)]
[StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half
{
private ushort value;
@ -107,9 +107,9 @@ namespace math
/// Initializes a new instance of the <see cref="Half"/> structure.
/// </summary>
/// <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>
@ -126,11 +126,11 @@ namespace math
/// </summary>
/// <param name = "values">The values to be converted.</param>
/// <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];
for (int i = 0; i < results.Length; i++)
results[i] = HalfUtils.Unpack(values[i].RawValue);
for( int i = 0; i < results.Length; i++ )
results[i] = HalfUtils.Unpack( values[i].RawValue );
return results;
}
@ -139,11 +139,11 @@ namespace math
/// </summary>
/// <param name = "values">The values to be converted.</param>
/// <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];
for (int i = 0; i < results.Length; i++)
results[i] = new Half(values[i]);
for( int i = 0; i < results.Length; i++ )
results[i] = new Half( values[i] );
return results;
}
@ -152,9 +152,9 @@ namespace math
/// </summary>
/// <param name = "value">The value to be converted.</param>
/// <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>
@ -162,9 +162,9 @@ namespace math
/// </summary>
/// <param name = "value">The value to be converted.</param>
/// <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>
@ -174,7 +174,7 @@ namespace math
/// <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>
public static bool operator ==(Half left, Half right)
public static bool operator ==( Half left, Half right )
{
return left.value == right.value;
}
@ -186,7 +186,7 @@ namespace math
/// <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>
public static bool operator !=(Half left, Half right)
public static bool operator !=( Half left, Half right )
{
return left.value != right.value;
}
@ -198,7 +198,7 @@ namespace math
public override string ToString()
{
float num = this;
return num.ToString(CultureInfo.CurrentCulture);
return num.ToString( CultureInfo.CurrentCulture );
}
/// <summary>
@ -208,7 +208,7 @@ namespace math
public override int GetHashCode()
{
ushort num = value;
return ((num * 3) / 2) ^ num;
return ( ( num * 3 ) / 2 ) ^ num;
}
/// <summary>
@ -217,9 +217,9 @@ namespace math
/// <param name = "value1">The first value.</param>
/// <param name = "value2">The second value.</param>
/// <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>
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;
}
@ -230,7 +230,7 @@ namespace math
/// <param name = "other">Object to make the comparison with.</param>
/// <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;
}
@ -241,13 +241,13 @@ namespace math
/// <param name = "obj">Object to make the comparison with.</param>
/// <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;
}
if (obj.GetType() != GetType())
if( obj.GetType() != GetType() )
{
return false;
}

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -32,7 +32,7 @@ namespace math
/// Represents a two dimensional mathematical vector with half-precision floats.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)]
[StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half2 : IEquatable<Half2>
{
/// <summary>
@ -52,7 +52,7 @@ namespace math
/// </summary>
/// <param name="x">The X 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.Y = y;
@ -62,7 +62,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half2"/> structure.
/// </summary>
/// <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.Y = value;
@ -73,7 +73,7 @@ namespace math
/// </summary>
/// <param name="x">The X 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.Y = (Half)y;
@ -83,7 +83,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half2"/> structure.
/// </summary>
/// <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.Y = (Half)value;
@ -96,9 +96,9 @@ namespace math
/// <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>
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>
@ -108,10 +108,10 @@ namespace math
/// <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>
[return: MarshalAs(UnmanagedType.U1)]
public static bool operator !=(Half2 left, Half2 right)
[return: MarshalAs( UnmanagedType.U1 )]
public static bool operator !=( Half2 left, Half2 right )
{
return !Equals(ref left, ref right);
return !Equals( ref left, ref right );
}
/// <summary>
@ -120,50 +120,50 @@ namespace math
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return (this.Y.GetHashCode() + this.X.GetHashCode());
return ( this.Y.GetHashCode() + this.X.GetHashCode() );
}
/// <summary>
/// Determines whether the specified object instances are considered equal.
/// Determines whether the specified object instances are considered equal.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <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>
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>
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// </summary>
/// <param name="other">Object to make the comparison with.</param>
/// <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>
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// </summary>
/// <param name="obj">Object to make the comparison with.</param>
/// <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;
}
if (obj.GetType() != GetType())
if( obj.GetType() != GetType() )
{
return false;
}
return this.Equals((Half2)obj);
return this.Equals( (Half2)obj );
}
/// <summary>
@ -171,9 +171,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -181,9 +181,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -32,7 +32,7 @@ namespace math
/// Represents a three dimensional mathematical vector with half-precision floats.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)]
[StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half3 : IEquatable<Half3>
{
/// <summary>
@ -59,7 +59,7 @@ namespace math
/// <param name="x">The X component.</param>
/// <param name="y">The Y 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.Y = y;
@ -70,7 +70,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half3"/> structure.
/// </summary>
/// <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.Y = value;
@ -83,7 +83,7 @@ namespace math
/// <param name="x">The X component.</param>
/// <param name="y">The Y 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.Y = (Half)y;
@ -94,7 +94,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half3"/> structure.
/// </summary>
/// <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.Y = (Half)value;
@ -108,9 +108,9 @@ namespace math
/// <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>
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>
@ -120,10 +120,10 @@ namespace math
/// <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>
[return: MarshalAs(UnmanagedType.U1)]
public static bool operator !=(Half3 left, Half3 right)
[return: MarshalAs( UnmanagedType.U1 )]
public static bool operator !=( Half3 left, Half3 right )
{
return !Equals(ref left, ref right);
return !Equals( ref left, ref right );
}
/// <summary>
@ -133,31 +133,31 @@ namespace math
public override int GetHashCode()
{
int num = this.Z.GetHashCode() + this.Y.GetHashCode();
return (this.X.GetHashCode() + num);
return ( this.X.GetHashCode() + num );
}
/// <summary>
/// Determines whether the specified object instances are considered equal.
/// Determines whether the specified object instances are considered equal.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <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>
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>
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// </summary>
/// <param name="other">Object to make the comparison with.</param>
/// <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>
@ -165,9 +165,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -175,28 +175,28 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// </summary>
/// <param name="obj">Object to make the comparison with.</param>
/// <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;
}
if (obj.GetType() != GetType())
if( obj.GetType() != GetType() )
{
return false;
}
return this.Equals((Half3)obj);
return this.Equals( (Half3)obj );
}
}
}

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -33,7 +33,7 @@ namespace math
/// Represents a four dimensional mathematical vector with half-precision floats.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 2)]
[StructLayout( LayoutKind.Sequential, Pack = 2 )]
public struct Half4 : IEquatable<Half4>
{
/// <summary>
@ -67,7 +67,7 @@ namespace math
/// <param name="y">The Y component.</param>
/// <param name="z">The Z 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.Y = y;
@ -79,7 +79,7 @@ namespace math
/// Initializes a new instance of the <see cref="Half4"/> structure.
/// </summary>
/// <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.Y = value;
@ -94,9 +94,9 @@ namespace math
/// <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>
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>
@ -106,9 +106,9 @@ namespace math
/// <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>
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>
@ -119,31 +119,31 @@ namespace math
{
int num2 = this.W.GetHashCode() + this.Z.GetHashCode();
int num = this.Y.GetHashCode() + num2;
return (this.X.GetHashCode() + num);
return ( this.X.GetHashCode() + num );
}
/// <summary>
/// Determines whether the specified object instances are considered equal.
/// Determines whether the specified object instances are considered equal.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <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>
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>
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// </summary>
/// <param name="other">Object to make the comparison with.</param>
/// <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>
@ -151,9 +151,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -161,28 +161,28 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// </summary>
/// <param name="obj">Object to make the comparison with.</param>
/// <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;
}
if (obj.GetType() != GetType())
if( obj.GetType() != GetType() )
{
return false;
}
return this.Equals((Half4)obj);
return this.Equals( (Half4)obj );
}
}
}

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -31,12 +31,12 @@ namespace math
/// </summary>
internal class HalfUtils
{
[StructLayout(LayoutKind.Explicit, Pack = 4)]
[StructLayout( LayoutKind.Explicit, Pack = 4 )]
private struct FloatToUint
{
[FieldOffset(0)]
[FieldOffset( 0 )]
public uint UIntValue;
[FieldOffset(0)]
[FieldOffset( 0 )]
public float FloatValue;
}
@ -45,10 +45,10 @@ namespace math
/// </summary>
/// <param name="h">The packed value.</param>
/// <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();
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;
}
@ -57,11 +57,11 @@ namespace math
/// </summary>
/// <param name="f">The float value.</param>
/// <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();
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];
@ -84,12 +84,12 @@ namespace math
HalfToFloatMantissaTable[0] = 0;
// 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;
while ((m & 0x00800000) == 0)
while( ( m & 0x00800000 ) == 0 )
{
e -= 0x00800000;
m <<= 1;
@ -100,20 +100,20 @@ namespace math
}
// Normal case
for (i = 1024; i < 2048; i++)
HalfToFloatMantissaTable[i] = 0x38000000 + (((uint)(i - 1024)) << 13);
for( i = 1024; i < 2048; i++ )
HalfToFloatMantissaTable[i] = 0x38000000 + ( ( (uint)( i - 1024 ) ) << 13 );
// Exponent table
// 0 => 0
HalfToFloatExponentTable[0] = 0;
for (i = 1; i < 63; i++)
for( i = 1; i < 63; i++ )
{
if (i < 31) // Positive Numbers
HalfToFloatExponentTable[i] = ((uint)i) << 23;
if( i < 31 ) // Positive Numbers
HalfToFloatExponentTable[i] = ( (uint)i ) << 23;
else // Negative Numbers
HalfToFloatExponentTable[i] = 0x80000000 + (((uint)(i - 32)) << 23);
HalfToFloatExponentTable[i] = 0x80000000 + ( ( (uint)( i - 32 ) ) << 23 );
}
HalfToFloatExponentTable[31] = 0x47800000;
HalfToFloatExponentTable[32] = 0x80000000;
@ -121,39 +121,39 @@ namespace math
// Offset table
HalfToFloatOffsetTable[0] = 0;
for (i = 1; i < 64; i++)
for( i = 1; i < 64; i++ )
HalfToFloatOffsetTable[i] = 1024;
HalfToFloatOffsetTable[32] = 0;
// -------------------------------------------------------------------
// Float to Half tables
// -------------------------------------------------------------------
for (i = 0; i < 256; i++)
for( i = 0; i < 256; i++ )
{
int e = i - 127;
if (e < -24)
if( e < -24 )
{ // Very small numbers map to zero
FloatToHalfBaseTable[i | 0x000] = 0x0000;
FloatToHalfBaseTable[i | 0x100] = 0x8000;
FloatToHalfShiftTable[i | 0x000] = 24;
FloatToHalfShiftTable[i | 0x100] = 24;
}
else if (e < -14)
else if( e < -14 )
{ // Small numbers map to denorms
FloatToHalfBaseTable[i | 0x000] = (ushort)((0x0400 >> (-e - 14)));
FloatToHalfBaseTable[i | 0x100] = (ushort)((0x0400 >> (-e - 14)) | 0x8000);
FloatToHalfShiftTable[i | 0x000] = (byte)(-e - 1);
FloatToHalfShiftTable[i | 0x100] = (byte)(-e - 1);
FloatToHalfBaseTable[i | 0x000] = (ushort)( ( 0x0400 >> ( -e - 14 ) ) );
FloatToHalfBaseTable[i | 0x100] = (ushort)( ( 0x0400 >> ( -e - 14 ) ) | 0x8000 );
FloatToHalfShiftTable[i | 0x000] = (byte)( -e - 1 );
FloatToHalfShiftTable[i | 0x100] = (byte)( -e - 1 );
}
else if (e <= 15)
else if( e <= 15 )
{ // Normal numbers just lose precision
FloatToHalfBaseTable[i | 0x000] = (ushort)(((e + 15) << 10));
FloatToHalfBaseTable[i | 0x100] = (ushort)(((e + 15) << 10) | 0x8000);
FloatToHalfBaseTable[i | 0x000] = (ushort)( ( ( e + 15 ) << 10 ) );
FloatToHalfBaseTable[i | 0x100] = (ushort)( ( ( e + 15 ) << 10 ) | 0x8000 );
FloatToHalfShiftTable[i | 0x000] = 13;
FloatToHalfShiftTable[i | 0x100] = 13;
}
else if (e < 128)
else if( e < 128 )
{ // Large numbers map to Infinity
FloatToHalfBaseTable[i | 0x000] = 0x7C00;
FloatToHalfBaseTable[i | 0x100] = 0xFC00;

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -36,9 +36,9 @@ namespace math
/// <summary>
/// Represents a three dimensional mathematical vector.
/// </summary>
[DataContract( Name = "Int2")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Int2" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int2 : IEquatable<Int2>, IFormattable
{
/// <summary>
@ -54,17 +54,17 @@ namespace math
/// <summary>
/// The X unit <see cref="math.Int2"/> (1, 0, 0).
/// </summary>
public static readonly Int2 UnitX = new Int2(1, 0);
public static readonly Int2 UnitX = new Int2( 1, 0 );
/// <summary>
/// The Y unit <see cref="math.Int2"/> (0, 1, 0).
/// </summary>
public static readonly Int2 UnitY = new Int2(0, 1);
public static readonly Int2 UnitY = new Int2( 0, 1 );
/// <summary>
/// A <see cref="math.Int2"/> with all of its components set to one.
/// </summary>
public static readonly Int2 One = new Int2(1, 1);
public static readonly Int2 One = new Int2( 1, 1 );
/// <summary>
/// The X component of the vector.
@ -82,7 +82,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Int2"/> struct.
/// </summary>
/// <param name="value">The value that will be assigned to all components.</param>
public Int2(int value)
public Int2( int value )
{
X = value;
Y = value;
@ -93,7 +93,7 @@ namespace math
/// </summary>
/// <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>
public Int2(int x, int y)
public Int2( int x, int y )
{
X = x;
Y = y;
@ -103,7 +103,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Int2"/> struct.
/// </summary>
/// <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;
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>
/// <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>
public Int2(int[] values)
public Int2( int[] values )
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length != 2)
throw new ArgumentOutOfRangeException("values", "There must be two and only two input values for Int2.");
if( values == null )
throw new ArgumentNullException( "values" );
if( values.Length != 2 )
throw new ArgumentOutOfRangeException( "values", "There must be two and only two input values for Int2." );
X = values[0];
Y = values[1];
@ -137,22 +137,29 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0: return X;
case 1: return Y;
case 0:
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
{
switch (index)
switch( index )
{
case 0: X = value; break;
case 1: Y = value; break;
default: throw new ArgumentOutOfRangeException("index", "Indices for Int2 run from 0 to 1, inclusive.");
case 0:
X = value;
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>
public int Length()
{
return (int)Math.Sqrt((X * X) + (Y * Y));
return (int)Math.Sqrt( ( X * X ) + ( Y * Y ) );
}
/// <summary>
@ -180,17 +187,17 @@ namespace math
/// </remarks>
public int LengthSquared()
{
return (X * X) + (Y * Y);
return ( X * X ) + ( Y * Y );
}
/// <summary>
/// Raises the exponent for each components.
/// </summary>
/// <param name="exponent">The exponent.</param>
public void Pow(int exponent)
public void Pow( int exponent )
{
X = (int)Math.Pow(X, exponent);
Y = (int)Math.Pow(Y, exponent);
X = (int)Math.Pow( X, exponent );
Y = (int)Math.Pow( Y, exponent );
}
/// <summary>
@ -208,9 +215,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -219,9 +226,9 @@ namespace math
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <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>
@ -230,9 +237,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -241,9 +248,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param>
/// <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>
@ -252,9 +259,9 @@ namespace math
/// <param name="value">The vector to scale.</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>
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>
@ -263,9 +270,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -274,9 +281,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -285,9 +292,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param>
/// <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>
@ -296,9 +303,9 @@ namespace math
/// <param name="value">The vector to scale.</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>
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>
@ -307,9 +314,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -317,9 +324,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</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>
@ -327,9 +334,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</param>
/// <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>
@ -339,17 +346,17 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum 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;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
x = ( x > max.X ) ? max.X : x;
x = ( x < min.X ) ? min.X : x;
int y = value.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
y = ( y > max.Y ) ? max.Y : y;
y = ( y < min.Y ) ? min.Y : y;
result = new Int2(x, y);
result = new Int2( x, y );
}
/// <summary>
@ -359,10 +366,10 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -372,9 +379,9 @@ namespace math
/// <param name="left">First 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>
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>
@ -383,9 +390,9 @@ namespace math
/// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param>
/// <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>
@ -398,12 +405,12 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
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.Y = (int)(start.Y + ((end.Y - start.Y) * amount));
result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
}
/// <summary>
@ -416,12 +423,12 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
public static Int2 Lerp(Int2 start, Int2 end, float amount)
public static Int2 Lerp( Int2 start, Int2 end, float amount )
{
Int2 result;
Lerp(ref start, ref end, amount, out result);
Lerp( ref start, ref end, amount, out result );
return result;
}
@ -432,13 +439,13 @@ namespace math
/// <param name="end">End vector.</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>
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 * amount) * (3 - (2 * amount));
amount = ( amount > 1 ) ? 1 : ( ( amount < 0 ) ? 0 : amount );
amount = ( amount * amount ) * ( 3 - ( 2 * amount ) );
result.X = (int)(start.X + ((end.X - start.X) * amount));
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount));
result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
}
/// <summary>
@ -448,10 +455,10 @@ namespace math
/// <param name="end">End vector.</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>
public static Int2 SmoothStep(Int2 start, Int2 end, float amount)
public static Int2 SmoothStep( Int2 start, Int2 end, float amount )
{
Int2 result;
SmoothStep(ref start, ref end, amount, out result);
SmoothStep( ref start, ref end, amount, out result );
return result;
}
@ -461,10 +468,10 @@ namespace math
/// <param name="left">The first 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>
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.Y = (left.Y > right.Y) ? left.Y : right.Y;
result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
}
/// <summary>
@ -473,10 +480,10 @@ namespace math
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -486,10 +493,10 @@ namespace math
/// <param name="left">The first 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>
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.Y = (left.Y < right.Y) ? left.Y : right.Y;
result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
}
/// <summary>
@ -498,10 +505,10 @@ namespace math
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
@ -511,9 +518,9 @@ namespace math
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <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>
@ -521,7 +528,7 @@ namespace math
/// </summary>
/// <param name="value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns>
public static Int2 operator +(Int2 value)
public static Int2 operator +( Int2 value )
{
return value;
}
@ -532,9 +539,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param>
/// <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>
@ -542,9 +549,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</param>
/// <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>
@ -553,9 +560,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -564,9 +571,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -575,9 +582,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -586,9 +593,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -597,9 +604,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -607,9 +614,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -617,9 +624,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -630,7 +637,7 @@ namespace math
/// </returns>
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>
@ -640,12 +647,12 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
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>
@ -655,9 +662,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -668,19 +675,19 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
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>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -694,10 +701,10 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="math.Int2"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Int2 other)
public bool Equals( Int2 other )
{
return ((float)Math.Abs(other.X - X) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Y - Y) < MathUtil.ZeroTolerance);
return ( (float)Math.Abs( other.X - X ) < MathUtil.ZeroTolerance &&
(float)Math.Abs( other.Y - Y ) < MathUtil.ZeroTolerance );
}
/// <summary>
@ -707,15 +714,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Int2)value);
return Equals( (Int2)value );
}
#if WPFInterop
/// <summary>

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -36,9 +36,9 @@ namespace math
/// <summary>
/// Represents a three dimensional mathematical vector.
/// </summary>
[DataContract( Name = "Int3")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Int3" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int3 : IEquatable<Int3>, IFormattable
{
/// <summary>
@ -54,22 +54,22 @@ namespace math
/// <summary>
/// The X unit <see cref="Int3"/> (1, 0, 0).
/// </summary>
public static readonly Int3 UnitX = new Int3(1, 0, 0);
public static readonly Int3 UnitX = new Int3( 1, 0, 0 );
/// <summary>
/// The Y unit <see cref="Int3"/> (0, 1, 0).
/// </summary>
public static readonly Int3 UnitY = new Int3(0, 1, 0);
public static readonly Int3 UnitY = new Int3( 0, 1, 0 );
/// <summary>
/// The Z unit <see cref="Int3"/> (0, 0, 1).
/// </summary>
public static readonly Int3 UnitZ = new Int3(0, 0, 1);
public static readonly Int3 UnitZ = new Int3( 0, 0, 1 );
/// <summary>
/// A <see cref="Int3"/> with all of its components set to one.
/// </summary>
public static readonly Int3 One = new Int3(1, 1, 1);
public static readonly Int3 One = new Int3( 1, 1, 1 );
/// <summary>
/// The X component of the vector.
@ -93,7 +93,7 @@ namespace math
/// Initializes a new instance of the <see cref="Int3"/> struct.
/// </summary>
/// <param name="value">The value that will be assigned to all components.</param>
public Int3(int value)
public Int3( int value )
{
X = value;
Y = value;
@ -106,7 +106,7 @@ namespace math
/// <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="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;
Y = y;
@ -118,7 +118,7 @@ namespace math
/// </summary>
/// <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>
public Int3(Vec2 value, int z)
public Int3( Vec2 value, int z )
{
X = (int)value.X;
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>
/// <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>
public Int3(int[] values)
public Int3( int[] values )
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length != 3)
throw new ArgumentOutOfRangeException("values", "There must be three and only three input values for Int3.");
if( values == null )
throw new ArgumentNullException( "values" );
if( values.Length != 3 )
throw new ArgumentOutOfRangeException( "values", "There must be three and only three input values for Int3." );
X = values[0];
Y = values[1];
@ -154,24 +154,34 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0: return X;
case 1: return Y;
case 2: return Z;
case 0:
return X;
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
{
switch (index)
switch( index )
{
case 0: X = value; break;
case 1: Y = value; break;
case 2: Z = value; break;
default: throw new ArgumentOutOfRangeException("index", "Indices for Int3 run from 0 to 2, inclusive.");
case 0:
X = value;
break;
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>
public int Length()
{
return (int)Math.Sqrt((X * X) + (Y * Y) + (Z * Z));
return (int)Math.Sqrt( ( X * X ) + ( Y * Y ) + ( Z * Z ) );
}
/// <summary>
@ -199,18 +209,18 @@ namespace math
/// </remarks>
public int LengthSquared()
{
return (X * X) + (Y * Y) + (Z * Z);
return ( X * X ) + ( Y * Y ) + ( Z * Z );
}
/// <summary>
/// Raises the exponent for each components.
/// </summary>
/// <param name="exponent">The exponent.</param>
public void Pow(int exponent)
public void Pow( int exponent )
{
X = (int)Math.Pow(X, exponent);
Y = (int)Math.Pow(Y, exponent);
Z = (int)Math.Pow(Z, exponent);
X = (int)Math.Pow( X, exponent );
Y = (int)Math.Pow( Y, exponent );
Z = (int)Math.Pow( Z, exponent );
}
/// <summary>
@ -228,9 +238,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -239,9 +249,9 @@ namespace math
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <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>
@ -250,9 +260,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -261,9 +271,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param>
/// <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>
@ -272,9 +282,9 @@ namespace math
/// <param name="value">The vector to scale.</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>
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>
@ -283,9 +293,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -294,9 +304,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -305,9 +315,9 @@ namespace math
/// <param name="left">The first vector to modulate.</param>
/// <param name="right">The second vector to modulate.</param>
/// <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>
@ -316,9 +326,9 @@ namespace math
/// <param name="value">The vector to scale.</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>
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>
@ -327,9 +337,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -337,9 +347,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</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>
@ -347,9 +357,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</param>
/// <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>
@ -359,21 +369,21 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum 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;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
x = ( x > max.X ) ? max.X : x;
x = ( x < min.X ) ? min.X : x;
int y = value.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
y = ( y > max.Y ) ? max.Y : y;
y = ( y < min.Y ) ? min.Y : y;
int z = value.Z;
z = (z > max.Z) ? max.Z : z;
z = (z < min.Z) ? min.Z : z;
z = ( z > max.Z ) ? max.Z : z;
z = ( z < min.Z ) ? min.Z : z;
result = new Int3(x, y, z);
result = new Int3( x, y, z );
}
/// <summary>
@ -383,10 +393,10 @@ namespace math
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -396,9 +406,9 @@ namespace math
/// <param name="left">First 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>
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>
@ -407,9 +417,9 @@ namespace math
/// <param name="left">First source vector.</param>
/// <param name="right">Second source vector.</param>
/// <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>
@ -422,13 +432,13 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
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.Y = (int)(start.Y + ((end.Y - start.Y) * amount));
result.Z = (int)(start.Z + ((end.Z - start.Z) * amount));
result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
result.Z = (int)( start.Z + ( ( end.Z - start.Z ) * amount ) );
}
/// <summary>
@ -441,12 +451,12 @@ namespace math
/// <remarks>
/// This method performs the linear interpolation based on the following formula.
/// <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>
public static Int3 Lerp(Int3 start, Int3 end, float amount)
public static Int3 Lerp( Int3 start, Int3 end, float amount )
{
Int3 result;
Lerp(ref start, ref end, amount, out result);
Lerp( ref start, ref end, amount, out result );
return result;
}
@ -457,14 +467,14 @@ namespace math
/// <param name="end">End vector.</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>
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 * amount) * (3 - (2 * amount));
amount = ( amount > 1 ) ? 1 : ( ( amount < 0 ) ? 0 : amount );
amount = ( amount * amount ) * ( 3 - ( 2 * amount ) );
result.X = (int)(start.X + ((end.X - start.X) * amount));
result.Y = (int)(start.Y + ((end.Y - start.Y) * amount));
result.Z = (int)(start.Z + ((end.Z - start.Z) * amount));
result.X = (int)( start.X + ( ( end.X - start.X ) * amount ) );
result.Y = (int)( start.Y + ( ( end.Y - start.Y ) * amount ) );
result.Z = (int)( start.Z + ( ( end.Z - start.Z ) * amount ) );
}
/// <summary>
@ -474,10 +484,10 @@ namespace math
/// <param name="end">End vector.</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>
public static Int3 SmoothStep(Int3 start, Int3 end, float amount)
public static Int3 SmoothStep( Int3 start, Int3 end, float amount )
{
Int3 result;
SmoothStep(ref start, ref end, amount, out result);
SmoothStep( ref start, ref end, amount, out result );
return result;
}
@ -487,11 +497,11 @@ namespace math
/// <param name="left">The first 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>
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.Y = (left.Y > right.Y) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z;
result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
}
/// <summary>
@ -500,10 +510,10 @@ namespace math
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -513,11 +523,11 @@ namespace math
/// <param name="left">The first 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>
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.Y = (left.Y < right.Y) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z;
result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
}
/// <summary>
@ -526,22 +536,22 @@ namespace math
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <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>
@ -549,7 +559,7 @@ namespace math
/// </summary>
/// <param name="value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns>
public static Int3 operator +(Int3 value)
public static Int3 operator +( Int3 value )
{
return value;
}
@ -560,9 +570,9 @@ namespace math
/// <param name="left">The first vector to subtract.</param>
/// <param name="right">The second vector to subtract.</param>
/// <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>
@ -570,9 +580,9 @@ namespace math
/// </summary>
/// <param name="value">The vector to negate.</param>
/// <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>
@ -581,9 +591,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -592,9 +602,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -603,9 +613,9 @@ namespace math
/// <param name="value">The vector to scale.</param>
/// <param name="scale">The amount by which to scale the vector.</param>
/// <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>
@ -614,9 +624,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -625,9 +635,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -635,9 +645,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -645,9 +655,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -655,9 +665,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -668,7 +678,7 @@ namespace math
/// </returns>
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>
@ -678,13 +688,13 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
return ToString();
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));
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 ) );
}
/// <summary>
@ -694,9 +704,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -707,20 +717,20 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
return ToString(formatProvider);
if( format == null )
return ToString( formatProvider );
return string.Format(formatProvider, "X:{0} Y:{1} Z:{2}", X.ToString(format, formatProvider),
Y.ToString(format, formatProvider), Z.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 ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -734,11 +744,11 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="Int3"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Int3 other)
public bool Equals( Int3 other )
{
return ((float)Math.Abs(other.X - X) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Y - Y) < MathUtil.ZeroTolerance &&
(float)Math.Abs(other.Z - Z) < MathUtil.ZeroTolerance);
return ( (float)Math.Abs( other.X - X ) < MathUtil.ZeroTolerance &&
(float)Math.Abs( other.Y - Y ) < MathUtil.ZeroTolerance &&
(float)Math.Abs( other.Z - Z ) < MathUtil.ZeroTolerance );
}
/// <summary>
@ -748,15 +758,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Int3)value);
return Equals( (Int3)value );
}
#if WPFInterop
/// <summary>

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -30,9 +30,9 @@ namespace math
/// <summary>
/// Represents a four dimensional mathematical vector.
/// </summary>
[DataContract( Name = "Int4")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Int4" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Int4 : IEquatable<Int4>, IFormattable
{
/// <summary>
@ -48,27 +48,27 @@ namespace math
/// <summary>
/// The X unit <see cref = "Int4" /> (1, 0, 0, 0).
/// </summary>
public static readonly Int4 UnitX = new Int4(1, 0, 0, 0);
public static readonly Int4 UnitX = new Int4( 1, 0, 0, 0 );
/// <summary>
/// The Y unit <see cref = "Int4" /> (0, 1, 0, 0).
/// </summary>
public static readonly Int4 UnitY = new Int4(0, 1, 0, 0);
public static readonly Int4 UnitY = new Int4( 0, 1, 0, 0 );
/// <summary>
/// The Z unit <see cref = "Int4" /> (0, 0, 1, 0).
/// </summary>
public static readonly Int4 UnitZ = new Int4(0, 0, 1, 0);
public static readonly Int4 UnitZ = new Int4( 0, 0, 1, 0 );
/// <summary>
/// The W unit <see cref = "Int4" /> (0, 0, 0, 1).
/// </summary>
public static readonly Int4 UnitW = new Int4(0, 0, 0, 1);
public static readonly Int4 UnitW = new Int4( 0, 0, 0, 1 );
/// <summary>
/// A <see cref = "Int4" /> with all of its components set to one.
/// </summary>
public static readonly Int4 One = new Int4(1, 1, 1, 1);
public static readonly Int4 One = new Int4( 1, 1, 1, 1 );
/// <summary>
/// The X component of the vector.
@ -98,7 +98,7 @@ namespace math
/// Initializes a new instance of the <see cref = "Int4" /> struct.
/// </summary>
/// <param name = "value">The value that will be assigned to all components.</param>
public Int4(int value)
public Int4( int value )
{
X = value;
Y = value;
@ -113,7 +113,7 @@ namespace math
/// <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 = "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;
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>
/// <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>
public Int4(int[] values)
public Int4( int[] values )
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length != 4)
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for Int4.");
if( values == null )
throw new ArgumentNullException( "values" );
if( values.Length != 4 )
throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for Int4." );
X = values[0];
Y = values[1];
@ -151,7 +151,7 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0:
return X;
@ -163,12 +163,12 @@ namespace math
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
{
switch (index)
switch( index )
{
case 0:
X = value;
@ -183,7 +183,7 @@ namespace math
W = value;
break;
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>
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>
@ -211,7 +211,7 @@ namespace math
/// </remarks>
public int LengthSquared()
{
return (X * X) + (Y * Y) + (Z * Z) + (W * W);
return ( X * X ) + ( Y * Y ) + ( Z * Z ) + ( W * W );
}
/// <summary>
@ -229,9 +229,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -240,9 +240,9 @@ namespace math
/// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param>
/// <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>
@ -251,9 +251,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -262,9 +262,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param>
/// <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>
@ -273,9 +273,9 @@ namespace math
/// <param name = "value">The vector to scale.</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>
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>
@ -284,9 +284,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -295,9 +295,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -306,9 +306,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param>
/// <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>
@ -317,9 +317,9 @@ namespace math
/// <param name = "value">The vector to scale.</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>
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>
@ -328,9 +328,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -338,9 +338,9 @@ namespace math
/// </summary>
/// <param name = "value">The vector to negate.</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>
@ -348,9 +348,9 @@ namespace math
/// </summary>
/// <param name = "value">The vector to negate.</param>
/// <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>
@ -360,25 +360,25 @@ namespace math
/// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum 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;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
x = ( x > max.X ) ? max.X : x;
x = ( x < min.X ) ? min.X : x;
int y = value.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
y = ( y > max.Y ) ? max.Y : y;
y = ( y < min.Y ) ? min.Y : y;
int z = value.Z;
z = (z > max.Z) ? max.Z : z;
z = (z < min.Z) ? min.Z : z;
z = ( z > max.Z ) ? max.Z : z;
z = ( z < min.Z ) ? min.Z : z;
int w = value.W;
w = (w > max.W) ? max.W : w;
w = (w < min.W) ? min.W : w;
w = ( w > max.W ) ? max.W : w;
w = ( w < min.W ) ? min.W : w;
result = new Int4(x, y, z, w);
result = new Int4( x, y, z, w );
}
/// <summary>
@ -388,10 +388,10 @@ namespace math
/// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -401,12 +401,12 @@ namespace math
/// <param name = "left">The first 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>
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.Y = (left.Y > right.Y) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z;
result.W = (left.W > right.W) ? left.W : right.W;
result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
result.W = ( left.W > right.W ) ? left.W : right.W;
}
/// <summary>
@ -415,10 +415,10 @@ namespace math
/// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -428,12 +428,12 @@ namespace math
/// <param name = "left">The first 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>
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.Y = (left.Y < right.Y) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z;
result.W = (left.W < right.W) ? left.W : right.W;
result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
result.W = ( left.W < right.W ) ? left.W : right.W;
}
/// <summary>
@ -442,10 +442,10 @@ namespace math
/// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
@ -455,9 +455,9 @@ namespace math
/// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param>
/// <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>
@ -465,7 +465,7 @@ namespace math
/// </summary>
/// <param name = "value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns>
public static Int4 operator +(Int4 value)
public static Int4 operator +( Int4 value )
{
return value;
}
@ -476,9 +476,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param>
/// <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>
@ -486,9 +486,9 @@ namespace math
/// </summary>
/// <param name = "value">The vector to negate.</param>
/// <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>
@ -497,9 +497,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -508,9 +508,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -519,9 +519,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -530,9 +530,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -541,9 +541,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -551,9 +551,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -561,9 +561,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -571,9 +571,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -584,7 +584,7 @@ namespace math
/// </returns>
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>
@ -594,16 +594,16 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString(format, CultureInfo.CurrentCulture),
Y.ToString(format, CultureInfo.CurrentCulture),
Z.ToString(format, CultureInfo.CurrentCulture),
W.ToString(format, CultureInfo.CurrentCulture));
return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString( format, CultureInfo.CurrentCulture ),
Y.ToString( format, CultureInfo.CurrentCulture ),
Z.ToString( format, CultureInfo.CurrentCulture ),
W.ToString( format, CultureInfo.CurrentCulture ) );
}
/// <summary>
@ -613,9 +613,9 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </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>
@ -626,21 +626,21 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
ToString(formatProvider);
if( format == null )
ToString( 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),
W.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 ),
W.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -654,7 +654,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref = "Int4" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Int4 other)
public bool Equals( Int4 other )
{
return other.X == X && other.Y == Y && other.Z == Z && other.W == W;
}
@ -666,15 +666,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Int4)value);
return Equals( (Int4)value );
}
/// <summary>
@ -682,9 +682,9 @@ namespace math
/// </summary>
/// <param name="input">The input.</param>
/// <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>
@ -692,7 +692,7 @@ namespace math
/// </summary>
/// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator int[](Int4 input)
public static implicit operator int[]( Int4 input )
{
return input.ToArray();
}

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -56,17 +56,17 @@ namespace math
/// <summary>
/// A value specifying the approximation of 2π which is 360 degrees.
/// </summary>
public const float TwoPi = (float)(2 * Math.PI);
public const float TwoPi = (float)( 2 * Math.PI );
/// <summary>
/// A value specifying the approximation of π/2 which is 90 degrees.
/// </summary>
public const float PiOverTwo = (float)(Math.PI / 2);
public const float PiOverTwo = (float)( Math.PI / 2 );
/// <summary>
/// A value specifying the approximation of π/4 which is 45 degrees.
/// </summary>
public const float PiOverFour = (float)(Math.PI / 4);
public const float PiOverFour = (float)( Math.PI / 4 );
/// <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.
@ -76,14 +76,14 @@ namespace math
/// <param name="b">The right value to compare.</param>
/// <returns><c>true</c> if a almost equal to b, <c>false</c> otherwise</returns>
/// <remarks>
/// 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>.
/// 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>.
/// </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
// when comparing numbers near zero.
if (IsZero(a - b))
if( IsZero( a - b ) )
return true;
// 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;
// Different signs means they do not match.
if ((aInt < 0) != (bInt < 0))
if( ( aInt < 0 ) != ( bInt < 0 ) )
return false;
// Find the difference in ULPs.
int ulp = Math.Abs(aInt - bInt);
int ulp = Math.Abs( aInt - bInt );
// Choose of maxUlp = 4
// according to http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h
const int maxUlp = 4;
return (ulp <= maxUlp);
return ( ulp <= maxUlp );
}
/// <summary>
@ -108,9 +108,9 @@ namespace math
/// </summary>
/// <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>
public static bool IsZero(float a)
public static bool IsZero( float a )
{
return Math.Abs(a) < ZeroTolerance;
return Math.Abs( a ) < ZeroTolerance;
}
/// <summary>
@ -118,9 +118,9 @@ namespace math
/// </summary>
/// <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>
public static bool IsZero(double a)
public static bool IsZero( double a )
{
return Math.Abs(a) < ZeroToleranceDouble;
return Math.Abs( a ) < ZeroToleranceDouble;
}
/// <summary>
@ -128,9 +128,9 @@ namespace math
/// </summary>
/// <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>
public static bool IsOne(float a)
public static bool IsOne( float a )
{
return IsZero(a - 1.0f);
return IsZero( a - 1.0f );
}
/// <summary>
@ -140,10 +140,10 @@ namespace math
/// <param name="b">The right value to compare.</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>
public static bool WithinEpsilon(float a, float b, float epsilon)
public static bool WithinEpsilon( float a, float b, float epsilon )
{
float num = a - b;
return ((-epsilon <= num) && (num <= epsilon));
return ( ( -epsilon <= num ) && ( num <= epsilon ) );
}
/// <summary>
@ -153,10 +153,10 @@ namespace math
/// <param name="value">The value to fill the array with.</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>
public static T[] Array<T>(T value, int length)
public static T[] Array<T>( T value, int length )
{
var result = new T[length];
for (var i = 0; i < length; i++)
for( var i = 0; i < length; i++ )
result[i] = value;
return result;
@ -167,7 +167,7 @@ namespace math
/// </summary>
/// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float RevolutionsToDegrees(float revolution)
public static float RevolutionsToDegrees( float revolution )
{
return revolution * 360.0f;
}
@ -177,7 +177,7 @@ namespace math
/// </summary>
/// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float RevolutionsToRadians(float revolution)
public static float RevolutionsToRadians( float revolution )
{
return revolution * TwoPi;
}
@ -187,7 +187,7 @@ namespace math
/// </summary>
/// <param name="revolution">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float RevolutionsToGradians(float revolution)
public static float RevolutionsToGradians( float revolution )
{
return revolution * 400.0f;
}
@ -197,7 +197,7 @@ namespace math
/// </summary>
/// <param name="degree">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float DegreesToRevolutions(float degree)
public static float DegreesToRevolutions( float degree )
{
return degree / 360.0f;
}
@ -207,9 +207,9 @@ namespace math
/// </summary>
/// <param name="degree">The value to convert.</param>
/// <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>
@ -217,7 +217,7 @@ namespace math
/// </summary>
/// <param name="radian">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float RadiansToRevolutions(float radian)
public static float RadiansToRevolutions( float radian )
{
return radian / TwoPi;
}
@ -227,9 +227,9 @@ namespace math
/// </summary>
/// <param name="radian">The value to convert.</param>
/// <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>
@ -237,7 +237,7 @@ namespace math
/// </summary>
/// <param name="gradian">The value to convert.</param>
/// <returns>The converted value.</returns>
public static float GradiansToRevolutions(float gradian)
public static float GradiansToRevolutions( float gradian )
{
return gradian / 400.0f;
}
@ -247,9 +247,9 @@ namespace math
/// </summary>
/// <param name="gradian">The value to convert.</param>
/// <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>
@ -257,9 +257,9 @@ namespace math
/// </summary>
/// <param name="gradian">The value to convert.</param>
/// <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>
@ -267,9 +267,9 @@ namespace math
/// </summary>
/// <param name="radian">The value to convert.</param>
/// <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>
@ -279,7 +279,7 @@ namespace math
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <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;
}
@ -291,7 +291,7 @@ namespace math
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <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;
}
@ -303,7 +303,7 @@ namespace math
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <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;
}
@ -315,11 +315,11 @@ namespace math
/// <param name="max">Maximum value that takes place in inverse-interpolation.</param>
/// <param name="value">Value to get inverse interpolation.</param>
/// <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 (value - min) / (max - min);
return ( value - min ) / ( max - min );
}
/// <summary>
@ -329,11 +329,11 @@ namespace math
/// <param name="max">Maximum value that takes place in inverse-interpolation.</param>
/// <param name="value">Value to get inverse interpolation.</param>
/// <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 (value - min) / (max - min);
return ( value - min ) / ( max - min );
}
/// <summary>
@ -347,9 +347,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param>
/// <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>
@ -363,9 +363,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param>
/// <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>
@ -379,9 +379,9 @@ namespace math
/// <param name="to">Value to interpolate to.</param>
/// <param name="amount">Interpolation amount.</param>
/// <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>
@ -391,11 +391,11 @@ namespace math
/// See https://en.wikipedia.org/wiki/Smoothstep
/// </remarks>
/// <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
: (amount >= 1) ? 1
: amount * amount * (3 - (2 * amount));
return ( amount <= 0 ) ? 0
: ( amount >= 1 ) ? 1
: amount * amount * ( 3 - ( 2 * amount ) );
}
/// <summary>
@ -405,11 +405,11 @@ namespace math
/// See https://en.wikipedia.org/wiki/Smoothstep
/// </remarks>
/// <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
: (amount >= 1) ? 1
: amount * amount * amount * (amount * ((amount * 6) - 15) + 10);
return ( amount <= 0 ) ? 0
: ( amount >= 1 ) ? 1
: amount * amount * amount * ( amount * ( ( amount * 6 ) - 15 ) + 10 );
}
/// <summary>
@ -419,7 +419,7 @@ namespace math
/// <param name="min">The minimum 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>
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;
}
@ -431,7 +431,7 @@ namespace math
/// <param name="min">The minimum 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>
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;
}
@ -441,9 +441,9 @@ namespace math
/// </summary>
/// <param name="x">The x.</param>
/// <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>
@ -451,10 +451,11 @@ namespace math
/// </summary>
/// <param name="sRgbValue">The sRGB value.</param>
/// <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;
return (float)Math.Pow((sRgbValue + 0.055) / 1.055, 2.4);
if( sRgbValue < 0.04045f )
return sRgbValue / 12.92f;
return (float)Math.Pow( ( sRgbValue + 0.055 ) / 1.055, 2.4 );
}
/// <summary>
@ -462,10 +463,11 @@ namespace math
/// </summary>
/// <param name="linearValue">The linear value.</param>
/// <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;
return (float)(1.055 * Math.Pow(linearValue, 1 / 2.4) - 0.055);
if( linearValue < 0.0031308f )
return linearValue * 12.92f;
return (float)( 1.055 * Math.Pow( linearValue, 1 / 2.4 ) - 0.055 );
}
/// <summary>
@ -473,9 +475,9 @@ namespace math
/// </summary>
/// <param name="x">The input float</param>
/// <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>
@ -483,11 +485,11 @@ namespace math
/// </summary>
/// <param name="i">The input integer</param>
/// <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;
while ((i >>= 1) != 0)
while( ( i >>= 1 ) != 0 )
++r;
return r;
@ -499,9 +501,9 @@ namespace math
/// <param name="x">The size.</param>
/// <returns>System.Int32.</returns>
/// <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;
x--;
@ -518,27 +520,27 @@ namespace math
/// </summary>
/// <param name="size">The size.</param>
/// <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>
/// Get the previous power of two of the provided integer.
/// </summary>
/// <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>
/// Get the previous power of two of the provided float.
/// </summary>
/// <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>
@ -547,11 +549,11 @@ namespace math
/// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param>
/// <returns>Aligned value (multiple of alignment).</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int AlignUp(int value, int alignment)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int AlignUp( int value, int alignment )
{
int mask = alignment - 1;
return (value + mask) & ~mask;
return ( value + mask ) & ~mask;
}
/// <summary>
@ -560,8 +562,8 @@ namespace math
/// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param>
/// <returns>Aligned value (multiple of alignment).</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int AlignDown(int value, int alignment)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int AlignDown( int value, int alignment )
{
int mask = alignment - 1;
return value & ~mask;
@ -573,10 +575,10 @@ namespace math
/// <param name="value">The value.</param>
/// <param name="alignment">The alignment.</param>
/// <returns><c>true</c> if the specified value is aligned; otherwise, <c>false</c>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsAligned(int value, int alignment)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool IsAligned( int value, int alignment )
{
return (value & (alignment - 1)) == 0;
return ( value & ( alignment - 1 ) ) == 0;
}
/// <summary>
@ -585,11 +587,11 @@ namespace math
/// <param name="value">The value to snap.</param>
/// <param name="gap">The interval gap.</param>
/// <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 (float)Math.Round((value / gap), MidpointRounding.AwayFromZero) * gap;
return (float)Math.Round( ( value / gap ), MidpointRounding.AwayFromZero ) * gap;
}
/// <summary>
@ -598,11 +600,11 @@ namespace math
/// <param name="value">The value to snap.</param>
/// <param name="gap">The interval gap.</param>
/// <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 Math.Round((value / gap), MidpointRounding.AwayFromZero) * gap;
return Math.Round( ( value / gap ), MidpointRounding.AwayFromZero ) * gap;
}
/// <summary>
@ -611,13 +613,13 @@ namespace math
/// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param>
/// <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 new Vec2(
(float)Math.Round((value.X / gap), MidpointRounding.AwayFromZero) * gap,
(float)Math.Round((value.Y / gap), MidpointRounding.AwayFromZero) * gap);
(float)Math.Round( ( value.X / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round( ( value.Y / gap ), MidpointRounding.AwayFromZero ) * gap );
}
/// <summary>
@ -626,14 +628,14 @@ namespace math
/// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param>
/// <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 new Vec3(
(float)Math.Round((value.X / 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.X / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round( ( value.Y / gap ), MidpointRounding.AwayFromZero ) * gap,
(float)Math.Round( ( value.Z / gap ), MidpointRounding.AwayFromZero ) * gap );
}
/// <summary>
@ -642,15 +644,15 @@ namespace math
/// <param name="value">The vector to snap.</param>
/// <param name="gap">The interval gap.</param>
/// <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 new Vec4(
(float)Math.Round((value.X / 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.W / 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.Z / 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

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -37,7 +37,7 @@ namespace math
/// Represents a plane in three dimensional space.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Plane : IEquatable<Plane>, IFormattable
{
/// <summary>
@ -54,7 +54,7 @@ namespace math
/// Initializes a new instance of the <see cref="math.Plane"/> struct.
/// </summary>
/// <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;
}
@ -66,7 +66,7 @@ namespace math
/// <param name="b">The Y 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>
public Plane(float a, float b, float c, float d)
public Plane( float a, float b, float c, float d )
{
Normal.X = a;
Normal.Y = b;
@ -79,10 +79,10 @@ namespace math
/// </summary>
/// <param name="point">Any point that lies along 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.D = Vec3.Dot(normal, point);
this.D = Vec3.Dot( normal, point );
}
/// <summary>
@ -90,7 +90,7 @@ namespace math
/// </summary>
/// <param name="value">The normal of the plane.</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;
D = d;
@ -102,7 +102,7 @@ namespace math
/// <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="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 y1 = point2.Y - point1.Y;
@ -110,15 +110,15 @@ namespace math
float x2 = point3.X - point1.X;
float y2 = point3.Y - point1.Y;
float z2 = point3.Z - point1.Z;
float yz = (y1 * z2) - (z1 * y2);
float xz = (z1 * x2) - (x1 * z2);
float xy = (x1 * y2) - (y1 * x2);
float invPyth = 1.0f / (float)(Math.Sqrt((yz * yz) + (xz * xz) + (xy * xy)));
float yz = ( y1 * z2 ) - ( z1 * y2 );
float xz = ( z1 * x2 ) - ( x1 * z2 );
float xy = ( x1 * y2 ) - ( y1 * x2 );
float invPyth = 1.0f / (float)( Math.Sqrt( ( yz * yz ) + ( xz * xz ) + ( xy * xy ) ) );
Normal.X = yz * invPyth;
Normal.Y = xz * 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>
@ -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>
/// <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>
public Plane(float[] values)
public Plane( float[] values )
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length != 4)
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for Plane.");
if( values == null )
throw new ArgumentNullException( "values" );
if( values.Length != 4 )
throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for Plane." );
Normal.X = values[0];
Normal.Y = values[1];
@ -151,26 +151,39 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0: return Normal.X;
case 1: return Normal.Y;
case 2: return Normal.Z;
case 3: return D;
case 0:
return Normal.X;
case 1:
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
{
switch (index)
switch( index )
{
case 0: Normal.X = value; break;
case 1: 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.");
case 0:
Normal.X = value;
break;
case 1:
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>
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.Y *= magnitude;
@ -213,9 +226,9 @@ namespace math
/// </summary>
/// <param name="point">The point to test.</param>
/// <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>
@ -223,10 +236,10 @@ namespace math
/// </summary>
/// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray)
public bool Intersects( ref Ray ray )
{
float distance;
return CollisionHelper.RayIntersectsPlane(ref ray, ref this, out distance);
return CollisionHelper.RayIntersectsPlane( ref ray, ref this, out distance );
}
/// <summary>
@ -236,9 +249,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -248,9 +261,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -258,9 +271,9 @@ namespace math
/// </summary>
/// <param name="plane">The plane to test.</param>
/// <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>
@ -270,9 +283,9 @@ namespace math
/// <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>
/// <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>
@ -282,9 +295,9 @@ namespace math
/// <param name="vertex2">The second vertex of the triagnle to test.</param>
/// <param name="vertex3">The third vertex of the triangle to test.</param>
/// <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>
@ -292,9 +305,9 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <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>
@ -302,9 +315,9 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <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>
@ -313,7 +326,7 @@ namespace math
/// <param name="value">The plane to scale.</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>
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.Y = value.Normal.Y * scale;
@ -327,9 +340,9 @@ namespace math
/// <param name="value">The plane to scale.</param>
/// <param name="scale">The amount by which to scale the plane.</param>
/// <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>
@ -338,9 +351,9 @@ namespace math
/// <param name="left">The source plane.</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>
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>
@ -349,9 +362,9 @@ namespace math
/// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param>
/// <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>
@ -360,9 +373,9 @@ namespace math
/// <param name="left">The source plane.</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>
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>
@ -371,9 +384,9 @@ namespace math
/// <param name="left">The source plane.</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>
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>
@ -382,9 +395,9 @@ namespace math
/// <param name="left">The source plane.</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>
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>
@ -393,9 +406,9 @@ namespace math
/// <param name="left">The source plane.</param>
/// <param name="right">The source vector.</param>
/// <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>
@ -404,14 +417,14 @@ namespace math
/// <param name="plane">The plane to project the point to.</param>
/// <param name="point">The point to project.</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;
DotCoordinate(ref plane, ref point, out distance);
DotCoordinate( ref plane, ref point, out distance );
// compute: point - distance * plane.Normal
Vec3.Multiply(ref plane.Normal, distance, out result);
Vec3.Subtract(ref point, ref result, out result);
Vec3.Multiply( ref plane.Normal, distance, out result );
Vec3.Subtract( ref point, ref result, out result );
}
/// <summary>
@ -420,10 +433,10 @@ namespace math
/// <param name="plane">The plane to project the point to.</param>
/// <param name="point">The point to project.</param>
/// <returns>The projected point.</returns>
public static Vec3 Project(Plane plane, Vec3 point)
public static Vec3 Project( Plane plane, Vec3 point )
{
Vec3 result;
Project(ref plane, ref point, out result);
Project( ref plane, ref point, out result );
return result;
}
@ -432,9 +445,9 @@ namespace math
/// </summary>
/// <param name="plane">The source 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.Y = plane.Normal.Y * magnitude;
@ -447,10 +460,10 @@ namespace math
/// </summary>
/// <param name="plane">The source plane.</param>
/// <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)));
return new Plane(plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude);
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 );
}
/// <summary>
@ -458,7 +471,7 @@ namespace math
/// </summary>
/// <param name="plane">The source 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.Y = -plane.Normal.Y;
@ -471,10 +484,10 @@ namespace math
/// </summary>
/// <param name="plane">The source plane.</param>
/// <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)));
return new Plane(plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude);
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 );
}
/// <summary>
@ -483,7 +496,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param>
/// <param name="rotation">The quaternion rotation.</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 y2 = rotation.Y + rotation.Y;
@ -502,9 +515,9 @@ namespace math
float y = plane.Normal.Y;
float z = plane.Normal.Z;
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.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy));
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.Z = ( ( x * ( xz - wy ) ) + ( y * ( yz + wx ) ) ) + ( z * ( ( 1.0f - xx ) - yy ) );
result.D = plane.D;
}
@ -514,7 +527,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param>
/// <param name="rotation">The quaternion rotation.</param>
/// <returns>The transformed plane.</returns>
public static Plane Transform(Plane plane, Quaternion rotation)
public static Plane Transform( Plane plane, Quaternion rotation )
{
Plane result;
float x2 = rotation.X + rotation.X;
@ -534,9 +547,9 @@ namespace math
float y = plane.Normal.Y;
float z = plane.Normal.Z;
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.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy));
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.Z = ( ( x * ( xz - wy ) ) + ( y * ( yz + wx ) ) ) + ( z * ( ( 1.0f - xx ) - yy ) );
result.D = plane.D;
return result;
@ -548,10 +561,10 @@ namespace math
/// <param name="planes">The array of normalized planes to transform.</param>
/// <param name="rotation">The quaternion rotation.</param>
/// <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)
throw new ArgumentNullException("planes");
if( planes == null )
throw new ArgumentNullException( "planes" );
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
@ -566,7 +579,7 @@ namespace math
float yz = rotation.Y * 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 y = planes[i].Normal.Y;
@ -576,9 +589,9 @@ namespace math
* Note:
* Factor common arithmetic out of loop.
*/
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.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy));
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.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="transformation">The transformation matrix.</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 y = plane.Normal.Y;
@ -596,12 +609,12 @@ namespace math
float d = plane.D;
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.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.D = (((x * inverse.M41) + (y * inverse.M42)) + (z * inverse.M43)) + (d * inverse.M44);
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.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 );
}
/// <summary>
@ -610,7 +623,7 @@ namespace math
/// <param name="plane">The normalized source plane.</param>
/// <param name="transformation">The transformation matrix.</param>
/// <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;
float x = plane.Normal.X;
@ -619,10 +632,10 @@ namespace math
float d = plane.D;
transformation.Invert();
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.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.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.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 );
return result;
}
@ -633,17 +646,17 @@ namespace math
/// <param name="planes">The array of normalized planes to transform.</param>
/// <param name="transformation">The transformation matrix.</param>
/// <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)
throw new ArgumentNullException("planes");
if( planes == null )
throw new ArgumentNullException( "planes" );
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="plane">The plane to scale.</param>
/// <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>
@ -664,18 +677,18 @@ namespace math
/// <param name="plane">The plane to scale.</param>
/// <param name="scale">The amount by which to scale the plane.</param>
/// <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>
/// Negates a plane by negating all its coefficients, which result in a plane in opposite direction.
/// </summary>
/// <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>
@ -684,9 +697,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -695,9 +708,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -708,7 +721,7 @@ namespace math
/// </returns>
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>
@ -718,10 +731,10 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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),
Normal.Y.ToString(format, CultureInfo.CurrentCulture), Normal.Z.ToString(format, CultureInfo.CurrentCulture), D.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 ) );
}
/// <summary>
@ -731,9 +744,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -744,17 +757,17 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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),
Normal.Y.ToString(format, formatProvider), Normal.Z.ToString(format, formatProvider), D.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 ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -768,7 +781,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Plane value)
public bool Equals( Plane value )
{
return Normal == value.Normal && D == value.D;
}
@ -780,15 +793,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Plane)value);
return Equals( (Plane)value );
}
#if SlimDX1xInterop

View File

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@ -32,20 +32,20 @@ namespace math
/// A 2D point.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Point : IEquatable<Point>
{
/// <summary>
/// A point with (0,0) coordinates.
/// </summary>
public static readonly Point Zero = new Point(0, 0);
public static readonly Point Zero = new Point( 0, 0 );
/// <summary>
/// Initializes a new instance of the <see cref="Point"/> struct.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public Point(int x, int y)
public Point( int x, int y )
{
X = x;
Y = y;
@ -70,17 +70,19 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Point other)
public bool Equals( Point other )
{
return other.X == X && other.Y == Y;
}
/// <inheritdoc/>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Point)) return false;
return Equals((Point)obj);
if( ReferenceEquals( null, obj ) )
return false;
if( obj.GetType() != typeof( Point ) )
return false;
return Equals( (Point)obj );
}
/// <inheritdoc/>
@ -88,7 +90,7 @@ namespace math
{
unchecked
{
return (X * 397) ^ Y;
return ( X * 397 ) ^ Y;
}
}
@ -100,9 +102,9 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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>
@ -113,15 +115,15 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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/>
public override string ToString()
{
return string.Format("({0},{1})", X, Y);
return string.Format( "({0},{1})", X, Y );
}
/// <summary>
@ -129,9 +131,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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>
@ -139,9 +141,9 @@ namespace math
/// </summary>
/// <param name="value">The value.</param>
/// <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.
/// </summary>
/// <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>
/// Get a deterministic double value between 0 and 1 based on the seed
/// </summary>
/// <returns>Deterministic pseudo-random value between 0 and 1</returns>
public double GetDouble(uint offset)
{
var dRand = (double)(unchecked(seed + offset)); // We want it to overflow
public double GetDouble( uint offset )
{
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 remainder = Numerator % denominator;
return (remainder - Math.Floor(remainder));
return ( remainder - Math.Floor( remainder ) );
}
/// <summary>
@ -56,6 +56,6 @@ namespace math
/// The calculations are still made as doubles to prevent underflow errors.
/// </summary>
/// <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

@ -7,17 +7,17 @@
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -37,7 +37,7 @@ namespace math
/// Represents a three dimensional line based on a point in space and a direction.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Ray : IEquatable<Ray>, IFormattable
{
/// <summary>
@ -55,7 +55,7 @@ namespace math
/// </summary>
/// <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>
public Ray(Vec3 position, Vec3 direction)
public Ray( Vec3 position, Vec3 direction )
{
this.Position = position;
this.Direction = direction;
@ -66,9 +66,9 @@ namespace math
/// </summary>
/// <param name="point">The point to test.</param>
/// <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>
@ -76,10 +76,10 @@ namespace math
/// </summary>
/// <param name="ray">The ray to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Ray ray)
public bool Intersects( ref Ray ray )
{
Vec3 point;
return CollisionHelper.RayIntersectsRay(ref this, ref ray, out point);
return CollisionHelper.RayIntersectsRay( ref this, ref ray, out point );
}
/// <summary>
@ -89,9 +89,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -99,10 +99,10 @@ namespace math
/// </summary>
/// <param name="plane">The plane to test</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref Plane plane)
public bool Intersects( ref Plane plane )
{
float distance;
return CollisionHelper.RayIntersectsPlane(ref this, ref plane, out distance);
return CollisionHelper.RayIntersectsPlane( ref this, ref plane, out distance );
}
/// <summary>
@ -112,9 +112,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -124,9 +124,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -136,10 +136,10 @@ namespace math
/// <param name="vertex2">The second 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>
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;
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>
@ -151,9 +151,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -165,9 +165,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -175,10 +175,10 @@ namespace math
/// </summary>
/// <param name="box">The box to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingBox box)
public bool Intersects( ref BoundingBox box )
{
float distance;
return CollisionHelper.RayIntersectsBox(ref this, ref box, out distance);
return CollisionHelper.RayIntersectsBox( ref this, ref box, out distance );
}
/// <summary>
@ -188,9 +188,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -200,9 +200,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -210,10 +210,10 @@ namespace math
/// </summary>
/// <param name="sphere">The sphere to test.</param>
/// <returns>Whether the two objects intersected.</returns>
public bool Intersects(ref BoundingSphere sphere)
public bool Intersects( ref BoundingSphere sphere )
{
float distance;
return CollisionHelper.RayIntersectsSphere(ref this, ref sphere, out distance);
return CollisionHelper.RayIntersectsSphere( ref this, ref sphere, out distance );
}
/// <summary>
@ -223,9 +223,9 @@ namespace math
/// <param name="distance">When the method completes, contains the distance of the intersection,
/// or 0 if there was no intersection.</param>
/// <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>
@ -235,9 +235,9 @@ namespace math
/// <param name="point">When the method completes, contains the point of intersection,
/// or <see cref="math.Vec3.Zero"/> if there was no intersection.</param>
/// <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>
@ -246,9 +246,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -257,9 +257,9 @@ namespace math
/// <param name="left">The first 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>
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>
@ -270,7 +270,7 @@ namespace math
/// </returns>
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>
@ -280,10 +280,10 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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),
Direction.ToString(format, CultureInfo.CurrentCulture));
return string.Format( CultureInfo.CurrentCulture, "Position:{0} Direction:{1}", Position.ToString( format, CultureInfo.CurrentCulture ),
Direction.ToString( format, CultureInfo.CurrentCulture ) );
}
/// <summary>
@ -293,9 +293,9 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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>
@ -306,17 +306,17 @@ namespace math
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </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),
Direction.ToString(format, formatProvider));
return string.Format( formatProvider, "Position:{0} Direction:{1}", Position.ToString( format, formatProvider ),
Direction.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -330,7 +330,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="math.Vec4"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Ray value)
public bool Equals( Ray value )
{
return Position == value.Position && Direction == value.Direction;
}
@ -342,15 +342,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((Ray)value);
return Equals( (Ray)value );
}
#if SlimDX1xInterop

View File

@ -31,9 +31,9 @@ namespace math
/// <summary>
/// A rectangle structure defining X,Y,Width,Height.
/// </summary>
[DataContract( Name = "Rectangle")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Rectangle" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Rectangle : IEquatable<Rectangle>
{
/// <summary>
@ -53,7 +53,7 @@ namespace math
/// <param name="y">The top.</param>
/// <param name="width">The width.</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.Y = y;
@ -142,7 +142,7 @@ namespace math
{
get
{
return new Point(X, Y);
return new Point( X, Y );
}
set
{
@ -162,7 +162,7 @@ namespace math
{
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
{
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
{
return new Size2(Width, Height);
return new Size2( Width, Height );
}
set
{
@ -202,37 +202,37 @@ namespace math
/// Gets the position of the top-left corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the top-right corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the bottom-left corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the bottom-right corner of the rectangle.
/// </summary>
/// <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>
/// <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>
/// <param name="offsetX">Change in the x-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;
Y += offsetY;
@ -241,7 +241,7 @@ namespace math
/// <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="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;
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>
/// <param name="x">The x-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>
/// <param name="value">The Point to evaluate.</param>
public bool Contains(Point value)
public bool Contains( Point value )
{
bool result;
Contains(ref value, out result);
Contains( ref value, out result );
return result;
}
/// <summary>Determines whether this rectangle contains a specified Point.</summary>
/// <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>
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>
/// <param name="value">The rectangle to evaluate.</param>
public bool Contains(Rectangle value)
public bool Contains( Rectangle value )
{
bool result;
Contains(ref value, out result);
Contains( ref value, out result );
return result;
}
/// <summary>Determines whether this rectangle entirely contains a specified rectangle.</summary>
/// <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>
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>
@ -297,9 +297,9 @@ namespace math
/// <param name="x">X 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>
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>
@ -307,9 +307,9 @@ namespace math
/// </summary>
/// <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>
public bool Contains(Vec2 vector2D)
public bool Contains( Vec2 vector2D )
{
return Contains(vector2D.X, vector2D.Y);
return Contains( vector2D.X, vector2D.Y );
}
/// <summary>
@ -317,17 +317,17 @@ namespace math
/// </summary>
/// <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>
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>
/// <param name="value">The rectangle to evaluate.</param>
public bool Intersects(Rectangle value)
public bool Intersects( Rectangle value )
{
bool result;
Intersects(ref value, out result);
Intersects( ref value, out result );
return result;
}
@ -336,9 +336,9 @@ namespace math
/// </summary>
/// <param name="value">The rectangle to evaluate</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>
@ -347,10 +347,10 @@ namespace math
/// <param name="value1">The first rectangle to compare.</param>
/// <param name="value2">The second rectangle to compare.</param>
/// <returns>The intersection rectangle.</returns>
public static Rectangle Intersect(Rectangle value1, Rectangle value2)
public static Rectangle Intersect( Rectangle value1, Rectangle value2 )
{
Rectangle result;
Intersect(ref value1, ref value2, out result);
Intersect( ref value1, ref value2, out result );
return result;
}
@ -358,33 +358,33 @@ namespace math
/// <param name="value1">The first 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>
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 newTop = (value1.Y > value2.Y) ? value1.Y : value2.Y;
int newRight = (value1.Right < value2.Right) ? value1.Right : value2.Right;
int newBottom = (value1.Bottom < value2.Bottom) ? value1.Bottom : value2.Bottom;
if ((newRight > newLeft) && (newBottom > newTop))
int newLeft = ( value1.X > value2.X ) ? value1.X : value2.X;
int newTop = ( value1.Y > value2.Y ) ? value1.Y : value2.Y;
int newRight = ( value1.Right < value2.Right ) ? value1.Right : value2.Right;
int newBottom = ( value1.Bottom < value2.Bottom ) ? value1.Bottom : value2.Bottom;
if( ( newRight > newLeft ) && ( newBottom > newTop ) )
{
result = new Rectangle(newLeft, newTop, newRight - newLeft, newBottom - newTop);
result = new Rectangle( newLeft, newTop, newRight - newLeft, newBottom - newTop );
}
else
{
result = Empty;
}
}
/// <summary>
/// Creates a new rectangle that incorporate the provided point to the given rectangle.
/// </summary>
/// <param name="rectangle">The original rectangle.</param>
/// <param name="point">The point to incorporate.</param>
/// <returns>The union rectangle.</returns>
public static Rectangle Union(Rectangle rectangle, Int2 point)
public static Rectangle Union( Rectangle rectangle, Int2 point )
{
Rectangle result;
var rect = new Rectangle(point.X, point.Y, 1, 1);
Union(ref rectangle, ref rect, out result);
var rect = new Rectangle( point.X, point.Y, 1, 1 );
Union( ref rectangle, ref rect, out result );
return result;
}
@ -394,10 +394,10 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param>
/// <returns>The union rectangle.</returns>
public static Rectangle Union(Rectangle value1, Rectangle value2)
public static Rectangle Union( Rectangle value1, Rectangle value2 )
{
Rectangle result;
Union(ref value1, ref value2, out result);
Union( ref value1, ref value2, out result );
return result;
}
@ -407,13 +407,13 @@ namespace math
/// <param name="value1">The first 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>
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 right = Math.Max(value1.Right, value2.Right);
var top = Math.Min(value1.Top, value2.Top);
var bottom = Math.Max(value1.Bottom, value2.Bottom);
result = new Rectangle(left, top, right - left, bottom - top);
var left = Math.Min( value1.Left, value2.Left );
var right = Math.Max( value1.Right, value2.Right );
var top = Math.Min( value1.Top, value2.Top );
var bottom = Math.Max( value1.Bottom, value2.Bottom );
result = new Rectangle( left, top, right - left, bottom - top );
}
/// <summary>
@ -423,11 +423,13 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Rectangle)) return false;
return Equals((Rectangle)obj);
if( ReferenceEquals( null, obj ) )
return false;
if( obj.GetType() != typeof( Rectangle ) )
return false;
return Equals( (Rectangle)obj );
}
/// <summary>
@ -437,7 +439,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="Rectangle"/> is equal to this instance; otherwise, <c>false</c>.
/// </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;
}
@ -453,9 +455,9 @@ namespace math
unchecked
{
int result = X;
result = (result * 397) ^ Y;
result = (result * 397) ^ Width;
result = (result * 397) ^ Height;
result = ( result * 397 ) ^ Y;
result = ( result * 397 ) ^ Width;
result = ( result * 397 ) ^ Height;
return result;
}
}
@ -466,9 +468,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -477,9 +479,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -488,15 +490,15 @@ namespace math
/// <remarks>Performs direct converstion from int to float.</remarks>
/// <param name="value">The source <see cref="Rectangle"/> value.</param>
/// <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/>
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>
/// Define a RectangleF.
/// </summary>
[DataContract( Name = "RectangleF")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "RectangleF" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct RectangleF : IEquatable<RectangleF>
{
/// <summary>
@ -53,7 +53,7 @@ namespace math
/// <param name="y">The top.</param>
/// <param name="width">The width.</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.Y = y;
@ -151,7 +151,7 @@ namespace math
{
get
{
return new Vec2(X, Y);
return new Vec2( X, Y );
}
set
{
@ -171,7 +171,7 @@ namespace math
{
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
{
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
{
return new Size2F(Width, Height);
return new Size2F( Width, Height );
}
set
{
@ -211,44 +211,44 @@ namespace math
/// Gets the position of the top-left corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the top-right corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the bottom-left corner of the rectangle.
/// </summary>
/// <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>
/// Gets the position of the bottom-right corner of the rectangle.
/// </summary>
/// <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>
/// <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>
/// <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>
/// <param name="offsetX">Change in the x-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;
Y += offsetY;
@ -257,7 +257,7 @@ namespace math
/// <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="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;
Y -= verticalAmount;
@ -268,24 +268,24 @@ namespace math
/// <summary>Determines whether this rectangle contains a specified Point.</summary>
/// <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>
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>
/// <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>
/// <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>
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>
@ -294,9 +294,9 @@ namespace math
/// <param name="x">X 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>
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>
@ -304,9 +304,9 @@ namespace math
/// </summary>
/// <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>
public bool Contains(Vec2 vector2D)
public bool Contains( Vec2 vector2D )
{
return Contains(vector2D.X, vector2D.Y);
return Contains( vector2D.X, vector2D.Y );
}
/// <summary>
@ -314,9 +314,9 @@ namespace math
/// </summary>
/// <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>
public bool Contains(Int2 int2)
public bool Contains( Int2 int2 )
{
return Contains(int2.X, int2.Y);
return Contains( int2.X, int2.Y );
}
/// <summary>
@ -324,17 +324,17 @@ namespace math
/// </summary>
/// <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>
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>
/// <param name="value">The rectangle to evaluate.</param>
public bool Intersects(RectangleF value)
public bool Intersects( RectangleF value )
{
bool result;
Intersects(ref value, out result);
Intersects( ref value, out result );
return result;
}
@ -343,9 +343,9 @@ namespace math
/// </summary>
/// <param name="value">The rectangle to evaluate</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>
@ -354,10 +354,10 @@ namespace math
/// <param name="value1">The first Rectangle to compare.</param>
/// <param name="value2">The second Rectangle to compare.</param>
/// <returns>The intersection rectangle.</returns>
public static RectangleF Intersect(RectangleF value1, RectangleF value2)
public static RectangleF Intersect( RectangleF value1, RectangleF value2 )
{
RectangleF result;
Intersect(ref value1, ref value2, out result);
Intersect( ref value1, ref value2, out result );
return result;
}
@ -365,15 +365,15 @@ namespace math
/// <param name="value1">The first 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>
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 newTop = (value1.Y > value2.Y) ? value1.Y : value2.Y;
float newRight = (value1.Right < value2.Right) ? value1.Right : value2.Right;
float newBottom = (value1.Bottom < value2.Bottom) ? value1.Bottom : value2.Bottom;
if ((newRight > newLeft) && (newBottom > newTop))
float newLeft = ( value1.X > value2.X ) ? value1.X : value2.X;
float newTop = ( value1.Y > value2.Y ) ? value1.Y : value2.Y;
float newRight = ( value1.Right < value2.Right ) ? value1.Right : value2.Right;
float newBottom = ( value1.Bottom < value2.Bottom ) ? value1.Bottom : value2.Bottom;
if( ( newRight > newLeft ) && ( newBottom > newTop ) )
{
result = new RectangleF(newLeft, newTop, newRight - newLeft, newBottom - newTop);
result = new RectangleF( newLeft, newTop, newRight - newLeft, newBottom - newTop );
}
else
{
@ -387,10 +387,10 @@ namespace math
/// <param name="value1">The first rectangle to contain.</param>
/// <param name="value2">The second rectangle to contain.</param>
/// <returns>The union rectangle.</returns>
public static RectangleF Union(RectangleF value1, RectangleF value2)
public static RectangleF Union( RectangleF value1, RectangleF value2 )
{
RectangleF result;
Union(ref value1, ref value2, out result);
Union( ref value1, ref value2, out result );
return result;
}
@ -400,13 +400,13 @@ namespace math
/// <param name="value1">The first 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>
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 right = Math.Max(value1.Right, value2.Right);
var top = Math.Min(value1.Top, value2.Top);
var bottom = Math.Max(value1.Bottom, value2.Bottom);
result = new RectangleF(left, top, right - left, bottom - top);
var left = Math.Min( value1.Left, value2.Left );
var right = Math.Max( value1.Right, value2.Right );
var top = Math.Min( value1.Top, value2.Top );
var bottom = Math.Max( value1.Bottom, value2.Bottom );
result = new RectangleF( left, top, right - left, bottom - top );
}
/// <summary>
@ -416,20 +416,22 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(RectangleF)) return false;
return Equals((RectangleF)obj);
if( ReferenceEquals( null, obj ) )
return false;
if( obj.GetType() != typeof( RectangleF ) )
return false;
return Equals( (RectangleF)obj );
}
/// <inheritdoc/>
public bool Equals(RectangleF other)
public bool Equals( RectangleF other )
{
return MathUtil.NearEqual(other.Left, Left) &&
MathUtil.NearEqual(other.Right, Right) &&
MathUtil.NearEqual(other.Top, Top) &&
MathUtil.NearEqual(other.Bottom, Bottom);
return MathUtil.NearEqual( other.Left, Left ) &&
MathUtil.NearEqual( other.Right, Right ) &&
MathUtil.NearEqual( other.Top, Top ) &&
MathUtil.NearEqual( other.Bottom, Bottom );
}
/// <summary>
@ -443,9 +445,9 @@ namespace math
unchecked
{
int result = X.GetHashCode();
result = (result * 397) ^ Y.GetHashCode();
result = (result * 397) ^ Width.GetHashCode();
result = (result * 397) ^ Height.GetHashCode();
result = ( result * 397 ) ^ Y.GetHashCode();
result = ( result * 397 ) ^ Width.GetHashCode();
result = ( result * 397 ) ^ Height.GetHashCode();
return result;
}
}
@ -456,9 +458,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -467,9 +469,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -478,15 +480,15 @@ namespace math
/// <remarks>Performs direct float to int conversion, any fractional data is truncated.</remarks>
/// <param name="value">The source <see cref="RectangleF"/> value.</param>
/// <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/>
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>
/// Defines a 2D rectangular size (width,height).
/// </summary>
[DataContract( Name = "!Size2")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "!Size2" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Size2 : IEquatable<Size2>
{
/// <summary>
/// A zero size with (width, height) = (0,0)
/// </summary>
public static readonly Size2 Zero = new Size2(0, 0);
public static readonly Size2 Zero = new Size2( 0, 0 );
/// <summary>
/// A zero size with (width, height) = (0,0)
@ -50,7 +50,7 @@ namespace math
/// </summary>
/// <param name="width">The x.</param>
/// <param name="height">The y.</param>
public Size2(int width, int height)
public Size2( int width, int height )
{
Width = width;
Height = height;
@ -75,17 +75,19 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Size2 other)
public bool Equals( Size2 other )
{
return other.Width == Width && other.Height == Height;
}
/// <inheritdoc/>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Size2)) return false;
return Equals((Size2)obj);
if( ReferenceEquals( null, obj ) )
return false;
if( obj.GetType() != typeof( Size2 ) )
return false;
return Equals( (Size2)obj );
}
/// <inheritdoc/>
@ -93,7 +95,7 @@ namespace math
{
unchecked
{
return (Width * 397) ^ Height;
return ( Width * 397 ) ^ Height;
}
}
@ -105,9 +107,9 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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>
@ -118,15 +120,15 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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/>
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>
/// Defines a 2D rectangular size (width,height).
/// </summary>
[DataContract( Name = "Size2F")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[DataContract( Name = "Size2F" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct Size2F : IEquatable<Size2F>
{
/// <summary>
/// A zero size with (width, height) = (0,0)
/// </summary>
public static readonly Size2F Zero = new Size2F(0, 0);
public static readonly Size2F Zero = new Size2F( 0, 0 );
/// <summary>
/// A zero size with (width, height) = (0,0)
@ -50,7 +50,7 @@ namespace math
/// </summary>
/// <param name="width">The x.</param>
/// <param name="height">The y.</param>
public Size2F(float width, float height)
public Size2F( float width, float height )
{
Width = width;
Height = height;
@ -75,17 +75,19 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Size2F other)
public bool Equals( Size2F other )
{
return other.Width == Width && other.Height == Height;
}
/// <inheritdoc/>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Size2F)) return false;
return Equals((Size2F)obj);
if( ReferenceEquals( null, obj ) )
return false;
if( obj.GetType() != typeof( Size2F ) )
return false;
return Equals( (Size2F)obj );
}
/// <inheritdoc/>
@ -93,7 +95,7 @@ namespace math
{
unchecked
{
return (Width.GetHashCode() * 397) ^ Height.GetHashCode();
return ( Width.GetHashCode() * 397 ) ^ Height.GetHashCode();
}
}
@ -105,9 +107,9 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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>
@ -118,15 +120,15 @@ namespace math
/// <returns>
/// The result of the operator.
/// </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/>
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>
/// Structure providing Width, Height and Depth.
/// </summary>
[DataContract( Name = "!Size3")]
[DataStyle(DataStyle.Compact)]
[StructLayout(LayoutKind.Sequential)]
[DataContract( Name = "!Size3" )]
[DataStyle( DataStyle.Compact )]
[StructLayout( LayoutKind.Sequential )]
public struct Size3 : IEquatable<Size3>, IComparable<Size3>
{
/// <summary>
/// A zero size with (width, height, depth) = (0,0,0)
/// </summary>
public static readonly Size3 Zero = new Size3(0, 0, 0);
public static readonly Size3 Zero = new Size3( 0, 0, 0 );
/// <summary>
/// A one size with (width, height, depth) = (1,1,1)
/// </summary>
public static readonly Size3 One = new Size3(1, 1, 1);
public static readonly Size3 One = new Size3( 1, 1, 1 );
/// <summary>
/// A zero size with (width, height, depth) = (0,0,0)
@ -56,7 +56,7 @@ namespace math
/// <param name="width">The x.</param>
/// <param name="height">The y.</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;
Height = height;
@ -93,16 +93,17 @@ namespace math
}
/// <inheritdoc/>
public bool Equals(Size3 other)
public bool Equals( Size3 other )
{
return Width == other.Width && Height == other.Height && Depth == other.Depth;
}
/// <inheritdoc/>
public override bool Equals(object obj)
public override bool Equals( object obj )
{
if (ReferenceEquals(null, obj)) return false;
return obj is Size3 && Equals((Size3)obj);
if( ReferenceEquals( null, obj ) )
return false;
return obj is Size3 && Equals( (Size3)obj );
}
/// <inheritdoc/>
@ -111,22 +112,22 @@ namespace math
unchecked
{
int hashCode = Width;
hashCode = (hashCode * 397) ^ Height;
hashCode = (hashCode * 397) ^ Depth;
hashCode = ( hashCode * 397 ) ^ Height;
hashCode = ( hashCode * 397 ) ^ Depth;
return hashCode;
}
}
/// <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/>
public override string ToString()
{
return string.Format("({0},{1},{2})", Width, Height, Depth);
return string.Format( "({0},{1},{2})", Width, Height, Depth );
}
/// <summary>
@ -135,9 +136,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -146,9 +147,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -157,9 +158,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -168,9 +169,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -179,9 +180,9 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
@ -190,23 +191,23 @@ namespace math
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <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>
/// Calculates the next up mip-level (*2) of this size.
/// </summary>
/// <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>
@ -214,14 +215,14 @@ namespace math
/// </summary>
/// <param name="count">The count.</param>
/// <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>
@ -229,7 +230,7 @@ namespace math
/// </summary>
/// <param name="direction">The direction &lt; 0 then <see cref="Down2"/>, &gt; 0 then <see cref="Up2"/>, else this unchanged.</param>
/// <returns>Size3.</returns>
public Size3 Mip(int direction)
public Size3 Mip( int direction )
{
return direction == 0 ? this : direction < 0 ? Down2() : Up2();
}

View File

@ -16,14 +16,14 @@ namespace math
/// A representation of a sphere of values via Spherical Harmonics (SH).
/// </summary>
/// <typeparam name="TDataType">The type of data contained by the sphere</typeparam>
[DataContract( Name = "SphericalHarmonicsGeneric")]
[DataContract( Name = "SphericalHarmonicsGeneric" )]
public abstract class SphericalHarmonics<TDataType>
{
/// <summary>
/// The maximum order supported.
/// </summary>
public const int MaximumOrder = 5;
private int order;
/// <summary>
@ -35,10 +35,10 @@ namespace math
get { return order; }
internal set
{
if (order>5)
throw new NotSupportedException("Only orders inferior or equal to 5 are supported");
order = Math.Max(1, value);
if( order > 5 )
throw new NotSupportedException( "Only orders inferior or equal to 5 are supported" );
order = Math.Max( 1, value );
}
}
@ -59,7 +59,7 @@ namespace math
/// Initializes a new instance of the <see cref="SphericalHarmonics{TDataType}"/> class.
/// </summary>
/// <param name="order">The order of the harmonics</param>
protected SphericalHarmonics(int order)
protected SphericalHarmonics( int order )
{
this.order = order;
Coefficients = new TDataType[order * order];
@ -70,7 +70,7 @@ namespace math
/// </summary>
/// <param name="direction">The direction</param>
/// <returns>The value of the spherical harmonics in the direction</returns>
public abstract TDataType Evaluate(Vec3 direction);
public abstract TDataType Evaluate( Vec3 direction );
/// <summary>
/// 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
{
CheckIndicesValidity(l, m, order);
return Coefficients[LmToCoefficientIndex(l, m)];
CheckIndicesValidity( l, m, order );
return Coefficients[LmToCoefficientIndex( l, m )];
}
set
{
CheckIndicesValidity(l, m, order);
Coefficients[LmToCoefficientIndex(l, m)] = value;
CheckIndicesValidity( l, m, order );
Coefficients[LmToCoefficientIndex( l, m )] = value;
}
}
// 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
{
if (l > maxOrder - 1)
throw new IndexOutOfRangeException($"'l' parameter should be between '0' and '{maxOrder-1}' (order-1).");
if( l > maxOrder - 1 )
throw new IndexOutOfRangeException( $"'l' parameter should be between '0' and '{maxOrder - 1}' (order-1)." );
if (Math.Abs(m) > l)
throw new IndexOutOfRangeException("'m' parameter should be between '-l' and '+l'.");
if( Math.Abs( m ) > 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;
}
@ -112,7 +112,7 @@ namespace math
/// <summary>
/// A spherical harmonics representation of a cubemap.
/// </summary>
[DataContract( Name = "SphericalHarmonics")]
[DataContract( Name = "SphericalHarmonics" )]
public class SphericalHarmonics : SphericalHarmonics<Color3>
{
private readonly float[] baseValues;
@ -120,7 +120,7 @@ namespace math
private const float Pi4 = 4 * MathUtil.Pi;
private const float Pi16 = 16 * 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>
/// Base coefficients for SH.
@ -169,8 +169,8 @@ namespace math
/// Initializes a new instance of the <see cref="SphericalHarmonics"/> class.
/// </summary>
/// <param name="order">The order of the harmonics</param>
public SphericalHarmonics(int order)
: base(order)
public SphericalHarmonics( int order )
: base( order )
{
baseValues = new float[order * order];
}
@ -180,60 +180,60 @@ namespace math
/// </summary>
/// <param name="direction">The direction to evaluate.</param>
/// <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 y = direction.Y;
var z = direction.Z;
var x2 = x*x;
var y2 = y*y;
var z2 = z*z;
var x2 = x * x;
var y2 = y * y;
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 y4 = (float)Math.Pow(y, 4.0);
var z4 = (float)Math.Pow(z, 4.0);
var x4 = (float)Math.Pow( x, 4.0 );
var y4 = (float)Math.Pow( y, 4.0 );
var z4 = (float)Math.Pow( z, 4.0 );
//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[ 2] = (float)Math.Sqrt(3/Pi4)*z;
baseValues[ 3] = -(float)Math.Sqrt(3/Pi4)*x;
if (Order > 2)
baseValues[1] = -(float)Math.Sqrt( 3 / Pi4 ) * y;
baseValues[2] = (float)Math.Sqrt( 3 / Pi4 ) * z;
baseValues[3] = -(float)Math.Sqrt( 3 / Pi4 ) * x;
if( Order > 2 )
{
baseValues[ 4] = (float)Math.Sqrt(15/Pi4)*y*x;
baseValues[ 5] = -(float)Math.Sqrt(15/Pi4)*y*z;
baseValues[ 6] = (float)Math.Sqrt(5/Pi16)*(3*z2-1);
baseValues[ 7] = -(float)Math.Sqrt(15/Pi4)*x*z;
baseValues[ 8] = (float)Math.Sqrt(15/Pi16)*(x2-y2);
if (Order > 3)
baseValues[4] = (float)Math.Sqrt( 15 / Pi4 ) * y * x;
baseValues[5] = -(float)Math.Sqrt( 15 / Pi4 ) * y * z;
baseValues[6] = (float)Math.Sqrt( 5 / Pi16 ) * ( 3 * z2 - 1 );
baseValues[7] = -(float)Math.Sqrt( 15 / Pi4 ) * x * z;
baseValues[8] = (float)Math.Sqrt( 15 / Pi16 ) * ( x2 - y2 );
if( Order > 3 )
{
baseValues[ 9] = -(float)Math.Sqrt( 70/Pi64)*y*(3*x2-y2);
baseValues[10] = (float)Math.Sqrt(105/ Pi4)*y*x*z;
baseValues[11] = -(float)Math.Sqrt( 42/Pi64)*y*(-1+5*z2);
baseValues[12] = (float)Math.Sqrt( 7/Pi16)*(5*z3-3*z);
baseValues[13] = -(float)Math.Sqrt( 42/Pi64)*x*(-1+5*z2);
baseValues[14] = (float)Math.Sqrt(105/Pi16)*(x2-y2)*z;
baseValues[15] = -(float)Math.Sqrt( 70/Pi64)*x*(x2-3*y2);
if (Order > 4)
baseValues[9] = -(float)Math.Sqrt( 70 / Pi64 ) * y * ( 3 * x2 - y2 );
baseValues[10] = (float)Math.Sqrt( 105 / Pi4 ) * y * x * z;
baseValues[11] = -(float)Math.Sqrt( 42 / Pi64 ) * y * ( -1 + 5 * z2 );
baseValues[12] = (float)Math.Sqrt( 7 / Pi16 ) * ( 5 * z3 - 3 * z );
baseValues[13] = -(float)Math.Sqrt( 42 / Pi64 ) * x * ( -1 + 5 * z2 );
baseValues[14] = (float)Math.Sqrt( 105 / Pi16 ) * ( x2 - y2 ) * z;
baseValues[15] = -(float)Math.Sqrt( 70 / Pi64 ) * x * ( x2 - 3 * y2 );
if( Order > 4 )
{
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[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[20] = (105*z4-90*z2+9)/(16*SqrtPi);
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[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[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[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[20] = ( 105 * z4 - 90 * z2 + 9 ) / ( 16 * SqrtPi );
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[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 );
}
}
}
@ -241,7 +241,7 @@ namespace math
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];
return data;

View File

@ -2,17 +2,17 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
//
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -31,7 +31,7 @@ namespace math
/// Represents a four dimensional mathematical vector.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
[StructLayout( LayoutKind.Sequential, Pack = 4 )]
public struct UInt4 : IEquatable<UInt4>, IFormattable
{
/// <summary>
@ -47,27 +47,27 @@ namespace math
/// <summary>
/// The X unit <see cref = "UInt4" /> (1, 0, 0, 0).
/// </summary>
public static readonly UInt4 UnitX = new UInt4(1, 0, 0, 0);
public static readonly UInt4 UnitX = new UInt4( 1, 0, 0, 0 );
/// <summary>
/// The Y unit <see cref = "UInt4" /> (0, 1, 0, 0).
/// </summary>
public static readonly UInt4 UnitY = new UInt4(0, 1, 0, 0);
public static readonly UInt4 UnitY = new UInt4( 0, 1, 0, 0 );
/// <summary>
/// The Z unit <see cref = "UInt4" /> (0, 0, 1, 0).
/// </summary>
public static readonly UInt4 UnitZ = new UInt4(0, 0, 1, 0);
public static readonly UInt4 UnitZ = new UInt4( 0, 0, 1, 0 );
/// <summary>
/// The W unit <see cref = "UInt4" /> (0, 0, 0, 1).
/// </summary>
public static readonly UInt4 UnitW = new UInt4(0, 0, 0, 1);
public static readonly UInt4 UnitW = new UInt4( 0, 0, 0, 1 );
/// <summary>
/// A <see cref = "UInt4" /> with all of its components set to one.
/// </summary>
public static readonly UInt4 One = new UInt4(1, 1, 1, 1);
public static readonly UInt4 One = new UInt4( 1, 1, 1, 1 );
/// <summary>
/// The X component of the vector.
@ -93,7 +93,7 @@ namespace math
/// Initializes a new instance of the <see cref = "UInt4" /> struct.
/// </summary>
/// <param name = "value">The value that will be assigned to all components.</param>
public UInt4(uint value)
public UInt4( uint value )
{
X = value;
Y = value;
@ -108,7 +108,7 @@ namespace math
/// <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 = "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;
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>
/// <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>
public UInt4(uint[] values)
public UInt4( uint[] values )
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length != 4)
throw new ArgumentOutOfRangeException("values", "There must be four and only four input values for UInt4.");
if( values == null )
throw new ArgumentNullException( "values" );
if( values.Length != 4 )
throw new ArgumentOutOfRangeException( "values", "There must be four and only four input values for UInt4." );
X = values[0];
Y = values[1];
@ -146,7 +146,7 @@ namespace math
{
get
{
switch (index)
switch( index )
{
case 0:
return X;
@ -158,12 +158,12 @@ namespace math
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
{
switch (index)
switch( index )
{
case 0:
X = value;
@ -178,7 +178,7 @@ namespace math
W = value;
break;
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 = "right">The second vector to add.</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>
@ -209,9 +209,9 @@ namespace math
/// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param>
/// <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>
@ -220,9 +220,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -231,9 +231,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param>
/// <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>
@ -242,9 +242,9 @@ namespace math
/// <param name = "value">The vector to scale.</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>
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>
@ -253,9 +253,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -264,9 +264,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -275,9 +275,9 @@ namespace math
/// <param name = "left">The first vector to modulate.</param>
/// <param name = "right">The second vector to modulate.</param>
/// <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>
@ -286,9 +286,9 @@ namespace math
/// <param name = "value">The vector to scale.</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>
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>
@ -297,9 +297,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -309,25 +309,25 @@ namespace math
/// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum 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;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
x = ( x > max.X ) ? max.X : x;
x = ( x < min.X ) ? min.X : x;
uint y = value.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
y = ( y > max.Y ) ? max.Y : y;
y = ( y < min.Y ) ? min.Y : y;
uint z = value.Z;
z = (z > max.Z) ? max.Z : z;
z = (z < min.Z) ? min.Z : z;
z = ( z > max.Z ) ? max.Z : z;
z = ( z < min.Z ) ? min.Z : z;
uint w = value.W;
w = (w > max.W) ? max.W : w;
w = (w < min.W) ? min.W : w;
w = ( w > max.W ) ? max.W : w;
w = ( w < min.W ) ? min.W : w;
result = new UInt4(x, y, z, w);
result = new UInt4( x, y, z, w );
}
/// <summary>
@ -337,10 +337,10 @@ namespace math
/// <param name = "min">The minimum value.</param>
/// <param name = "max">The maximum value.</param>
/// <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;
Clamp(ref value, ref min, ref max, out result);
Clamp( ref value, ref min, ref max, out result );
return result;
}
@ -350,12 +350,12 @@ namespace math
/// <param name = "left">The first 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>
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.Y = (left.Y > right.Y) ? left.Y : right.Y;
result.Z = (left.Z > right.Z) ? left.Z : right.Z;
result.W = (left.W > right.W) ? left.W : right.W;
result.X = ( left.X > right.X ) ? left.X : right.X;
result.Y = ( left.Y > right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z > right.Z ) ? left.Z : right.Z;
result.W = ( left.W > right.W ) ? left.W : right.W;
}
/// <summary>
@ -364,10 +364,10 @@ namespace math
/// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param>
/// <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;
Max(ref left, ref right, out result);
Max( ref left, ref right, out result );
return result;
}
@ -377,12 +377,12 @@ namespace math
/// <param name = "left">The first 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>
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.Y = (left.Y < right.Y) ? left.Y : right.Y;
result.Z = (left.Z < right.Z) ? left.Z : right.Z;
result.W = (left.W < right.W) ? left.W : right.W;
result.X = ( left.X < right.X ) ? left.X : right.X;
result.Y = ( left.Y < right.Y ) ? left.Y : right.Y;
result.Z = ( left.Z < right.Z ) ? left.Z : right.Z;
result.W = ( left.W < right.W ) ? left.W : right.W;
}
/// <summary>
@ -391,10 +391,10 @@ namespace math
/// <param name = "left">The first source vector.</param>
/// <param name = "right">The second source vector.</param>
/// <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;
Min(ref left, ref right, out result);
Min( ref left, ref right, out result );
return result;
}
@ -404,9 +404,9 @@ namespace math
/// <param name = "left">The first vector to add.</param>
/// <param name = "right">The second vector to add.</param>
/// <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>
@ -414,7 +414,7 @@ namespace math
/// </summary>
/// <param name = "value">The vector to assert (unchange).</param>
/// <returns>The asserted (unchanged) vector.</returns>
public static UInt4 operator +(UInt4 value)
public static UInt4 operator +( UInt4 value )
{
return value;
}
@ -425,9 +425,9 @@ namespace math
/// <param name = "left">The first vector to subtract.</param>
/// <param name = "right">The second vector to subtract.</param>
/// <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>
@ -436,9 +436,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -447,9 +447,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -458,9 +458,9 @@ namespace math
/// <param name = "value">The vector to scale.</param>
/// <param name = "scale">The amount by which to scale the vector.</param>
/// <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>
@ -469,9 +469,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -480,9 +480,9 @@ namespace math
/// <param name = "left">The first 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>
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>
@ -490,9 +490,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -500,9 +500,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -510,9 +510,9 @@ namespace math
/// </summary>
/// <param name = "value">The value.</param>
/// <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>
@ -523,7 +523,7 @@ namespace math
/// </returns>
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>
@ -533,16 +533,16 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </returns>
public string ToString(string format)
public string ToString( string format )
{
if (format == null)
if( format == null )
return ToString();
return string.Format(CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString(format, CultureInfo.CurrentCulture),
Y.ToString(format, CultureInfo.CurrentCulture),
Z.ToString(format, CultureInfo.CurrentCulture),
W.ToString(format, CultureInfo.CurrentCulture));
return string.Format( CultureInfo.CurrentCulture, "X:{0} Y:{1} Z:{2} W:{3}",
X.ToString( format, CultureInfo.CurrentCulture ),
Y.ToString( format, CultureInfo.CurrentCulture ),
Z.ToString( format, CultureInfo.CurrentCulture ),
W.ToString( format, CultureInfo.CurrentCulture ) );
}
/// <summary>
@ -552,9 +552,9 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </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>
@ -565,21 +565,21 @@ namespace math
/// <returns>
/// A <see cref = "string" /> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
public string ToString( string format, IFormatProvider formatProvider )
{
if (format == null)
ToString(formatProvider);
if( format == null )
ToString( 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),
W.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 ),
W.ToString( format, formatProvider ) );
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
@ -593,7 +593,7 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref = "UInt4" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(UInt4 other)
public bool Equals( UInt4 other )
{
return other.X == X && other.Y == Y && other.Z == Z && other.W == W;
}
@ -605,15 +605,15 @@ namespace math
/// <returns>
/// <c>true</c> if the specified <see cref = "object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
public override bool Equals( object value )
{
if (value == null)
if( value == null )
return false;
if (value.GetType() != GetType())
if( value.GetType() != GetType() )
return false;
return Equals((UInt4)value);
return Equals( (UInt4)value );
}
/// <summary>
@ -621,9 +621,9 @@ namespace math
/// </summary>
/// <param name="input">The input.</param>
/// <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>
@ -631,7 +631,7 @@ namespace math
/// </summary>
/// <param name="input">The input.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator uint[](UInt4 input)
public static implicit operator uint[]( UInt4 input )
{
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.
/// </summary>
/// <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>
/// Return the X/Y components of the vector.
/// </summary>
/// <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>
/// Return the X/Z components of the vector.
/// </summary>
/// <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>
/// Return the Y/Z components of the vector.
/// </summary>
/// <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>
/// Return the X/Y components of the vector.
/// </summary>
/// <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>
/// Return the X/Y/Z components of the vector.
/// </summary>
/// <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 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 ToDeg( float rad ) => (float)( 180.0 / Math.PI ) * rad;
static public float ToRad( float deg ) => (float)( Math.PI / 180.0 ) * deg;
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 )
{
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;
}
@ -47,28 +47,28 @@ namespace math
}
//Tracked these down in Desmos
static public float s_a = 0.0f;
static public float s_b = 0.155f;
static public float s_c = 1.03f;
static public float s_d = 6.13f;
static public float s_a = 0.0f;
static public float s_b = 0.155f;
static public float s_c = 1.03f;
static public float s_d = 6.13f;
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 )
{
var vv = v * v;
var vvv = vv * v;
var vv = v * v;
var vvv = vv * 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;
}
static public float s_p = 0.37f;
static public float s_o = 0.15f;
static public float s_m = 2.11f;
static public float s_p = 0.37f;
static public float s_o = 0.15f;
static public float s_m = 2.11f;
static public float s_n = -0.57f;
static public float PerlinToContinent( float h )
@ -93,7 +93,7 @@ namespace math
{
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;

View File

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

View File

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

View File

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

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